File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.12.2.44: download - view: text, annotated - select for diffs
Mon Oct 8 19:12:29 2018 UTC (5 years, 7 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.596.2.12: preferred, unified
- For 2.11
  - Backport 1.751, 1.752.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.12.2.44 2018/10/08 19:12:29 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: 
 2057:     if (!&canview($usec)) {
 2058:         $request->print(
 2059:             '<span class="LC_warning">'.
 2060:             &mt('Unable to view requested student.').
 2061:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2062:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2063:             '</span>');
 2064: 	$request->print(&show_grading_menu_form($symb));
 2065: 	return;
 2066:     }
 2067: 
 2068:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2069:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2070:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2071:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2072:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2073: 	'" src="'.$request->dir_config('lonIconsURL').
 2074: 	'/check.gif" height="16" border="0" />';
 2075: 
 2076:     # header info
 2077:     if ($counter == 0) {
 2078: 	&sub_page_js($request);
 2079: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2080: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2081: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2082: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2083: 	    &download_all_link($request, $symb);
 2084: 	}
 2085: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2086: 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
 2087: 
 2088: 	# option to display problem, only once else it cause problems 
 2089:         # with the form later since the problem has a form.
 2090: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2091: 	    my $mode;
 2092: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2093: 		$mode='both';
 2094: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2095: 		$mode='text';
 2096: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2097: 		$mode='answer';
 2098: 	    }
 2099: 	    &Apache::lonxml::clear_problem_counter();
 2100: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2101: 	}
 2102: 
 2103: 	# kwclr is the only variable that is guaranteed not to be blank 
 2104:         # if this subroutine has been called once.
 2105: 	my %keyhash = ();
 2106: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2107: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2108: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2109: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2110: 
 2111: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2112: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2113: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2114: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2115: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2116: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2117: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2118: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2119: 	}
 2120: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2121: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2122: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2123: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2124: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2125: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2126: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2127: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2128: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2129: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2130: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2131: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2132: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2133: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2134: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2135: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2136: 			&build_section_inputs().
 2137: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2138: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2139: 			'<input type="hidden" name="NCT"'.
 2140: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2141: 	if ($env{'form.handgrade'} eq 'yes') {
 2142: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2143: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2144: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2145: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2146: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2147: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2148: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2149: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2150: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2151: 	    }
 2152: 	}
 2153: 	
 2154: 	my ($cts,$prnmsg) = (1,'');
 2155: 	while ($cts <= $env{'form.savemsgN'}) {
 2156: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2157: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2158: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2159: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2160: 		'" />'."\n".
 2161: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2162: 	    $cts++;
 2163: 	}
 2164: 	$request->print($prnmsg);
 2165: 
 2166: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2167: 
 2168:             my %lt = &Apache::lonlocal::texthash(
 2169:                           keyh => 'Keyword Highlighting for Essays',
 2170:                           keyw => 'Keyword Options',
 2171:                           list => 'List',
 2172:                           past => 'Paste Selection to List',
 2173:                           high => 'Highlight Attribute',
 2174:                      );
 2175: #
 2176: # Print out the keyword options line
 2177: #
 2178:             $request->print(
 2179:                 '<div class="LC_columnSection">'
 2180:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2181:                .&Apache::lonhtmlcommon::funclist_from_array(
 2182:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2183:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2184:  class="page">'.$lt{'past'}.'</a>',
 2185:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2186:                     {legend => $lt{'keyw'}})
 2187:                .'</fieldset></div>'
 2188:             );
 2189: 
 2190: #
 2191: # Load the other essays for similarity check
 2192: #
 2193:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2194: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2195: 	    $apath=&escape($apath);
 2196: 	    $apath=~s/\W/\_/gs;
 2197:             &init_old_essays($symb,$apath,$adom,$aname);
 2198:         }
 2199:     }
 2200: 
 2201: # This is where output for one specific student would start
 2202:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2203:     $request->print(
 2204:         "\n\n"
 2205:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2206:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2207:        ."\n"
 2208:     );
 2209: 
 2210:     # Show additional functions if allowed
 2211:     if ($perm{'vgr'}) {
 2212:         $request->print(
 2213:             &Apache::loncommon::track_student_link(
 2214:                 'View recent activity',
 2215:                 $uname,$udom,'check')
 2216:            .' '
 2217:         );
 2218:     }
 2219:     if ($perm{'opa'}) {
 2220:         $request->print(
 2221:             &Apache::loncommon::pprmlink(
 2222:                 &mt('Set/Change parameters'),
 2223:                 $uname,$udom,$symb,'check'));
 2224:     }
 2225: 
 2226:     # Show Problem
 2227:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2228: 	my $mode;
 2229: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2230: 	    $mode='both';
 2231: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2232: 	    $mode='text';
 2233: 	} elsif ($env{'form.vAns'} eq 'all') {
 2234: 	    $mode='answer';
 2235: 	}
 2236: 	&Apache::lonxml::clear_problem_counter();
 2237: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2238:     }
 2239: 
 2240:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2241:     my $res_error;
 2242:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2243:     if ($res_error) {
 2244:         $request->print(&navmap_errormsg());
 2245:         return;
 2246:     }
 2247: 
 2248:     # Display student info
 2249:     $request->print(($counter == 0 ? '' : '<br />'));
 2250: 
 2251:     my $result='<div class="LC_Box">'
 2252:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2253:     $result.='<input type="hidden" name="name'.$counter.
 2254:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2255:     if ($env{'form.handgrade'} eq 'no') {
 2256:         $result.='<p class="LC_info">'
 2257:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2258:                 ."</p>\n";
 2259:     }
 2260: 
 2261:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2262:     my $fullname;
 2263:     my $col_fullnames = [];
 2264:     if ($env{'form.handgrade'} eq 'yes') {
 2265: 	(my $sub_result,$fullname,$col_fullnames)=
 2266: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2267: 				 $counter);
 2268: 	$result.=$sub_result;
 2269:     }
 2270:     $request->print($result."\n");
 2271: 
 2272:     # print student answer/submission
 2273:     # Options are (1) Handgraded submission only
 2274:     #             (2) Last submission, includes submission that is not handgraded 
 2275:     #                  (for multi-response type part)
 2276:     #             (3) Last submission plus the parts info
 2277:     #             (4) The whole record for this student
 2278: 
 2279: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2280: 	
 2281: 	my $lastsubonly;
 2282: 
 2283:         if ($$timestamp eq '') {
 2284:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2285:         } else {
 2286:             $lastsubonly =
 2287:                 '<div class="LC_grade_submissions_body">'
 2288:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2289: 
 2290: 	    my %seenparts;
 2291: 	    my @part_response_id = &flatten_responseType($responseType);
 2292: 	    foreach my $part (@part_response_id) {
 2293: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2294: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2295: 
 2296: 		my ($partid,$respid) = @{ $part };
 2297: 		my $display_part=&get_display_part($partid,$symb);
 2298: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2299: 		    if (exists($seenparts{$partid})) { next; }
 2300: 		    $seenparts{$partid}=1;
 2301:                     $request->print(
 2302:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2303:                         ' <b>'.&mt('Collaborative submission by: [_1]',
 2304:                                    '<a href="javascript:viewSubmitter(\''.
 2305:                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
 2306:                                    '\');" target="_self">'.
 2307:                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2308:                         '<br />');
 2309: 		    next;
 2310: 		}
 2311: 		my $responsetype = $responseType->{$partid}->{$respid};
 2312: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2313:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2314:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2315:                         ' <span class="LC_internal_info">'.
 2316:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2317:                         '</span>&nbsp; &nbsp;'.
 2318: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2319: 		    next;
 2320: 		}
 2321: 		foreach my $submission (@$string) {
 2322: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2323: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2324: 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2325: 		    # Similarity check
 2326: 		    my $similar='';
 2327:                     my ($type,$trial,$rndseed);
 2328:                     if ($hide eq 'rand') {
 2329:                         $type = 'randomizetry';
 2330:                         $trial = $record{"resource.$partid.tries"};
 2331:                         $rndseed = $record{"resource.$partid.rndseed"};
 2332:                     }
 2333: 		    if ($env{'form.checkPlag'}) {
 2334: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2335: 			    &most_similar($uname,$udom,$symb,$subval);
 2336: 			if ($osim) {
 2337: 			    $osim=int($osim*100.0);
 2338: 			    my %old_course_desc = 
 2339: 				&Apache::lonnet::coursedescription($ocrsid,
 2340: 								   {'one_time' => 1});
 2341: 
 2342:                             if ($hide eq 'anon') {
 2343:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2344:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2345:                             } else {
 2346: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2347: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2348: 				        $osim,
 2349: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2350: 				        $old_course_desc{'description'},
 2351: 				        $old_course_desc{'num'},
 2352: 				        $old_course_desc{'domain'}).
 2353: 				    '</span></h3><blockquote><i>'.
 2354: 				    &keywords_highlight($oessay).
 2355: 				    '</i></blockquote><hr />';
 2356:                             }
 2357: 			}
 2358: 		    }
 2359: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2360:                                          undef,$type,$trial,$rndseed);
 2361:                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
 2362:                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2363: 			my $display_part=&get_display_part($partid,$symb);
 2364:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2365:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2366:                             ' <span class="LC_internal_info">'.
 2367:                             '('.&mt('Response ID: [_1]',$respid).')'.
 2368:                             '</span>&nbsp; &nbsp;';
 2369: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2370: 			if (@$files) {
 2371:                             if ($hide eq 'anon') {
 2372:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2373:                             } else {
 2374:                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2375:                                             .'<br /><span class="LC_warning">';
 2376:                                 if(@$files == 1) {
 2377:                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2378:                                 } else {
 2379:                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2380:                                 }
 2381:                                 $lastsubonly .= '</span>';
 2382: 
 2383:                                 foreach my $file (@$files) {
 2384:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2385:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2386:                                 }
 2387:                             }
 2388: 			    $lastsubonly.='<br />';
 2389: 			}
 2390:                         if ($hide eq 'anon') {
 2391:                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2392:                         } else {
 2393: 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2394:                             if ($draft) {
 2395:                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2396:                             }
 2397:                             $subval =
 2398: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2399: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2400:                             if ($responsetype eq 'essay') {
 2401:                                 $subval =~ s{\n}{<br />}g;
 2402:                             }
 2403:                             $lastsubonly.=$subval."\n";
 2404:                         }
 2405: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2406: 			$lastsubonly.='</div>';
 2407: 		    }
 2408: 		}
 2409: 	    }
 2410: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2411: 	}
 2412: 	$request->print($lastsubonly);
 2413:    if ($env{'form.lastSub'} eq 'datesub') {
 2414: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2415: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2416:     }
 2417:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2418:         my $identifier = (&canmodify($usec)? $counter : '');
 2419: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2420: 								 $env{'request.course.id'},
 2421: 								 $last,'.submission',
 2422: 								 'Apache::grades::keywords_highlight',
 2423:                                                                  $usec,$identifier));
 2424:     }
 2425: 
 2426:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2427: 	.$udom.'" />'."\n");
 2428:     # return if view submission with no grading option
 2429:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2430: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2431: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2432: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2433: 	$toGrade.='</div>'."\n";
 2434: 	if (($env{'form.command'} eq 'submission') || 
 2435: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2436: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2437: 	}
 2438: 	$request->print($toGrade);
 2439: 	return;
 2440:     } else {
 2441: 	$request->print('</div>'."\n");
 2442:     }
 2443: 
 2444:     # essay grading message center
 2445:     if ($env{'form.handgrade'} eq 'yes') {
 2446: 	my $result='<div class="LC_grade_message_center">';
 2447:     
 2448: 	$result.='<div class="LC_grade_message_center_header">'.
 2449: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2450: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2451: 	my $msgfor = $givenn.' '.$lastname;
 2452: 	if (scalar(@$col_fullnames) > 0) {
 2453: 	    my $lastone = pop(@$col_fullnames);
 2454: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2455: 	}
 2456: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2457: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2458: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2459: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2460: 	    ',\''.$msgfor.'\');" target="_self">'.
 2461: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2462: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2463: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2464: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2465: 	    '<br />&nbsp;('.
 2466: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2467: 	$result.='</div></div>';
 2468: 	$request->print($result);
 2469:     }
 2470: 
 2471:     my %seen = ();
 2472:     my @partlist;
 2473:     my @gradePartRespid;
 2474:     my @part_response_id = &flatten_responseType($responseType);
 2475:     $request->print(
 2476:         '<div class="LC_Box">'
 2477:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2478:     );
 2479:     $request->print(&gradeBox_start());
 2480:     foreach my $part_response_id (@part_response_id) {
 2481:     	my ($partid,$respid) = @{ $part_response_id };
 2482: 	my $part_resp = join('_',@{ $part_response_id });
 2483: 	next if ($seen{$partid} > 0);
 2484: 	$seen{$partid}++;
 2485: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2486: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2487: 	push(@partlist,$partid);
 2488: 	push(@gradePartRespid,$partid.'.'.$respid);
 2489: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2490:     }
 2491:     $request->print(&gradeBox_end()); # </div>
 2492:     $request->print('</div>');
 2493: 
 2494:     $request->print('<div class="LC_grade_info_links">');
 2495:     $request->print('</div>');
 2496: 
 2497:     $result='<input type="hidden" name="partlist'.$counter.
 2498: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2499:     $result.='<input type="hidden" name="gradePartRespid'.
 2500: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2501:     my $ctr = 0;
 2502:     while ($ctr < scalar(@partlist)) {
 2503: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2504: 	    $partlist[$ctr].'" />'."\n";
 2505: 	$ctr++;
 2506:     }
 2507:     $request->print($result.''."\n");
 2508: 
 2509: # Done with printing info for one student
 2510: 
 2511:     $request->print('</div>');#LC_grade_show_user
 2512: 
 2513: 
 2514:     # print end of form
 2515:     if ($counter == $total) {
 2516:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2517: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2518: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2519: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2520: 	my $ntstu ='<select name="NTSTU">'.
 2521: 	    '<option>1</option><option>2</option>'.
 2522: 	    '<option>3</option><option>5</option>'.
 2523: 	    '<option>7</option><option>10</option></select>'."\n";
 2524: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2525: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2526:         $endform.=&mt('[_1]student(s)',$ntstu);
 2527: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2528: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2529: 	    '<input type="button" value="'.&mt('Next').'" '.
 2530: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2531:         $endform.='<span class="LC_warning">'.
 2532:                   &mt('(Next and Previous (student) do not save the scores.)').
 2533:                   '</span>'."\n" ;
 2534:         $endform.="<input type='hidden' value='".&get_increment().
 2535:             "' name='increment' />";
 2536: 	$endform.='</td></tr></table></form>';
 2537: 	$endform.=&show_grading_menu_form($symb);
 2538: 	$request->print($endform);
 2539:     }
 2540:     return '';
 2541: }
 2542: 
 2543: sub check_collaborators {
 2544:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2545:     my ($result,@col_fullnames);
 2546:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2547:     foreach my $part (keys(%$handgrade)) {
 2548: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2549: 					'.maxcollaborators',
 2550: 					$symb,$udom,$uname);
 2551: 	next if ($ncol <= 0);
 2552: 	$part =~ s/\_/\./g;
 2553: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2554: 	my (@good_collaborators, @bad_collaborators);
 2555: 	foreach my $possible_collaborator
 2556: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2557: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2558: 	    next if ($possible_collaborator eq '');
 2559: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2560: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2561: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2562: 	    # Doing this grep allows 'fuzzy' specification
 2563: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2564: 			       keys(%$classlist));
 2565: 	    if (! scalar(@matches)) {
 2566: 		push(@bad_collaborators, $possible_collaborator);
 2567: 	    } else {
 2568: 		push(@good_collaborators, @matches);
 2569: 	    }
 2570: 	}
 2571: 	if (scalar(@good_collaborators) != 0) {
 2572: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2573: 	    foreach my $name (@good_collaborators) {
 2574: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2575: 		push(@col_fullnames, $givenn.' '.$lastname);
 2576: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2577: 	    }
 2578: 	    $result.='</ol><br />'."\n";
 2579: 	    my ($part)=split(/\./,$part);
 2580: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2581: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2582: 		"\n";
 2583: 	}
 2584: 	if (scalar(@bad_collaborators) > 0) {
 2585: 	    $result.='<div class="LC_warning">';
 2586: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2587: 	    $result .= '</div>';
 2588: 	}         
 2589: 	if (scalar(@bad_collaborators > $ncol)) {
 2590: 	    $result .= '<div class="LC_warning">';
 2591: 	    $result .= &mt('This student has submitted too many '.
 2592: 		'collaborators.  Maximum is [_1].',$ncol);
 2593: 	    $result .= '</div>';
 2594: 	}
 2595:     }
 2596:     return ($result,$fullname,\@col_fullnames);
 2597: }
 2598: 
 2599: #--- Retrieve the last submission for all the parts
 2600: sub get_last_submission {
 2601:     my ($returnhash)=@_;
 2602:     my (@string,$timestamp,%lasthidden);
 2603:     if ($$returnhash{'version'}) {
 2604: 	my %lasthash=();
 2605: 	my ($version);
 2606: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2607: 	    foreach my $key (sort(split(/\:/,
 2608: 					$$returnhash{$version.':keys'}))) {
 2609: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2610: 		$timestamp = 
 2611: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2612: 	    }
 2613: 	}
 2614:         my (%typeparts,%randombytry);
 2615:         my $showsurv = 
 2616:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2617:         foreach my $key (sort(keys(%lasthash))) {
 2618:             if ($key =~ /\.type$/) {
 2619:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2620:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2621:                     ($lasthash{$key} eq 'randomizetry')) {
 2622:                     my ($ign,@parts) = split(/\./,$key);
 2623:                     pop(@parts);
 2624:                     my $id = join('.',@parts);
 2625:                     if ($lasthash{$key} eq 'randomizetry') {
 2626:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2627:                     } else {
 2628:                         unless ($showsurv) {
 2629:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2630:                         }
 2631:                     }
 2632:                     delete($lasthash{$key});
 2633:                 }
 2634:             }
 2635:         }
 2636:         my @hidden = keys(%typeparts);
 2637:         my @randomize = keys(%randombytry);
 2638: 	foreach my $key (keys(%lasthash)) {
 2639: 	    next if ($key !~ /\.submission$/);
 2640:             my $hide;
 2641:             if (@hidden) {
 2642:                 foreach my $id (@hidden) {
 2643:                     if ($key =~ /^\Q$id\E/) {
 2644:                         $hide = 'anon';
 2645:                         last;
 2646:                     }
 2647:                 }
 2648:             }
 2649:             unless ($hide) {
 2650:                 if (@randomize) {
 2651:                     foreach my $id (@randomize) {
 2652:                         if ($key =~ /^\Q$id\E/) {
 2653:                             $hide = 'rand';
 2654:                             last;
 2655:                         }
 2656:                     }
 2657:                 }
 2658:             }
 2659: 	    my ($partid,$foo) = split(/submission$/,$key);
 2660: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
 2661:             push(@string, join(':', $key, $hide, $draft, (
 2662:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2663:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2664: 	}
 2665:     }
 2666:     if (!@string) {
 2667: 	$string[0] =
 2668: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2669:     }
 2670:     return (\@string,\$timestamp);
 2671: }
 2672: 
 2673: #--- High light keywords, with style choosen by user.
 2674: sub keywords_highlight {
 2675:     my $string    = shift;
 2676:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2677:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2678:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2679:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2680:     foreach my $keyword (@keylist) {
 2681: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2682:     }
 2683:     return $string;
 2684: }
 2685: 
 2686: # For Tasks provide a mechanism to display previous version for one specific student
 2687: 
 2688: sub show_previous_task_version {
 2689:     my ($request,$symb) = @_;
 2690:     if ($symb eq '') {
 2691:         $request->print(
 2692:             '<span class="LC_error">'.
 2693:             &mt('Unable to handle ambiguous references.').
 2694:             '</span>');
 2695:         return '';
 2696:     }
 2697:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2698:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2699:     if (!&canview($usec)) {
 2700:         $request->print('<span class="LC_warning">'.
 2701:                         &mt('Unable to view previous version for requested student.').
 2702:                         ' '.&mt('([_1] in section [_2] in course id [_3])',
 2703:                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2704:                         '</span>');
 2705:         return;
 2706:     }
 2707:     my $mode = 'both';
 2708:     my $isTask = ($symb =~/\.task$/);
 2709:     if ($isTask) {
 2710:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2711:             if ($env{'form.fullname'} eq '') {
 2712:                 $env{'form.fullname'} =
 2713:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2714:             }
 2715:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2716:             $request->print("\n\n".
 2717:                             '<div class="LC_grade_show_user">'.
 2718:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2719:                             '</h2>'."\n");
 2720:             &Apache::lonxml::clear_problem_counter();
 2721:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2722:                             {'previousversion' => $env{'form.previousversion'} }));
 2723:             $request->print("\n</div>");
 2724:         }
 2725:     }
 2726:     return;
 2727: }
 2728: 
 2729: sub choose_task_version_form {
 2730:     my ($symb,$uname,$udom,$nomenu) = @_;
 2731:     my $isTask = ($symb =~/\.task$/);
 2732:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2733:     if ($isTask) {
 2734:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2735:                                               $udom,$uname);
 2736:         if (($record{'resource.0.version'} eq '') ||
 2737:             ($record{'resource.0.version'} < 2)) {
 2738:             return ($record{'resource.0.version'},
 2739:                     $record{'resource.0.version'},$result,$js);
 2740:         } else {
 2741:             $current = $record{'resource.0.version'};
 2742:         }
 2743:         if ($env{'form.previousversion'}) {
 2744:             $displayed = $env{'form.previousversion'};
 2745:             $rowtitle = &mt('Choose another version:')
 2746:         } else {
 2747:             $displayed = $current;
 2748:             $rowtitle = &mt('Show earlier version:');
 2749:         }
 2750:         $result = '<div class="LC_left_float">';
 2751:         my $list;
 2752:         my $numversions = 0;
 2753:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2754:             if ($i == $current) {
 2755:                 if (!$env{'form.previousversion'} || $nomenu) {
 2756:                     next;
 2757:                 } else {
 2758:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2759:                     $numversions ++;
 2760:                 }
 2761:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2762:                 unless ($i == $env{'form.previousversion'}) {
 2763:                     $numversions ++;
 2764:                 }
 2765:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2766:             }
 2767:         }
 2768:         if ($numversions) {
 2769:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2770:             $result .=
 2771:                 '<form name="getprev" method="post" action=""'.
 2772:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2773:                 &Apache::loncommon::start_data_table().
 2774:                 &Apache::loncommon::start_data_table_row().
 2775:                 '<th align="left">'.$rowtitle.'</th>'.
 2776:                 '<td><select name="version">'.
 2777:                 '<option>'.&mt('Select').'</option>'.
 2778:                 $list.
 2779:                 '</select></td>'.
 2780:                 &Apache::loncommon::end_data_table_row();
 2781:             unless ($nomenu) {
 2782:                 $result .= &Apache::loncommon::start_data_table_row().
 2783:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2784:                 '<td><span class="LC_nobreak">'.
 2785:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2786:                 &mt('Yes').'</label>'.
 2787:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2788:                 '</span></td>'.
 2789:                 &Apache::loncommon::end_data_table_row();
 2790:             }
 2791:             $result .=
 2792:                 &Apache::loncommon::start_data_table_row().
 2793:                 '<th align="left">&nbsp;</th>'.
 2794:                 '<td>'.
 2795:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2796:                 '</td>'.
 2797:                 &Apache::loncommon::end_data_table_row().
 2798:                 &Apache::loncommon::end_data_table().
 2799:                 '</form>';
 2800:             $js = &previous_display_javascript($nomenu,$current);
 2801:         } elsif ($displayed && $nomenu) {
 2802:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2803:         } else {
 2804:             $result .= &mt('No previous versions to show for this student');
 2805:         }
 2806:         $result .= '</div>';
 2807:     }
 2808:     return ($current,$displayed,$result,$js);
 2809: }
 2810: 
 2811: sub previous_display_javascript {
 2812:     my ($nomenu,$current) = @_;
 2813:     my $js = <<"JSONE";
 2814: <script type="text/javascript">
 2815: // <![CDATA[
 2816: function previousVersion(uname,udom,symb) {
 2817:     var current = '$current';
 2818:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2819:     var prevstr = new RegExp("^\\\\d+\$");
 2820:     if (!prevstr.test(version)) {
 2821:         return false;
 2822:     }
 2823:     var url = '';
 2824:     if (version == current) {
 2825:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2826:     } else {
 2827:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2828:     }
 2829: JSONE
 2830:     if ($nomenu) {
 2831:         $js .= <<"JSTWO";
 2832:     document.location.href = url;
 2833: JSTWO
 2834:     } else {
 2835:         $js .= <<"JSTHREE";
 2836:     var newwin = 0;
 2837:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2838:         if (document.getprev.prevwin[i].checked == true) {
 2839:             newwin = document.getprev.prevwin[i].value;
 2840:         }
 2841:     }
 2842:     if (newwin == 1) {
 2843:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2844:         url = url+'&inhibitmenu=yes';
 2845:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2846:             previousWin = window.open(url,'',options,1);
 2847:         } else {
 2848:             previousWin.location.href = url;
 2849:         }
 2850:         previousWin.focus();
 2851:         return false;
 2852:     } else {
 2853:         document.location.href = url;
 2854:         return false;
 2855:     }
 2856: JSTHREE
 2857:     }
 2858:     $js .= <<"ENDJS";
 2859:     return false;
 2860: }
 2861: // ]]>
 2862: </script>
 2863: ENDJS
 2864: 
 2865: }
 2866: 
 2867: #--- Called from submission routine
 2868: sub processHandGrade {
 2869:     my ($request) = shift;
 2870:     my ($symb)   = &get_symb($request);
 2871:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2872:     my $button = $env{'form.gradeOpt'};
 2873:     my $ngrade = $env{'form.NCT'};
 2874:     my $ntstu  = $env{'form.NTSTU'};
 2875:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2876:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2877: 
 2878:     if ($button eq 'Save & Next') {
 2879: 	my $ctr = 0;
 2880: 	while ($ctr < $ngrade) {
 2881: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2882: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2883:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2884: 	    if ($errorflag eq 'no_score') {
 2885: 		$ctr++;
 2886: 		next;
 2887: 	    }
 2888: 	    if ($errorflag eq 'not_allowed') {
 2889:                 $request->print(
 2890:                     '<span class="LC_error">'
 2891:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2892:                    .'</span>');
 2893: 		$ctr++;
 2894: 		next;
 2895: 	    }
 2896:             if ($numhidden) {
 2897:                 $request->print(
 2898:                     '<span class="LC_info">'
 2899:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2900:                    .'</span><br />');
 2901:             }
 2902: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2903: 	    my ($subject,$message,$msgstatus) = ('','','');
 2904: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2905:             my ($feedurl,$showsymb) =
 2906: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2907: 	    my $messagetail;
 2908: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2909: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2910: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2911: 		$subject.=' ['.$restitle.']';
 2912: 		my (@msgnum) = split(/,/,$includemsg);
 2913: 		foreach (@msgnum) {
 2914: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2915: 		}
 2916: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2917: 		if ($env{'form.withgrades'.$ctr}) {
 2918: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2919: 		    $messagetail = " for <a href=\"".
 2920: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2921: 		}
 2922: 		$msgstatus = 
 2923:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2924: 						     $message.$messagetail,
 2925:                                                      undef,$feedurl,undef,
 2926:                                                      undef,undef,$showsymb,
 2927:                                                      $restitle);
 2928: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2929: 				$msgstatus.'<br />');
 2930: 	    }
 2931: 	    if ($env{'form.collaborator'.$ctr}) {
 2932: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2933: 		foreach my $collabstr (@collabstrs) {
 2934: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2935: 		    foreach my $collaborator (@collaborators) {
 2936: 			my ($errorflag,$pts,$wgt) = 
 2937: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2938: 					   $env{'form.unamedom'.$ctr},$part);
 2939: 			if ($errorflag eq 'not_allowed') {
 2940: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2941: 			    next;
 2942: 			} elsif ($message ne '') {
 2943: 			    my ($baseurl,$showsymb) = 
 2944: 				&get_feedurl_and_symb($symb,$collaborator,
 2945: 						      $udom);
 2946: 			    if ($env{'form.withgrades'.$ctr}) {
 2947: 				$messagetail = " for <a href=\"".
 2948:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2949: 			    }
 2950: 			    $msgstatus = 
 2951: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2952: 			}
 2953: 		    }
 2954: 		}
 2955: 	    }
 2956: 	    $ctr++;
 2957: 	}
 2958:     }
 2959: 
 2960:     if ($env{'form.handgrade'} eq 'yes') {
 2961: 	# Keywords sorted in alphabatical order
 2962: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2963: 	my %keyhash = ();
 2964: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2965: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2966: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2967: 	$env{'form.keywords'} = join(' ',@keywords);
 2968: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2969: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2970: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2971: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2972: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2973: 
 2974: 	# message center - Order of message gets changed. Blank line is eliminated.
 2975: 	# New messages are saved in env for the next student.
 2976: 	# All messages are saved in nohist_handgrade.db
 2977: 	my ($ctr,$idx) = (1,1);
 2978: 	while ($ctr <= $env{'form.savemsgN'}) {
 2979: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2980: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2981: 		$idx++;
 2982: 	    }
 2983: 	    $ctr++;
 2984: 	}
 2985: 	$ctr = 0;
 2986: 	while ($ctr < $ngrade) {
 2987: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2988: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2989: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2990: 		$idx++;
 2991: 	    }
 2992: 	    $ctr++;
 2993: 	}
 2994: 	$env{'form.savemsgN'} = --$idx;
 2995: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2996: 	my $putresult = &Apache::lonnet::put
 2997: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2998:     }
 2999:     # Called by Save & Refresh from Highlight Attribute Window
 3000:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3001:     if ($env{'form.refresh'} eq 'on') {
 3002: 	my ($ctr,$total) = (0,0);
 3003: 	while ($ctr < $ngrade) {
 3004: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3005: 	    $ctr++;
 3006: 	}
 3007: 	$env{'form.NTSTU'}=$ngrade;
 3008: 	$ctr = 0;
 3009: 	while ($ctr < $total) {
 3010: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3011: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3012: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3013: 	    &submission($request,$ctr,$total-1);
 3014: 	    $ctr++;
 3015: 	}
 3016: 	return '';
 3017:     }
 3018: 
 3019: # Go directly to grade student - from submission or link from chart page
 3020:     if ($button eq 'Grade Student') {
 3021: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 3022: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 3023: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3024: 	$env{'form.fullname'} = $$fullname{$processUser};
 3025: 	&submission($request,0,0);
 3026: 	return '';
 3027:     }
 3028: 
 3029:     # Get the next/previous one or group of students
 3030:     my $firststu = $env{'form.unamedom0'};
 3031:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3032:     my $ctr = 2;
 3033:     while ($laststu eq '') {
 3034: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3035: 	$ctr++;
 3036: 	$laststu = $firststu if ($ctr > $ngrade);
 3037:     }
 3038: 
 3039:     my (@parsedlist,@nextlist);
 3040:     my ($nextflg) = 0;
 3041:     foreach my $item (sort 
 3042: 	     {
 3043: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3044: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3045: 		 }
 3046: 		 return $a cmp $b;
 3047: 	     } (keys(%$fullname))) {
 3048: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3049: 	    push(@parsedlist,$item);
 3050: 	}
 3051: 	$nextflg = 1 if ($item eq $laststu);
 3052: 	if ($button eq 'Previous') {
 3053: 	    last if ($item eq $firststu);
 3054: 	    push(@parsedlist,$item);
 3055: 	}
 3056:     }
 3057:     $ctr = 0;
 3058:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3059:     my $res_error;
 3060:     my ($partlist) = &response_type($symb,\$res_error);
 3061:     if ($res_error) {
 3062:         $request->print(&navmap_errormsg());
 3063:         return;
 3064:     }
 3065:     foreach my $student (@parsedlist) {
 3066: 	my $submitonly=$env{'form.submitonly'};
 3067: 	my ($uname,$udom) = split(/:/,$student);
 3068: 	
 3069: 	if ($submitonly eq 'queued') {
 3070: 	    my %queue_status = 
 3071: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3072: 							$udom,$uname);
 3073: 	    next if (!defined($queue_status{'gradingqueue'}));
 3074: 	}
 3075: 
 3076: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3077: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3078: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3079: 	    my $submitted = 0;
 3080: 	    my $ungraded = 0;
 3081: 	    my $incorrect = 0;
 3082: 	    foreach my $item (keys(%status)) {
 3083: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3084: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3085: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3086: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3087: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3088: 		    $submitted = 0;
 3089: 		}
 3090: 	    }
 3091: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3092: 				     $submitonly eq 'incorrect' ||
 3093: 				     $submitonly eq 'graded'));
 3094: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3095: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3096: 	}
 3097: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3098: 	last if ($ctr == $ntstu);
 3099: 	$ctr++;
 3100:     }
 3101: 
 3102:     $ctr = 0;
 3103:     my $total = scalar(@nextlist)-1;
 3104: 
 3105:     foreach (sort(@nextlist)) {
 3106: 	my ($uname,$udom,$submitter) = split(/:/);
 3107: 	$env{'form.student'}  = $uname;
 3108: 	$env{'form.userdom'}  = $udom;
 3109: 	$env{'form.fullname'} = $$fullname{$_};
 3110: 	&submission($request,$ctr,$total);
 3111: 	$ctr++;
 3112:     }
 3113:     if ($total < 0) {
 3114: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 3115: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3116: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 3117: 	$the_end.=&show_grading_menu_form($symb);
 3118: 	$request->print($the_end);
 3119:     }
 3120:     return '';
 3121: }
 3122: 
 3123: #---- Save the score and award for each student, if changed
 3124: sub saveHandGrade {
 3125:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3126:     my @version_parts;
 3127:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3128: 					   $env{'request.course.id'});
 3129:     if (!&canmodify($usec)) { return('not_allowed'); }
 3130:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3131:     my @parts_graded;
 3132:     my %newrecord  = ();
 3133:     my ($pts,$wgt,$totchg) = ('','',0);
 3134:     my %aggregate = ();
 3135:     my $aggregateflag = 0;
 3136:     if ($env{'form.HIDE'.$newflg}) {
 3137:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3138:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3139:         $totchg += $numchgs;
 3140:     }
 3141:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3142:     foreach my $new_part (@parts) {
 3143: 	#collaborator ($submi may vary for different parts
 3144: 	if ($submitter && $new_part ne $part) { next; }
 3145: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3146: 	if ($dropMenu eq 'excused') {
 3147: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3148: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3149: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3150: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3151: 		}
 3152: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3153: 	    }
 3154: 	} elsif ($dropMenu eq 'reset status'
 3155: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3156: 	    foreach my $key (keys(%record)) {
 3157: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3158: 	    }
 3159: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3160: 		"$env{'user.name'}:$env{'user.domain'}";
 3161:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3162: 
 3163:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3164: 					       [$new_part]);
 3165:             my $aggtries =$totaltries;
 3166:             if ($last_resets{$new_part}) {
 3167:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3168: 					   $new_part);
 3169:             }
 3170: 
 3171:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3172:             if ($aggtries > 0) {
 3173:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3174:                 $aggregateflag = 1;
 3175:             }
 3176: 	} elsif ($dropMenu eq '') {
 3177: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3178: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3179: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3180: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3181: 		next;
 3182: 	    }
 3183: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3184: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3185: 	    my $partial= $pts/$wgt;
 3186: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3187: 		#do not update score for part if not changed.
 3188:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3189: 		next;
 3190: 	    } else {
 3191: 	        push(@parts_graded,$new_part);
 3192: 	    }
 3193: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3194: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3195: 	    }
 3196: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3197: 	    if ($partial == 0) {
 3198: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3199: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3200: 		}
 3201: 	    } else {
 3202: 		if ($record{$reckey} ne 'correct_by_override') {
 3203: 		    $newrecord{$reckey} = 'correct_by_override';
 3204: 		}
 3205: 	    }	    
 3206: 	    if ($submitter && 
 3207: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3208: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3209: 	    }
 3210: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3211: 		"$env{'user.name'}:$env{'user.domain'}";
 3212: 	}
 3213: 	# unless problem has been graded, set flag to version the submitted files
 3214: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3215: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3216: 	        $dropMenu eq 'reset status')
 3217: 	   {
 3218: 	    push(@version_parts,$new_part);
 3219: 	}
 3220:     }
 3221:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3222:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3223: 
 3224:     if (%newrecord) {
 3225:         if (@version_parts) {
 3226:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3227:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3228: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3229: 	    foreach my $new_part (@version_parts) {
 3230: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3231: 				$new_part,\%newrecord);
 3232: 	    }
 3233:         }
 3234: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3235: 				$env{'request.course.id'},$domain,$stuname);
 3236: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3237: 				     $cdom,$cnum,$domain,$stuname);
 3238:     }
 3239:     if ($aggregateflag) {
 3240:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3241: 			      $cdom,$cnum);
 3242:     }
 3243:     return ('',$pts,$wgt,$totchg);
 3244: }
 3245: 
 3246: sub makehidden {
 3247:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3248:     return unless (ref($record) eq 'HASH');
 3249:     my %modified;
 3250:     my $numchanged = 0;
 3251:     if (exists($record->{$version.':keys'})) {
 3252:         my $partsregexp = $parts;
 3253:         $partsregexp =~ s/,/|/g;
 3254:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3255:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3256:                  my $item = $1;
 3257:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3258:                      $modified{$key} = $record->{$version.':'.$key};
 3259:                  }
 3260:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3261:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3262:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3263:                 $modified{$key} = $record->{$version.':'.$key};
 3264:             }
 3265:         }
 3266:         if (keys(%modified)) {
 3267:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3268:                                           $domain,$stuname,$tolog) eq 'ok') {
 3269:                 $numchanged ++;
 3270:             }
 3271:         }
 3272:     }
 3273:     return $numchanged;
 3274: }
 3275: 
 3276: sub check_and_remove_from_queue {
 3277:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3278:     my @ungraded_parts;
 3279:     foreach my $part (@{$parts}) {
 3280: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3281: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3282: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3283: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3284: 		) {
 3285: 	    push(@ungraded_parts, $part);
 3286: 	}
 3287:     }
 3288:     if ( !@ungraded_parts ) {
 3289: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3290: 					       $cnum,$domain,$stuname);
 3291:     }
 3292: }
 3293: 
 3294: sub handback_files {
 3295:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3296:     my $portfolio_root = '/userfiles/portfolio';
 3297:     my $res_error;
 3298:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3299:     if ($res_error) {
 3300:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3301:         return;
 3302:     }
 3303:     my @handedback;
 3304:     my $file_msg;
 3305:     my @part_response_id = &flatten_responseType($responseType);
 3306:     foreach my $part_response_id (@part_response_id) {
 3307:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3308: 	my $part_resp = join('_',@{ $part_response_id });
 3309:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3310:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3311:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 3312: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3313:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3314:                     my ($directory,$answer_file) = 
 3315:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3316:                     my ($answer_name,$answer_ver,$answer_ext) =
 3317: 		        &file_name_version_ext($answer_file);
 3318: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3319:                     my $getpropath = 1;
 3320:                     my ($dir_list,$listerror) =
 3321:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3322:                                                  $domain,$stuname,$getpropath);
 3323: 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3324:                     # fix filename
 3325:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3326:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3327:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3328:             	                                $save_file_name);
 3329:                     if ($result !~ m|^/uploaded/|) {
 3330:                         $request->print('<br /><span class="LC_error">'.
 3331:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3332:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3333:                                         '</span>');
 3334:                     } else {
 3335:                         # mark the file as read only
 3336:                         push(@handedback,$save_file_name);
 3337: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3338: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3339: 			}
 3340:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3341: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3342: 
 3343:                     }
 3344:                     $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>'));
 3345:                 }
 3346:             }
 3347:         }
 3348:     }
 3349:     if (@handedback > 0) {
 3350:         $request->print('<br />');
 3351:         my @what = ($symb,$env{'request.course.id'},'handback');
 3352:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3353:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
 3354:         my ($subject,$message);
 3355:         if (scalar(@handedback) == 1) {
 3356:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3357:         } else {
 3358:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3359:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3360:         }
 3361:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3362:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3363:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3364:         my ($feedurl,$showsymb) =
 3365:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3366:         my $restitle = &Apache::lonnet::gettitle($symb);
 3367:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3368:         my $msgstatus =
 3369:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3370:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3371:                  $restitle);
 3372:         if ($msgstatus) {
 3373:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3374:         }
 3375:     }
 3376:     return;
 3377: }
 3378: 
 3379: sub get_feedurl_and_symb {
 3380:     my ($symb,$uname,$udom) = @_;
 3381:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3382:     $url = &Apache::lonnet::clutter($url);
 3383:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3384: 					$symb,$udom,$uname);
 3385:     if ($encrypturl =~ /^yes$/i) {
 3386: 	&Apache::lonenc::encrypted(\$url,1);
 3387: 	&Apache::lonenc::encrypted(\$symb,1);
 3388:     }
 3389:     return ($url,$symb);
 3390: }
 3391: 
 3392: sub get_submitted_files {
 3393:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3394:     my @files;
 3395:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3396:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3397:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3398:     	    push(@files,$file_url.$file);
 3399:         }
 3400:     }
 3401:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3402:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3403:     }
 3404:     return (\@files);
 3405: }
 3406: 
 3407: # ----------- Provides number of tries since last reset.
 3408: sub get_num_tries {
 3409:     my ($record,$last_reset,$part) = @_;
 3410:     my $timestamp = '';
 3411:     my $num_tries = 0;
 3412:     if ($$record{'version'}) {
 3413:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3414:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3415:                 $timestamp = $$record{$version.':timestamp'};
 3416:                 if ($timestamp > $last_reset) {
 3417:                     $num_tries ++;
 3418:                 } else {
 3419:                     last;
 3420:                 }
 3421:             }
 3422:         }
 3423:     }
 3424:     return $num_tries;
 3425: }
 3426: 
 3427: # ----------- Determine decrements required in aggregate totals 
 3428: sub decrement_aggs {
 3429:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3430:     my %decrement = (
 3431:                         attempts => 0,
 3432:                         users => 0,
 3433:                         correct => 0
 3434:                     );
 3435:     $decrement{'attempts'} = $aggtries;
 3436:     if ($solvedstatus =~ /^correct/) {
 3437:         $decrement{'correct'} = 1;
 3438:     }
 3439:     if ($aggtries == $totaltries) {
 3440:         $decrement{'users'} = 1;
 3441:     }
 3442:     foreach my $type (keys(%decrement)) {
 3443:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3444:     }
 3445:     return;
 3446: }
 3447: 
 3448: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3449: sub get_last_resets {
 3450:     my ($symb,$courseid,$partids) =@_;
 3451:     my %last_resets;
 3452:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3453:     my $cname = $env{'course.'.$courseid.'.num'};
 3454:     my @keys;
 3455:     foreach my $part (@{$partids}) {
 3456: 	push(@keys,"$symb\0$part\0resettime");
 3457:     }
 3458:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3459: 				     $cdom,$cname);
 3460:     foreach my $part (@{$partids}) {
 3461: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3462:     }
 3463:     return %last_resets;
 3464: }
 3465: 
 3466: # ----------- Handles creating versions for portfolio files as answers
 3467: sub version_portfiles {
 3468:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3469:     my $version_parts = join('|',@$v_flag);
 3470:     my @returned_keys;
 3471:     my $parts = join('|', @$parts_graded);
 3472:     my $portfolio_root = '/userfiles/portfolio';
 3473:     foreach my $key (keys(%$record)) {
 3474:         my $new_portfiles;
 3475:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3476:             my @versioned_portfiles;
 3477:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3478:             foreach my $file (@portfiles) {
 3479:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3480:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3481: 		my ($answer_name,$answer_ver,$answer_ext) =
 3482: 		    &file_name_version_ext($answer_file);
 3483:                 my $getpropath = 1;
 3484:                 my ($dir_list,$listerror) =
 3485:                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
 3486:                                              $stu_name,$getpropath);
 3487:                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 3488:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3489:                 if ($new_answer ne 'problem getting file') {
 3490:                     push(@versioned_portfiles, $directory.$new_answer);
 3491:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3492:                         [$directory.$new_answer],
 3493:                         [$symb,$env{'request.course.id'},'graded']);
 3494:                 }
 3495:             }
 3496:             $$record{$key} = join(',',@versioned_portfiles);
 3497:             push(@returned_keys,$key);
 3498:         }
 3499:     } 
 3500:     return (@returned_keys);   
 3501: }
 3502: 
 3503: sub get_next_version {
 3504:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3505:     my $version;
 3506:     if (ref($dir_list) eq 'ARRAY') {
 3507:         foreach my $row (@{$dir_list}) {
 3508:             my ($file) = split(/\&/,$row,2);
 3509:             my ($file_name,$file_version,$file_ext) =
 3510: 	        &file_name_version_ext($file);
 3511:             if (($file_name eq $answer_name) && 
 3512: 	        ($file_ext eq $answer_ext)) {
 3513:                 # gets here if filename and extension match, 
 3514:                 # regardless of version
 3515:                 if ($file_version ne '') {
 3516:                     # a versioned file is found  so save it for later
 3517:                     if ($file_version > $version) {
 3518: 		        $version = $file_version;
 3519:                     }
 3520: 	        }
 3521:             }
 3522:         }
 3523:     }
 3524:     $version ++;
 3525:     return($version);
 3526: }
 3527: 
 3528: sub version_selected_portfile {
 3529:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3530:     my ($answer_name,$answer_ver,$answer_ext) =
 3531:         &file_name_version_ext($file_name);
 3532:     my $new_answer;
 3533:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3534:     if($env{'form.copy'} eq '-1') {
 3535:         $new_answer = 'problem getting file';
 3536:     } else {
 3537:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3538:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3539:                             $stu_name,$domain,'copy',
 3540: 		        '/portfolio'.$directory.$new_answer);
 3541:     }    
 3542:     return ($new_answer);
 3543: }
 3544: 
 3545: sub file_name_version_ext {
 3546:     my ($file)=@_;
 3547:     my @file_parts = split(/\./, $file);
 3548:     my ($name,$version,$ext);
 3549:     if (@file_parts > 1) {
 3550: 	$ext=pop(@file_parts);
 3551: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3552: 	    $version=pop(@file_parts);
 3553: 	}
 3554: 	$name=join('.',@file_parts);
 3555:     } else {
 3556: 	$name=join('.',@file_parts);
 3557:     }
 3558:     return($name,$version,$ext);
 3559: }
 3560: 
 3561: #--------------------------------------------------------------------------------------
 3562: #
 3563: #-------------------------- Next few routines handles grading by section or whole class
 3564: #
 3565: #--- Javascript to handle grading by section or whole class
 3566: sub viewgrades_js {
 3567:     my ($request) = shift;
 3568: 
 3569:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3570:     &js_escape(\$alertmsg);
 3571:     $request->print(<<VIEWJAVASCRIPT);
 3572: <script type="text/javascript" language="javascript">
 3573:    function writePoint(partid,weight,point) {
 3574: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3575: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3576: 	if (point == "textval") {
 3577: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3578: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3579: 		alert("$alertmsg"+parseFloat(point));
 3580: 		var resetbox = false;
 3581: 		for (var i=0; i<radioButton.length; i++) {
 3582: 		    if (radioButton[i].checked) {
 3583: 			textbox.value = i;
 3584: 			resetbox = true;
 3585: 		    }
 3586: 		}
 3587: 		if (!resetbox) {
 3588: 		    textbox.value = "";
 3589: 		}
 3590: 		return;
 3591: 	    }
 3592: 	    if (parseFloat(point) > parseFloat(weight)) {
 3593: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3594: 				   ") greater than the weight for the part. Accept?");
 3595: 		if (resp == false) {
 3596: 		    textbox.value = "";
 3597: 		    return;
 3598: 		}
 3599: 	    }
 3600: 	    for (var i=0; i<radioButton.length; i++) {
 3601: 		radioButton[i].checked=false;
 3602: 		if (parseFloat(point) == i) {
 3603: 		    radioButton[i].checked=true;
 3604: 		}
 3605: 	    }
 3606: 
 3607: 	} else {
 3608: 	    textbox.value = parseFloat(point);
 3609: 	}
 3610: 	for (i=0;i<document.classgrade.total.value;i++) {
 3611: 	    var user = document.classgrade["ctr"+i].value;
 3612: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3613: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3614: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3615: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3616: 	    if (saveval != "correct") {
 3617: 		scorename.value = point;
 3618: 		if (selname[0].selected != true) {
 3619: 		    selname[0].selected = true;
 3620: 		}
 3621: 	    }
 3622: 	}
 3623: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3624:     }
 3625: 
 3626:     function writeRadText(partid,weight) {
 3627: 	var selval   = document.classgrade["SELVAL_"+partid];
 3628: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3629:         var override = document.classgrade["FORCE_"+partid].checked;
 3630: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3631: 	if (selval[1].selected || selval[2].selected) {
 3632: 	    for (var i=0; i<radioButton.length; i++) {
 3633: 		radioButton[i].checked=false;
 3634: 
 3635: 	    }
 3636: 	    textbox.value = "";
 3637: 
 3638: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3639: 		var user = document.classgrade["ctr"+i].value;
 3640: 		user = user.replace(new RegExp(':', 'g'),"_");
 3641: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3642: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3643: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3644: 		if ((saveval != "correct") || override) {
 3645: 		    scorename.value = "";
 3646: 		    if (selval[1].selected) {
 3647: 			selname[1].selected = true;
 3648: 		    } else {
 3649: 			selname[2].selected = true;
 3650: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3651: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3652: 		    }
 3653: 		}
 3654: 	    }
 3655: 	} else {
 3656: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3657: 		var user = document.classgrade["ctr"+i].value;
 3658: 		user = user.replace(new RegExp(':', 'g'),"_");
 3659: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3660: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3661: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3662: 		if ((saveval != "correct") || override) {
 3663: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3664: 		    selname[0].selected = true;
 3665: 		}
 3666: 	    }
 3667: 	}	    
 3668:     }
 3669: 
 3670:     function changeSelect(partid,user) {
 3671: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3672: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3673: 	var point  = textbox.value;
 3674: 	var weight = document.classgrade["weight_"+partid].value;
 3675: 
 3676: 	if (isNaN(point) || parseFloat(point) < 0) {
 3677: 	    alert("$alertmsg"+parseFloat(point));
 3678: 	    textbox.value = "";
 3679: 	    return;
 3680: 	}
 3681: 	if (parseFloat(point) > parseFloat(weight)) {
 3682: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3683: 			       ") greater than the weight of the part. Accept?");
 3684: 	    if (resp == false) {
 3685: 		textbox.value = "";
 3686: 		return;
 3687: 	    }
 3688: 	}
 3689: 	selval[0].selected = true;
 3690:     }
 3691: 
 3692:     function changeOneScore(partid,user) {
 3693: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3694: 	if (selval[1].selected || selval[2].selected) {
 3695: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3696: 	    if (selval[2].selected) {
 3697: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3698: 	    }
 3699:         }
 3700:     }
 3701: 
 3702:     function resetEntry(numpart) {
 3703: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3704: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3705: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3706: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3707: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3708: 	    for (var i=0; i<radioButton.length; i++) {
 3709: 		radioButton[i].checked=false;
 3710: 
 3711: 	    }
 3712: 	    textbox.value = "";
 3713: 	    selval[0].selected = true;
 3714: 
 3715: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3716: 		var user = document.classgrade["ctr"+i].value;
 3717: 		user = user.replace(new RegExp(':', 'g'),"_");
 3718: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3719: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3720: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3721: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3722: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3723: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3724: 		if (saveselval == "excused") {
 3725: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3726: 		} else {
 3727: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3728: 		}
 3729: 	    }
 3730: 	}
 3731:     }
 3732: 
 3733: </script>
 3734: VIEWJAVASCRIPT
 3735: }
 3736: 
 3737: #--- show scores for a section or whole class w/ option to change/update a score
 3738: sub viewgrades {
 3739:     my ($request) = shift;
 3740:     &viewgrades_js($request);
 3741: 
 3742:     my ($symb) = &get_symb($request);
 3743:     #need to make sure we have the correct data for later EXT calls, 
 3744:     #thus invalidate the cache
 3745:     &Apache::lonnet::devalidatecourseresdata(
 3746:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3747:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3748:     &Apache::lonnet::clear_EXT_cache_status();
 3749: 
 3750:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3751:     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 3752: 
 3753:     #view individual student submission form - called using Javascript viewOneStudent
 3754:     $result.=&jscriptNform($symb);
 3755: 
 3756:     #beginning of class grading form
 3757:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3758:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3759: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3760: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3761: 	&build_section_inputs().
 3762: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3763: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3764: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3765: 
 3766:     #retrieve selected groups
 3767:     my (@groups,$group_display);
 3768:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3769:     if (grep(/^all$/,@groups)) {
 3770:         @groups = ('all');
 3771:     } elsif (grep(/^none$/,@groups)) {
 3772:         @groups = ('none');
 3773:     } elsif (@groups > 0) {
 3774:         $group_display = join(', ',@groups);
 3775:     }
 3776: 
 3777:     my ($common_header,$specific_header,@sections,$section_display);
 3778:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3779:     if (grep(/^all$/,@sections)) {
 3780:         @sections = ('all');
 3781:         if ($group_display) {
 3782:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3783:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3784:         } elsif (grep(/^none$/,@groups)) {
 3785:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3786:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3787:         } else {
 3788:             $common_header = &mt('Assign Common Grade to Class');
 3789:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3790:         }
 3791:     } elsif (grep(/^none$/,@sections)) {
 3792:         @sections = ('none');
 3793:         if ($group_display) {
 3794:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3795:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3796:         } elsif (grep(/^none$/,@groups)) {
 3797:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3798:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3799:         } else {
 3800:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3801:             $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3802:         }
 3803:     } else {
 3804:         $section_display = join (", ",@sections);
 3805:         if ($group_display) {
 3806:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3807:                                  $section_display,$group_display);
 3808:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3809:                                    $section_display,$group_display);
 3810:         } elsif (grep(/^none$/,@groups)) {
 3811:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3812:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3813:         } else {
 3814:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3815:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3816:         }
 3817:     }
 3818:     my %submit_types = &substatus_options();
 3819:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3820: 
 3821:     if ($env{'form.submitonly'} eq 'all') {
 3822:         $result.= '<h3>'.$common_header.'</h3>';
 3823:     } else {
 3824:         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
 3825:     }
 3826:     $result .= &Apache::loncommon::start_data_table();
 3827:     #radio buttons/text box for assigning points for a section or class.
 3828:     #handles different parts of a problem
 3829:     my $res_error;
 3830:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3831:     if ($res_error) {
 3832:         return &navmap_errormsg();
 3833:     }
 3834:     my %weight = ();
 3835:     my $ctsparts = 0;
 3836:     my %seen = ();
 3837:     my @part_response_id = &flatten_responseType($responseType);
 3838:     foreach my $part_response_id (@part_response_id) {
 3839:     	my ($partid,$respid) = @{ $part_response_id };
 3840: 	my $part_resp = join('_',@{ $part_response_id });
 3841: 	next if $seen{$partid};
 3842: 	$seen{$partid}++;
 3843: 	my $handgrade=$$handgrade{$part_resp};
 3844: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3845: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3846: 
 3847: 	my $display_part=&get_display_part($partid,$symb);
 3848: 	my $radio.='<table border="0"><tr>';  
 3849: 	my $ctr = 0;
 3850: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3851: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3852: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3853: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3854: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3855: 	    $ctr++;
 3856: 	}
 3857: 	$radio.='</tr></table>';
 3858: 	my $line = '<input type="text" name="TEXTVAL_'.
 3859: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3860: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3861: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3862: 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3863:                 '<select name="SELVAL_'.$partid.'" '.
 3864: 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
 3865: 		$weight{$partid}.')"> '.
 3866: 	    '<option selected="selected"> </option>'.
 3867: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3868: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3869: 	    '</select></td>'.
 3870:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3871: 	$line.='<input type="hidden" name="partid_'.
 3872: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3873: 	$line.='<input type="hidden" name="weight_'.
 3874: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3875: 
 3876: 	$result.=
 3877: 	    &Apache::loncommon::start_data_table_row()."\n".
 3878: 	    '<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>'.
 3879: 	    &Apache::loncommon::end_data_table_row()."\n";
 3880: 	$ctsparts++;
 3881:     }
 3882:     $result.=&Apache::loncommon::end_data_table()."\n".
 3883: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3884:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3885: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3886: 
 3887:     #table listing all the students in a section/class
 3888:     #header of table
 3889:     if ($env{'form.submitonly'} eq 'all') { 
 3890:         $result.= '<h3>'.$specific_header.'</h3>';
 3891:     } else {
 3892:         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
 3893:     }
 3894:     $result.= &Apache::loncommon::start_data_table().
 3895: 	      &Apache::loncommon::start_data_table_header_row().
 3896: 	      '<th>'.&mt('No.').'</th>'.
 3897: 	      '<th>'.&nameUserString('header')."</th>\n";
 3898:     my $partserror;
 3899:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3900:     if ($partserror) {
 3901:         return &navmap_errormsg();
 3902:     }
 3903:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3904:     my @partids = ();
 3905:     foreach my $part (@parts) {
 3906: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3907:         my $narrowtext = &mt('Tries');
 3908: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3909: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3910: 	my ($partid) = &split_part_type($part);
 3911:         push(@partids,$partid);
 3912: 	my $display_part=&get_display_part($partid,$symb);
 3913: 	if ($display =~ /^Partial Credit Factor/) {
 3914: 	    $result.='<th>'.
 3915:                 &mt('Score Part: [_1][_2](weight = [_3])',
 3916:                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3917: 	    next;
 3918: 	    
 3919: 	} else {
 3920: 	    if ($display =~ /Problem Status/) {
 3921: 		my $grade_status_mt = &mt('Grade Status');
 3922: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3923: 	    }
 3924: 	    my $part_mt = &mt('Part:');
 3925: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3926: 	}
 3927: 
 3928: 	$result.='<th>'.$display.'</th>'."\n";
 3929:     }
 3930:     $result.=&Apache::loncommon::end_data_table_header_row();
 3931: 
 3932:     my %last_resets = 
 3933: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3934: 
 3935:     #get info for each student
 3936:     #list all the students - with points and grade status
 3937:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3938:     my $ctr = 0;
 3939:     foreach (sort 
 3940: 	     {
 3941: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3942: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3943: 		 }
 3944: 		 return $a cmp $b;
 3945: 	     } (keys(%$fullname))) {
 3946: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3947: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
 3948:     }
 3949:     $result.=&Apache::loncommon::end_data_table();
 3950:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3951:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3952: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3953:     if ($ctr == 0) {
 3954:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3955:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3956:                 '<span class="LC_warning">';
 3957:         if ($env{'form.submitonly'} eq 'all') {
 3958:             if (grep(/^all$/,@sections)) {
 3959:                 if (grep(/^all$/,@groups)) {
 3960:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3961:                                    $stu_status);
 3962:                 } elsif (grep(/^none$/,@groups)) {
 3963:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3964:                                    $stu_status);
 3965:                 } else {
 3966:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3967:                                    $group_display,$stu_status);
 3968:                 }
 3969:             } elsif (grep(/^none$/,@sections)) {
 3970:                 if (grep(/^all$/,@groups)) {
 3971:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3972:                                    $stu_status);
 3973:                 } elsif (grep(/^none$/,@groups)) {
 3974:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3975:                                    $stu_status);
 3976:                 } else {
 3977:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3978:                                    $group_display,$stu_status);
 3979:                 }
 3980:             } else {
 3981:                 if (grep(/^all$/,@groups)) {
 3982:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3983:                                    $section_display,$stu_status);
 3984:                 } elsif (grep(/^none$/,@groups)) {
 3985:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3986:                                    $section_display,$stu_status);
 3987:                 } else {
 3988:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3989:                                    $section_display,$group_display,$stu_status);
 3990:                 }
 3991:             }
 3992:         } else {
 3993:             if (grep(/^all$/,@sections)) {
 3994:                 if (grep(/^all$/,@groups)) {
 3995:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3996:                                    $stu_status,$submission_status);
 3997:                 } elsif (grep(/^none$/,@groups)) {
 3998:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 3999:                                    $stu_status,$submission_status);
 4000:                 } else {
 4001:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4002:                                    $group_display,$stu_status,$submission_status);
 4003:                 }
 4004:             } elsif (grep(/^none$/,@sections)) {
 4005:                 if (grep(/^all$/,@groups)) {
 4006:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4007:                                    $stu_status,$submission_status);
 4008:                 } elsif (grep(/^none$/,@groups)) {
 4009:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4010:                                    $stu_status,$submission_status);
 4011:                 } else {
 4012:                     $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.',
 4013:                                    $group_display,$stu_status,$submission_status);
 4014:                 }
 4015:             } else {
 4016:                 if (grep(/^all$/,@groups)) {
 4017:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4018:                                    $section_display,$stu_status,$submission_status);
 4019:                 } elsif (grep(/^none$/,@groups)) {
 4020:                     $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.',
 4021:                                    $section_display,$stu_status,$submission_status);
 4022:                 } else {
 4023:                     $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.',
 4024:                                    $section_display,$group_display,$stu_status,$submission_status);
 4025:                 }
 4026:             }
 4027: 	}
 4028: 	$result .= '</span><br />';
 4029:     }
 4030:     $result.=&show_grading_menu_form($symb);
 4031:     return $result;
 4032: }
 4033: 
 4034: #--- call by previous routine to display each student who satisfies submission filter.
 4035: sub viewstudentgrade {
 4036:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 4037:     my ($uname,$udom) = split(/:/,$student);
 4038:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4039:     my $submitonly = $env{'form.submitonly'};
 4040:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4041:         my %partstatus = ();
 4042:         if (ref($parts) eq 'ARRAY') {
 4043:             foreach my $apart (@{$parts}) {
 4044:                 my ($part,$type) = &split_part_type($apart);
 4045:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4046:                 $status = 'nothing' if ($status eq '');
 4047:                 $partstatus{$part}      = $status;
 4048:                 my $subkey = "resource.$part.submitted_by";
 4049:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4050:             }
 4051:             my $submitted = 0;
 4052:             my $graded = 0;
 4053:             my $incorrect = 0;
 4054:             foreach my $key (keys(%partstatus)) {
 4055:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4056:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4057:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4058: 
 4059:                 my $partid = (split(/\./,$key))[1];
 4060:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4061:                     $submitted = 0;
 4062:                 }
 4063:             }
 4064:             return if (!$submitted && ($submitonly eq 'yes' ||
 4065:                                        $submitonly eq 'incorrect' ||
 4066:                                        $submitonly eq 'graded'));
 4067:             return if (!$graded && ($submitonly eq 'graded'));
 4068:             return if (!$incorrect && $submitonly eq 'incorrect');
 4069:         }
 4070:     }
 4071:     if ($submitonly eq 'queued') {
 4072:         my ($cdom,$cnum) = split(/_/,$courseid);
 4073:         my %queue_status =
 4074:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4075:                                                     $udom,$uname);
 4076:         return if (!defined($queue_status{'gradingqueue'}));
 4077:     }
 4078:     $$ctr++;
 4079:     my %aggregates = ();
 4080:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4081: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4082: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4083: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4084: 	'\');" target="_self">'.$fullname.'</a> '.
 4085: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4086:     $student=~s/:/_/; # colon doen't work in javascript for names
 4087:     foreach my $apart (@$parts) {
 4088: 	my ($part,$type) = &split_part_type($apart);
 4089: 	my $score=$record{"resource.$part.$type"};
 4090:         $result.='<td align="center">';
 4091:         my ($aggtries,$totaltries);
 4092:         unless (exists($aggregates{$part})) {
 4093: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4094: 
 4095: 	    $aggtries = $totaltries;
 4096:             if ($$last_resets{$part}) {  
 4097:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4098: 					   $part);
 4099:             }
 4100:             $result.='<input type="hidden" name="'.
 4101:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4102:             $result.='<input type="hidden" name="'.
 4103:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4104:             $aggregates{$part} = 1;
 4105:         }
 4106: 	if ($type eq 'awarded') {
 4107: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4108: 	    $result.='<input type="hidden" name="'.
 4109: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4110: 	    $result.='<input type="text" name="'.
 4111: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4112:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4113: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4114: 	} elsif ($type eq 'solved') {
 4115: 	    my ($status,$foo)=split(/_/,$score,2);
 4116: 	    $status = 'nothing' if ($status eq '');
 4117: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4118: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4119: 	    $result.='&nbsp;<select name="'.
 4120: 		'GD_'.$student.'_'.$part.'_solved" '.
 4121:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4122: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4123: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4124: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4125: 	    $result.="</select>&nbsp;</td>\n";
 4126: 	} else {
 4127: 	    $result.='<input type="hidden" name="'.
 4128: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4129: 		    "\n";
 4130: 	    $result.='<input type="text" name="'.
 4131: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4132: 		'value="'.$score.'" size="4" /></td>'."\n";
 4133: 	}
 4134:     }
 4135:     $result.=&Apache::loncommon::end_data_table_row();
 4136:     return $result;
 4137: }
 4138: 
 4139: #--- change scores for all the students in a section/class
 4140: #    record does not get update if unchanged
 4141: sub editgrades {
 4142:     my ($request) = @_;
 4143: 
 4144:     my ($symb)=&get_symb($request);
 4145:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4146:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4147:     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
 4148:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
 4149: 
 4150:     my $result= &Apache::loncommon::start_data_table().
 4151: 	&Apache::loncommon::start_data_table_header_row().
 4152: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4153: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4154:     my %scoreptr = (
 4155: 		    'correct'  =>'correct_by_override',
 4156: 		    'incorrect'=>'incorrect_by_override',
 4157: 		    'excused'  =>'excused',
 4158: 		    'ungraded' =>'ungraded_attempted',
 4159:                     'credited' =>'credit_attempted',
 4160: 		    'nothing'  => '',
 4161: 		    );
 4162:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4163: 
 4164:     my (@partid);
 4165:     my %weight = ();
 4166:     my %columns = ();
 4167:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4168: 
 4169:     my $partserror;
 4170:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4171:     if ($partserror) {
 4172:         return &navmap_errormsg();
 4173:     }
 4174:     my $header;
 4175:     while ($ctr < $env{'form.totalparts'}) {
 4176: 	my $partid = $env{'form.partid_'.$ctr};
 4177: 	push(@partid,$partid);
 4178: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4179: 	$ctr++;
 4180:     }
 4181:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4182:     my $totcolspan = 0;
 4183:     foreach my $partid (@partid) {
 4184: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4185: 	    '<th align="center">'.&mt('New Score').'</th>';
 4186: 	$columns{$partid}=2;
 4187: 	foreach my $stores (@parts) {
 4188: 	    my ($part,$type) = &split_part_type($stores);
 4189: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4190: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4191: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 4192: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4193:             my $narrowtext = &mt('Tries');
 4194: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4195: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4196: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4197: 	    $columns{$partid}+=2;
 4198: 	}
 4199:         $totcolspan += $columns{$partid};
 4200:     }
 4201:     foreach my $partid (@partid) {
 4202: 	my $display_part=&get_display_part($partid,$symb);
 4203: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4204: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4205: 	    '</th>';
 4206: 
 4207:     }
 4208:     $result .= &Apache::loncommon::end_data_table_header_row().
 4209: 	&Apache::loncommon::start_data_table_header_row().
 4210: 	$header.
 4211: 	&Apache::loncommon::end_data_table_header_row();
 4212:     my @noupdate;
 4213:     my ($updateCtr,$noupdateCtr) = (1,1);
 4214:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4215: 	my $user = $env{'form.ctr'.$i};
 4216: 	my ($uname,$udom)=split(/:/,$user);
 4217: 	my %newrecord;
 4218: 	my $updateflag = 0;
 4219:         my $usec=$classlist->{"$uname:$udom"}[5];
 4220:         my $canmodify = &canmodify($usec);
 4221:         my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4222:                    &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4223:         if (!$canmodify) {
 4224:             push(@noupdate,
 4225:                  $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4226:                  &mt('Not allowed to modify student')."</span></td>");
 4227:             next;
 4228:         }
 4229:         my %aggregate = ();
 4230:         my $aggregateflag = 0;
 4231: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4232: 	foreach (@partid) {
 4233: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4234: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4235: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4236: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4237: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4238: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4239: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4240: 	    my $score;
 4241: 	    if ($partial eq '') {
 4242: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4243: 	    } elsif ($partial > 0) {
 4244: 		$score = 'correct_by_override';
 4245: 	    } elsif ($partial == 0) {
 4246: 		$score = 'incorrect_by_override';
 4247: 	    }
 4248: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4249: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4250: 
 4251: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4252: 		"$env{'user.name'}:$env{'user.domain'}";
 4253: 	    if ($dropMenu eq 'reset status' &&
 4254: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4255: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4256: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4257: 		$newrecord{'resource.'.$_.'.award'} = '';
 4258: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4259: 		$updateflag = 1;
 4260:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4261:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4262:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4263:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4264:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4265:                     $aggregateflag = 1;
 4266:                 }
 4267: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4268: 		$updateflag = 1;
 4269: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4270: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4271: 		$rec_update++;
 4272: 	    }
 4273: 
 4274: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4275: 		'<td align="center">'.$awarded.
 4276: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4277: 
 4278: 
 4279: 	    my $partid=$_;
 4280: 	    foreach my $stores (@parts) {
 4281: 		my ($part,$type) = &split_part_type($stores);
 4282: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4283: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4284: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4285: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4286: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4287: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4288: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4289: 		    $updateflag=1;
 4290: 		}
 4291: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4292: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4293: 	    }
 4294: 	}
 4295: 	$line.="\n";
 4296: 
 4297: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4298: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4299: 
 4300: 	if ($updateflag) {
 4301: 	    $count++;
 4302: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4303: 				    $udom,$uname);
 4304: 
 4305: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4306: 					      $cnum,$udom,$uname)) {
 4307: 		# need to figure out if should be in queue.
 4308: 		my %record =  
 4309: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4310: 					     $udom,$uname);
 4311: 		my $all_graded = 1;
 4312: 		my $none_graded = 1;
 4313: 		foreach my $part (@parts) {
 4314: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4315: 			$all_graded = 0;
 4316: 		    } else {
 4317: 			$none_graded = 0;
 4318: 		    }
 4319: 		}
 4320: 
 4321: 		if ($all_graded || $none_graded) {
 4322: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4323: 							   $symb,$cdom,$cnum,
 4324: 							   $udom,$uname);
 4325: 		}
 4326: 	    }
 4327: 
 4328: 	    $result.=&Apache::loncommon::start_data_table_row().
 4329: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4330: 		&Apache::loncommon::end_data_table_row();
 4331: 	    $updateCtr++;
 4332: 	} else {
 4333: 	    push(@noupdate,
 4334: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4335: 	    $noupdateCtr++;
 4336: 	}
 4337:         if ($aggregateflag) {
 4338:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4339: 				  $cdom,$cnum);
 4340:         }
 4341:     }
 4342:     if (@noupdate) {
 4343:         my $numcols=$totcolspan+2;
 4344: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4345: 	    '<td align="center" colspan="'.$numcols.'">'.
 4346: 	    &mt('No Changes Occurred For the Students Below').
 4347: 	    '</td>'.
 4348: 	    &Apache::loncommon::end_data_table_row();
 4349: 	foreach my $line (@noupdate) {
 4350: 	    $result.=
 4351: 		&Apache::loncommon::start_data_table_row().
 4352: 		$line.
 4353: 		&Apache::loncommon::end_data_table_row();
 4354: 	}
 4355:     }
 4356:     $result .= &Apache::loncommon::end_data_table().
 4357: 	&show_grading_menu_form($symb);
 4358:     my $msg = '<p><b>'.
 4359: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4360: 	    $rec_update,$count).'</b><br />'.
 4361: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4362: 	'</b></p>';
 4363:     return $title.$msg.$result;
 4364: }
 4365: 
 4366: sub split_part_type {
 4367:     my ($partstr) = @_;
 4368:     my ($temp,@allparts)=split(/_/,$partstr);
 4369:     my $type=pop(@allparts);
 4370:     my $part=join('_',@allparts);
 4371:     return ($part,$type);
 4372: }
 4373: 
 4374: #------------- end of section for handling grading by section/class ---------
 4375: #
 4376: #----------------------------------------------------------------------------
 4377: 
 4378: 
 4379: #----------------------------------------------------------------------------
 4380: #
 4381: #-------------------------- Next few routines handles grading by csv upload
 4382: #
 4383: #--- Javascript to handle csv upload
 4384: sub csvupload_javascript_reverse_associate {
 4385:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4386:     my $error2=&mt('You need to specify at least one grading field');
 4387:   &js_escape(\$error1);
 4388:   &js_escape(\$error2);
 4389:   return(<<ENDPICK);
 4390:   function verify(vf) {
 4391:     var foundsomething=0;
 4392:     var founduname=0;
 4393:     var foundID=0;
 4394:     for (i=0;i<=vf.nfields.value;i++) {
 4395:       tw=eval('vf.f'+i+'.selectedIndex');
 4396:       if (i==0 && tw!=0) { foundID=1; }
 4397:       if (i==1 && tw!=0) { founduname=1; }
 4398:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 4399:     }
 4400:     if (founduname==0 && foundID==0) {
 4401: 	alert('$error1');
 4402: 	return;
 4403:     }
 4404:     if (foundsomething==0) {
 4405: 	alert('$error2');
 4406: 	return;
 4407:     }
 4408:     vf.submit();
 4409:   }
 4410:   function flip(vf,tf) {
 4411:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4412:     var i;
 4413:     for (i=0;i<=vf.nfields.value;i++) {
 4414:       //can not pick the same destination field for both name and domain
 4415:       if (((i ==0)||(i ==1)) && 
 4416:           ((tf==0)||(tf==1)) && 
 4417:           (i!=tf) &&
 4418:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4419:         eval('vf.f'+i+'.selectedIndex=0;')
 4420:       }
 4421:     }
 4422:   }
 4423: ENDPICK
 4424: }
 4425: 
 4426: sub csvupload_javascript_forward_associate {
 4427:     my $error1=&mt('You need to specify the username or the student/employee ID');
 4428:     my $error2=&mt('You need to specify at least one grading field');
 4429:   &js_escape(\$error1);
 4430:   &js_escape(\$error2);
 4431:   return(<<ENDPICK);
 4432:   function verify(vf) {
 4433:     var foundsomething=0;
 4434:     var founduname=0;
 4435:     var foundID=0;
 4436:     for (i=0;i<=vf.nfields.value;i++) {
 4437:       tw=eval('vf.f'+i+'.selectedIndex');
 4438:       if (tw==1) { foundID=1; }
 4439:       if (tw==2) { founduname=1; }
 4440:       if (tw>3) { foundsomething=1; }
 4441:     }
 4442:     if (founduname==0 && foundID==0) {
 4443: 	alert('$error1');
 4444: 	return;
 4445:     }
 4446:     if (foundsomething==0) {
 4447: 	alert('$error2');
 4448: 	return;
 4449:     }
 4450:     vf.submit();
 4451:   }
 4452:   function flip(vf,tf) {
 4453:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4454:     var i;
 4455:     //can not pick the same destination field twice
 4456:     for (i=0;i<=vf.nfields.value;i++) {
 4457:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4458:         eval('vf.f'+i+'.selectedIndex=0;')
 4459:       }
 4460:     }
 4461:   }
 4462: ENDPICK
 4463: }
 4464: 
 4465: sub csvuploadmap_header {
 4466:     my ($request,$symb,$datatoken,$distotal)= @_;
 4467:     my $javascript;
 4468:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4469: 	$javascript=&csvupload_javascript_reverse_associate();
 4470:     } else {
 4471: 	$javascript=&csvupload_javascript_forward_associate();
 4472:     }
 4473: 
 4474:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 4475:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 4476:     my $ignore=&mt('Ignore First Line');
 4477:     $symb = &Apache::lonenc::check_encrypt($symb);
 4478:     $request->print(<<ENDPICK);
 4479: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4480: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 4481: $result
 4482: <hr />
 4483: <h3>Identify fields</h3>
 4484: Total number of records found in file: $distotal <hr />
 4485: Enter as many fields as you can. The system will inform you and bring you back
 4486: to this page if the data selected is insufficient to run your class.<hr />
 4487: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4488: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 4489: <input type="hidden" name="associate"  value="" />
 4490: <input type="hidden" name="phase"      value="three" />
 4491: <input type="hidden" name="datatoken"  value="$datatoken" />
 4492: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4493: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4494: <input type="hidden" name="upfile_associate" 
 4495:                                        value="$env{'form.upfile_associate'}" />
 4496: <input type="hidden" name="symb"       value="$symb" />
 4497: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4498: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 4499: <input type="hidden" name="command"    value="csvuploadoptions" />
 4500: <hr />
 4501: <script type="text/javascript" language="Javascript">
 4502: $javascript
 4503: </script>
 4504: ENDPICK
 4505:     return '';
 4506: 
 4507: }
 4508: 
 4509: sub csvupload_fields {
 4510:     my ($symb,$errorref) = @_;
 4511:     my (@parts) = &getpartlist($symb,$errorref);
 4512:     if (ref($errorref)) {
 4513:         if ($$errorref) {
 4514:             return;
 4515:         }
 4516:     }
 4517: 
 4518:     my @fields=(['ID','Student/Employee ID'],
 4519: 		['username','Student Username'],
 4520: 		['domain','Student Domain']);
 4521:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4522:     foreach my $part (sort(@parts)) {
 4523: 	my @datum;
 4524: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 4525: 	my $name=$part;
 4526: 	if  (!$display) { $display = $name; }
 4527: 	@datum=($name,$display);
 4528: 	if ($name=~/^stores_(.*)_awarded/) {
 4529: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4530: 	}
 4531: 	push(@fields,\@datum);
 4532:     }
 4533:     return (@fields);
 4534: }
 4535: 
 4536: sub csvuploadmap_footer {
 4537:     my ($request,$i,$keyfields) =@_;
 4538:     my $buttontext = &mt('Assign Grades');
 4539:     $request->print(<<ENDPICK);
 4540: </table>
 4541: <input type="hidden" name="nfields" value="$i" />
 4542: <input type="hidden" name="keyfields" value="$keyfields" />
 4543: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4544: </form>
 4545: ENDPICK
 4546: }
 4547: 
 4548: sub checkforfile_js {
 4549:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4550:     &js_escape(\$alertmsg);
 4551:     my $result =<<CSVFORMJS;
 4552: <script type="text/javascript" language="javascript">
 4553:     function checkUpload(formname) {
 4554: 	if (formname.upfile.value == "") {
 4555: 	    alert("$alertmsg");
 4556: 	    return false;
 4557: 	}
 4558: 	formname.submit();
 4559:     }
 4560:     </script>
 4561: CSVFORMJS
 4562:     return $result;
 4563: }
 4564: 
 4565: sub upcsvScores_form {
 4566:     my ($request) = shift;
 4567:     my ($symb)=&get_symb($request);
 4568:     if (!$symb) {return '';}
 4569:     my $result=&checkforfile_js();
 4570:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4571:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4572:     $result.=$table;
 4573:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4574:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4575:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4576: 	'</b></td></tr>'."\n";
 4577:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
 4578:     my $upload=&mt("Upload Scores");
 4579:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4580:     my $ignore=&mt('Ignore First Line');
 4581:     $symb = &Apache::lonenc::check_encrypt($symb);
 4582:     $result.=<<ENDUPFORM;
 4583: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4584: <input type="hidden" name="symb" value="$symb" />
 4585: <input type="hidden" name="command" value="csvuploadmap" />
 4586: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4587: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4588: $upfile_select
 4589: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4590: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4591: </form>
 4592: ENDUPFORM
 4593:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4594:                            &mt("How do I create a CSV file from a spreadsheet"))
 4595:     .'</td></tr></table>'."\n";
 4596:     $result.='</td></tr></table><br /><br />'."\n";
 4597:     $result.=&show_grading_menu_form($symb);
 4598:     return $result;
 4599: }
 4600: 
 4601: 
 4602: sub csvuploadmap {
 4603:     my ($request)= @_;
 4604:     my ($symb)=&get_symb($request);
 4605:     if (!$symb) {return '';}
 4606: 
 4607:     my $datatoken;
 4608:     if (!$env{'form.datatoken'}) {
 4609: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4610:     } else {
 4611:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4612:         if ($datatoken ne '') { 
 4613: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4614:         }
 4615:     }
 4616:     my @records=&Apache::loncommon::upfile_record_sep();
 4617:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4618:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4619:     my ($i,$keyfields);
 4620:     if (@records) {
 4621:         my $fieldserror;
 4622: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4623:         if ($fieldserror) {
 4624:             $request->print(&navmap_errormsg());
 4625:             return;
 4626:         }
 4627: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4628: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4629: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4630: 							  \@fields);
 4631: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4632: 	    chop($keyfields);
 4633: 	} else {
 4634: 	    unshift(@fields,['none','']);
 4635: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4636: 							    \@fields);
 4637:             foreach my $rec (@records) {
 4638:                 my %temp = &Apache::loncommon::record_sep($rec);
 4639:                 if (%temp) {
 4640:                     $keyfields=join(',',sort(keys(%temp)));
 4641:                     last;
 4642:                 }
 4643:             }
 4644: 	}
 4645:     }
 4646:     &csvuploadmap_footer($request,$i,$keyfields);
 4647:     $request->print(&show_grading_menu_form($symb));
 4648: 
 4649:     return '';
 4650: }
 4651: 
 4652: sub csvuploadoptions {
 4653:     my ($request)= @_;
 4654:     my ($symb)=&get_symb($request);
 4655:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4656:     my $ignore=&mt('Ignore First Line');
 4657:     $request->print(<<ENDPICK);
 4658: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4659: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4660: <input type="hidden" name="command"    value="csvuploadassign" />
 4661: <!--
 4662: <p>
 4663: <label>
 4664:    <input type="checkbox" name="show_full_results" />
 4665:    Show a table of all changes
 4666: </label>
 4667: </p>
 4668: -->
 4669: <p>
 4670: <label>
 4671:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4672:    Overwrite any existing score
 4673: </label>
 4674: </p>
 4675: ENDPICK
 4676:     my %fields=&get_fields();
 4677:     if (!defined($fields{'domain'})) {
 4678: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4679: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4680:     }
 4681:     foreach my $key (sort(keys(%env))) {
 4682: 	if ($key !~ /^form\.(.*)$/) { next; }
 4683: 	my $cleankey=$1;
 4684: 	if ($cleankey eq 'command') { next; }
 4685: 	$request->print('<input type="hidden" name="'.$cleankey.
 4686: 			'"  value="'.$env{$key}.'" />'."\n");
 4687:     }
 4688:     # FIXME do a check for any duplicated user ids...
 4689:     # FIXME do a check for any invalid user ids?...
 4690:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4691: <hr /></form>'."\n");
 4692:     $request->print(&show_grading_menu_form($symb));
 4693:     return '';
 4694: }
 4695: 
 4696: sub get_fields {
 4697:     my %fields;
 4698:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4699:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4700: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4701: 	    if ($env{'form.f'.$i} ne 'none') {
 4702: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4703: 	    }
 4704: 	} else {
 4705: 	    if ($env{'form.f'.$i} ne 'none') {
 4706: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4707: 	    }
 4708: 	}
 4709:     }
 4710:     return %fields;
 4711: }
 4712: 
 4713: sub csvuploadassign {
 4714:     my ($request)= @_;
 4715:     my ($symb)=&get_symb($request);
 4716:     if (!$symb) {return '';}
 4717:     my $error_msg = '';
 4718:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4719:     if ($datatoken ne '') {
 4720:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4721:     }
 4722:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4723:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4724:     my %fields=&get_fields();
 4725:     $request->print('<h3>Assigning Grades</h3>');
 4726:     my $courseid=$env{'request.course.id'};
 4727:     my ($classlist) = &getclasslist('all',0);
 4728:     my @notallowed;
 4729:     my @skipped;
 4730:     my @warnings;
 4731:     my $countdone=0;
 4732:     foreach my $grade (@gradedata) {
 4733: 	my %entries=&Apache::loncommon::record_sep($grade);
 4734: 	my $domain;
 4735: 	if ($entries{$fields{'domain'}}) {
 4736: 	    $domain=$entries{$fields{'domain'}};
 4737: 	} else {
 4738: 	    $domain=$env{'form.default_domain'};
 4739: 	}
 4740: 	$domain=~s/\s//g;
 4741: 	my $username=$entries{$fields{'username'}};
 4742: 	$username=~s/\s//g;
 4743: 	if (!$username) {
 4744: 	    my $id=$entries{$fields{'ID'}};
 4745: 	    $id=~s/\s//g;
 4746: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4747: 	    $username=$ids{$id};
 4748: 	}
 4749: 	if (!exists($$classlist{"$username:$domain"})) {
 4750: 	    my $id=$entries{$fields{'ID'}};
 4751: 	    $id=~s/\s//g;
 4752: 	    if ($id) {
 4753: 		push(@skipped,"$id:$domain");
 4754: 	    } else {
 4755: 		push(@skipped,"$username:$domain");
 4756: 	    }
 4757: 	    next;
 4758: 	}
 4759: 	my $usec=$classlist->{"$username:$domain"}[5];
 4760: 	if (!&canmodify($usec)) {
 4761: 	    push(@notallowed,"$username:$domain");
 4762: 	    next;
 4763: 	}
 4764: 	my %points;
 4765: 	my %grades;
 4766: 	foreach my $dest (keys(%fields)) {
 4767: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4768: 		$dest eq 'domain') { next; }
 4769: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4770: 	    if ($dest=~/stores_(.*)_points/) {
 4771: 		my $part=$1;
 4772: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4773: 					      $symb,$domain,$username);
 4774:                 if ($wgt) {
 4775:                     $entries{$fields{$dest}}=~s/\s//g;
 4776:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4777:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4778:                                           : 'correct_by_override';
 4779:                     if ($pcr>1) {
 4780:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4781:                     }
 4782:                     $grades{"resource.$part.awarded"}=$pcr;
 4783:                     $grades{"resource.$part.solved"}=$award;
 4784:                     $points{$part}=1;
 4785:                 } else {
 4786:                     $error_msg = "<br />" .
 4787:                         &mt("Some point values were assigned"
 4788:                             ." for problems with a weight "
 4789:                             ."of zero. These values were "
 4790:                             ."ignored.");
 4791:                 }
 4792: 	    } else {
 4793: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4794: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4795: 		my $store_key=$dest;
 4796: 		$store_key=~s/^stores/resource/;
 4797: 		$store_key=~s/_/\./g;
 4798: 		$grades{$store_key}=$entries{$fields{$dest}};
 4799: 	    }
 4800: 	}
 4801: 	if (! %grades) { 
 4802:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4803:         } else {
 4804: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4805: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4806: 					   $env{'request.course.id'},
 4807: 					   $domain,$username);
 4808: 	   if ($result eq 'ok') {
 4809: 	      $request->print('.');
 4810: # Remove from grading queue
 4811:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4812:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4813:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4814:                                              $domain,$username);
 4815: 	   } else {
 4816: 	      $request->print("<p><span class=\"LC_error\">".
 4817:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4818:                                   "$username:$domain",$result)."</span></p>");
 4819: 	   }
 4820: 	   $request->rflush();
 4821: 	   $countdone++;
 4822:         }
 4823:     }
 4824:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4825:     if (@warnings) {
 4826:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4827:         $request->print(join(', ',@warnings));
 4828:     }
 4829:     if (@skipped) {
 4830: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4831:         $request->print(join(', ',@skipped));
 4832:     }
 4833:     if (@notallowed) {
 4834: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4835: 	$request->print(join(', ',@notallowed));
 4836:     }
 4837:     $request->print("<br />\n");
 4838:     $request->print(&show_grading_menu_form($symb));
 4839:     return $error_msg;
 4840: }
 4841: #------------- end of section for handling csv file upload ---------
 4842: #
 4843: #-------------------------------------------------------------------
 4844: #
 4845: #-------------- Next few routines handle grading by page/sequence
 4846: #
 4847: #--- Select a page/sequence and a student to grade
 4848: sub pickStudentPage {
 4849:     my ($request) = shift;
 4850: 
 4851:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4852:     &js_escape(\$alertmsg);
 4853:     $request->print(<<LISTJAVASCRIPT);
 4854: <script type="text/javascript" language="javascript">
 4855: 
 4856: function checkPickOne(formname) {
 4857:     if (radioSelection(formname.student) == null) {
 4858: 	alert("$alertmsg");
 4859: 	return;
 4860:     }
 4861:     ptr = pullDownSelection(formname.selectpage);
 4862:     formname.page.value = formname["page"+ptr].value;
 4863:     formname.title.value = formname["title"+ptr].value;
 4864:     formname.submit();
 4865: }
 4866: 
 4867: </script>
 4868: LISTJAVASCRIPT
 4869:     &commonJSfunctions($request);
 4870:     my ($symb) = &get_symb($request);
 4871:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4872:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4873:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4874: 
 4875:     my $result='<h3><span class="LC_info">&nbsp;'.
 4876: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4877: 
 4878:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4879:     my $map_error;
 4880:     my ($titles,$symbx) = &getSymbMap($map_error);
 4881:     if ($map_error) {
 4882:         $request->print(&navmap_errormsg());
 4883:         return; 
 4884:     }
 4885:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4886: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4887: #    my $type=($curpage =~ /\.(page|sequence)/);
 4888:     my $select = '<select name="selectpage">'."\n";
 4889:     my $ctr=0;
 4890:     foreach (@$titles) {
 4891: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4892: 	$select.='<option value="'.$ctr.'" '.
 4893: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4894: 	    '>'.$showtitle.'</option>'."\n";
 4895: 	$ctr++;
 4896:     }
 4897:     $select.= '</select>';
 4898:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4899: 
 4900:     $ctr=0;
 4901:     foreach (@$titles) {
 4902: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4903: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4904: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4905: 	$ctr++;
 4906:     }
 4907:     $result.='<input type="hidden" name="page" />'."\n".
 4908: 	'<input type="hidden" name="title" />'."\n";
 4909: 
 4910:     my $options =
 4911: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4912: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4913:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4914: 
 4915:     $options =
 4916: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4917: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4918: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4919:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4920:     
 4921:     $result.=&build_section_inputs();
 4922:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4923:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4924: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4925: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4926: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4927: 
 4928:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4929: 
 4930:     $result.='&nbsp;<input type="button" '.
 4931:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4932: 
 4933:     $request->print($result);
 4934: 
 4935:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4936: 	&Apache::loncommon::start_data_table().
 4937: 	&Apache::loncommon::start_data_table_header_row().
 4938: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4939: 	'<th>'.&nameUserString('header').'</th>'.
 4940: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4941: 	'<th>'.&nameUserString('header').'</th>'.
 4942: 	&Apache::loncommon::end_data_table_header_row();
 4943:  
 4944:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4945:     my $ptr = 1;
 4946:     foreach my $student (sort 
 4947: 			 {
 4948: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4949: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4950: 			     }
 4951: 			     return $a cmp $b;
 4952: 			 } (keys(%$fullname))) {
 4953: 	my ($uname,$udom) = split(/:/,$student);
 4954: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4955:                                   : '</td>');
 4956: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4957: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4958: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4959: 	$studentTable.=
 4960: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4961:                          : '');
 4962: 	$ptr++;
 4963:     }
 4964:     if ($ptr%2 == 0) {
 4965: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4966: 	    &Apache::loncommon::end_data_table_row();
 4967:     }
 4968:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4969:     $studentTable.='<input type="button" '.
 4970:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4971: 
 4972:     $studentTable.=&show_grading_menu_form($symb);
 4973:     $request->print($studentTable);
 4974: 
 4975:     return '';
 4976: }
 4977: 
 4978: sub getSymbMap {
 4979:     my ($map_error) = @_;
 4980:     my $navmap = Apache::lonnavmaps::navmap->new();
 4981:     unless (ref($navmap)) {
 4982:         if (ref($map_error)) {
 4983:             $$map_error = 'navmap';
 4984:         }
 4985:         return;
 4986:     }
 4987:     my %symbx = ();
 4988:     my @titles = ();
 4989:     my $minder = 0;
 4990: 
 4991:     # Gather every sequence that has problems.
 4992:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4993: 					       1,0,1);
 4994:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4995: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4996: 	    my $title = $minder.'.'.
 4997: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4998: 	    push(@titles, $title); # minder in case two titles are identical
 4999: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5000: 	    $minder++;
 5001: 	}
 5002:     }
 5003:     return \@titles,\%symbx;
 5004: }
 5005: 
 5006: #
 5007: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5008: sub displayPage {
 5009:     my ($request) = shift;
 5010: 
 5011:     my ($symb) = &get_symb($request);
 5012:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5013:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5014:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5015:     my $pageTitle = $env{'form.page'};
 5016:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5017:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5018:     my $usec=$classlist->{$env{'form.student'}}[5];
 5019: 
 5020:     #need to make sure we have the correct data for later EXT calls, 
 5021:     #thus invalidate the cache
 5022:     &Apache::lonnet::devalidatecourseresdata(
 5023:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5024:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5025:     &Apache::lonnet::clear_EXT_cache_status();
 5026: 
 5027:     if (!&canview($usec)) {
 5028: 	$request->print('<span class="LC_warning">'.
 5029:                         &mt('Unable to view requested student. ([_1])',
 5030:                             $env{'form.student'}).
 5031:                         '</span>');
 5032:         $request->print(&show_grading_menu_form($symb));
 5033:         return;
 5034:     }
 5035:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5036:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5037: 	'</h3>'."\n";
 5038:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5039:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5040: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5041:     } else {
 5042: 	delete($env{'form.CODE'});
 5043:     }
 5044:     &sub_page_js($request);
 5045:     $request->print($result);
 5046: 
 5047:     my $navmap = Apache::lonnavmaps::navmap->new();
 5048:     unless (ref($navmap)) {
 5049:         $request->print(&navmap_errormsg());
 5050:         $request->print(&show_grading_menu_form($symb));
 5051:         return;
 5052:     }
 5053:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5054:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5055:     if (!$map) {
 5056: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5057: 	$request->print(&show_grading_menu_form($symb));
 5058: 	return; 
 5059:     }
 5060:     my $iterator = $navmap->getIterator($map->map_start(),
 5061: 					$map->map_finish());
 5062: 
 5063:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5064: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5065: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5066: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5067: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5068: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5069: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5070: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 5071: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 5072: 
 5073:     if (defined($env{'form.CODE'})) {
 5074: 	$studentTable.=
 5075: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5076:     }
 5077:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5078: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5079: 
 5080:     $studentTable.='&nbsp;<span class="LC_info">'.
 5081:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5082:         '</span>'."\n".
 5083: 	&Apache::loncommon::start_data_table().
 5084: 	&Apache::loncommon::start_data_table_header_row().
 5085: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 5086: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5087: 	&Apache::loncommon::end_data_table_header_row();
 5088: 
 5089:     &Apache::lonxml::clear_problem_counter();
 5090:     my ($depth,$question,$prob) = (1,1,1);
 5091:     $iterator->next(); # skip the first BEGIN_MAP
 5092:     my $curRes = $iterator->next(); # for "current resource"
 5093:     while ($depth > 0) {
 5094:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5095:         if($curRes == $iterator->END_MAP) { $depth--; }
 5096: 
 5097:         if (ref($curRes) && $curRes->is_problem()) {
 5098: 	    my $parts = $curRes->parts();
 5099:             my $title = $curRes->compTitle();
 5100: 	    my $symbx = $curRes->symb();
 5101: 	    $studentTable.=
 5102: 		&Apache::loncommon::start_data_table_row().
 5103: 		'<td align="center" valign="top" >'.$prob.
 5104: 		(scalar(@{$parts}) == 1 ? '' 
 5105: 		                        : '<br />('.&mt('[_1]parts',
 5106: 							scalar(@{$parts}).'&nbsp;').')'
 5107: 		 ).
 5108: 		 '</td>';
 5109: 	    $studentTable.='<td valign="top">';
 5110: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5111: 	    if ($env{'form.vProb'} eq 'yes' ) {
 5112: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5113: 					     undef,'both',\%form);
 5114: 	    } else {
 5115: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5116: 		$companswer =~ s|<form(.*?)>||g;
 5117: 		$companswer =~ s|</form>||g;
 5118: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5119: #		    $companswer =~ s/$1/ /ms;
 5120: #		    $request->print('match='.$1."<br />\n");
 5121: #		}
 5122: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5123: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5124: 	    }
 5125: 
 5126: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5127: 
 5128: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5129: 		if ($record{'version'} eq '') {
 5130: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 5131: 		} else {
 5132: 		    my %responseType = ();
 5133: 		    foreach my $partid (@{$parts}) {
 5134: 			my @responseIds =$curRes->responseIds($partid);
 5135: 			my @responseType =$curRes->responseType($partid);
 5136: 			my %responseIds;
 5137: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5138: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5139: 			}
 5140: 			$responseType{$partid} = \%responseIds;
 5141: 		    }
 5142: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5143: 
 5144: 		}
 5145: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5146: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5147:                 my $identifier = (&canmodify($usec)? $prob : '');
 5148: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5149: 									$env{'request.course.id'},
 5150: 									'','.submission',undef,
 5151:                                                                         $usec,$identifier);
 5152:  
 5153: 	    }
 5154: 	    if (&canmodify($usec)) {
 5155:             $studentTable.=&gradeBox_start();
 5156: 		foreach my $partid (@{$parts}) {
 5157: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5158: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5159: 		    $question++;
 5160: 		}
 5161:             $studentTable.=&gradeBox_end();
 5162: 		$prob++;
 5163: 	    }
 5164: 	    $studentTable.='</td></tr>';
 5165: 
 5166: 	}
 5167:         $curRes = $iterator->next();
 5168:     }
 5169: 
 5170:     $studentTable.=
 5171:         '</table>'."\n".
 5172:         '<input type="button" value="'.&mt('Save').'" '.
 5173:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5174:         '</form>'."\n";
 5175:     $studentTable.=&show_grading_menu_form($symb);
 5176:     $request->print($studentTable);
 5177: 
 5178:     return '';
 5179: }
 5180: 
 5181: sub displaySubByDates {
 5182:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5183:     my $isCODE=0;
 5184:     my $isTask = ($symb =~/\.task$/);
 5185:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5186:     my $studentTable=&Apache::loncommon::start_data_table().
 5187: 	&Apache::loncommon::start_data_table_header_row().
 5188: 	'<th>'.&mt('Date/Time').'</th>'.
 5189: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5190:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5191: 	'<th>'.&mt('Submission').'</th>'.
 5192: 	'<th>'.&mt('Status').'</th>'.
 5193: 	&Apache::loncommon::end_data_table_header_row();
 5194:     my ($version);
 5195:     my %mark;
 5196:     my %orders;
 5197:     $mark{'correct_by_student'} = $checkIcon;
 5198:     if (!exists($$record{'1:timestamp'})) {
 5199: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5200:     }
 5201: 
 5202:     my $interaction;
 5203:     my $no_increment = 1;
 5204:     my (%lastrndseed,%lasttype);
 5205:     for ($version=1;$version<=$$record{'version'};$version++) {
 5206: 	my $timestamp = 
 5207: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5208: 	if (exists($$record{$version.':resource.0.version'})) {
 5209: 	    $interaction = $$record{$version.':resource.0.version'};
 5210: 	}
 5211:         if ($isTask && $env{'form.previousversion'}) {
 5212:             next unless ($interaction == $env{'form.previousversion'});
 5213:         }
 5214: 	my $where = ($isTask ? "$version:resource.$interaction"
 5215: 		             : "$version:resource");
 5216: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5217: 	    '<td>'.$timestamp.'</td>';
 5218: 	if ($isCODE) {
 5219: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5220: 	}
 5221:         if ($isTask) {
 5222:             $studentTable.='<td>'.$interaction.'</td>';
 5223:         }
 5224: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5225: 	my @displaySub = ();
 5226: 	foreach my $partid (@{$parts}) {
 5227:             my ($hidden,$type);
 5228:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5229:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5230:                 $hidden = 1;
 5231:             }
 5232: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 5233: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 5234: 	    
 5235: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5236: 	    my $display_part=&get_display_part($partid,$symb);
 5237: 	    foreach my $matchKey (@matchKey) {
 5238: 		if (exists($$record{$version.':'.$matchKey}) &&
 5239: 		    $$record{$version.':'.$matchKey} ne '') {
 5240:                     
 5241: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5242: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5243:                     $displaySub[0].='<span class="LC_nobreak">';
 5244:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5245:                                    .' <span class="LC_internal_info">'
 5246:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
 5247:                                    .'</span>'
 5248:                                    .' <b>';
 5249:                     if ($hidden) {
 5250:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5251:                     } else {
 5252:                         my ($trial,$rndseed,$newvariation);
 5253:                         if ($type eq 'randomizetry') {
 5254:                             $trial = $$record{"$where.$partid.tries"};
 5255:                             $rndseed = $$record{"$where.$partid.rndseed"};
 5256:                         }
 5257: 		        if ($$record{"$where.$partid.tries"} eq '') {
 5258: 			    $displaySub[0].=&mt('Trial not counted');
 5259: 		        } else {
 5260: 			    $displaySub[0].=&mt('Trial: [_1]',
 5261: 					    $$record{"$where.$partid.tries"});
 5262:                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
 5263:                                 if (($rndseed ne $lastrndseed{$partid}) &&
 5264:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5265:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5266:                                 }
 5267:                             }
 5268:                             $lastrndseed{$partid} = $rndseed;
 5269:                             $lasttype{$partid} = $type;
 5270: 		        }
 5271: 		        my $responseType=($isTask ? 'Task'
 5272:                                               : $responseType->{$partid}->{$responseId});
 5273: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5274: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5275: 			    $orders{$partid}->{$responseId}=
 5276: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 5277:                                            $no_increment,$type,$trial,$rndseed);
 5278: 		        }
 5279: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5280: 		        $displaySub[0].='&nbsp; '.
 5281: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5282:                     }
 5283: 		}
 5284: 	    }
 5285: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5286: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5287: 				    $$record{"$where.$partid.checkedin"},
 5288: 				    $$record{"$where.$partid.checkedin.slot"}).
 5289: 					'<br />';
 5290: 	    }
 5291: 	    if (exists $$record{"$where.$partid.award"}) {
 5292: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5293: 		    lc($$record{"$where.$partid.award"}).' '.
 5294: 		    $mark{$$record{"$where.$partid.solved"}}.
 5295: 		    '<br />';
 5296: 	    }
 5297: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5298: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 5299: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5300: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5301: 		$displaySub[2].=
 5302: 		    $$record{"$version:resource.$partid.regrader"}.
 5303: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5304: 	    }
 5305: 	}
 5306: 	# needed because old essay regrader has not parts info
 5307: 	if (exists $$record{"$version:resource.regrader"}) {
 5308: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5309: 	}
 5310: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5311: 	if ($displaySub[2]) {
 5312: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5313: 	}
 5314: 	$studentTable.='&nbsp;</td>'.
 5315: 	    &Apache::loncommon::end_data_table_row();
 5316:     }
 5317:     $studentTable.=&Apache::loncommon::end_data_table();
 5318:     return $studentTable;
 5319: }
 5320: 
 5321: sub updateGradeByPage {
 5322:     my ($request) = shift;
 5323: 
 5324:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5325:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5326:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5327:     my $pageTitle = $env{'form.page'};
 5328:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5329:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5330:     my $usec=$classlist->{$env{'form.student'}}[5];
 5331:     if (!&canmodify($usec)) {
 5332: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5333: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 5334: 	return;
 5335:     }
 5336:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5337:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5338: 	'</h3>'."\n";
 5339: 
 5340:     $request->print($result);
 5341: 
 5342: 
 5343:     my $navmap = Apache::lonnavmaps::navmap->new();
 5344:     unless (ref($navmap)) {
 5345:         $request->print(&navmap_errormsg());
 5346:         return;
 5347:     }
 5348:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5349:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5350:     if (!$map) {
 5351: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5352: 	my ($symb)=&get_symb($request);
 5353: 	$request->print(&show_grading_menu_form($symb));
 5354: 	return; 
 5355:     }
 5356:     my $iterator = $navmap->getIterator($map->map_start(),
 5357: 					$map->map_finish());
 5358: 
 5359:     my $studentTable=
 5360: 	&Apache::loncommon::start_data_table().
 5361: 	&Apache::loncommon::start_data_table_header_row().
 5362: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5363: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5364: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5365: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5366: 	&Apache::loncommon::end_data_table_header_row();
 5367: 
 5368:     $iterator->next(); # skip the first BEGIN_MAP
 5369:     my $curRes = $iterator->next(); # for "current resource"
 5370:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5371:     while ($depth > 0) {
 5372:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5373:         if($curRes == $iterator->END_MAP) { $depth--; }
 5374: 
 5375:         if (ref($curRes) && $curRes->is_problem()) {
 5376: 	    my $parts = $curRes->parts();
 5377:             my $title = $curRes->compTitle();
 5378: 	    my $symbx = $curRes->symb();
 5379: 	    $studentTable.=
 5380: 		&Apache::loncommon::start_data_table_row().
 5381: 		'<td align="center" valign="top" >'.$prob.
 5382: 		(scalar(@{$parts}) == 1 ? '' 
 5383:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5384: 		.')').'</td>';
 5385: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5386: 
 5387: 	    my %newrecord=();
 5388: 	    my @displayPts=();
 5389:             my %aggregate = ();
 5390:             my $aggregateflag = 0;
 5391:             if ($env{'form.HIDE'.$prob}) {
 5392:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5393:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5394:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5395:                 $hideflag += $numchgs;
 5396:             }
 5397: 	    foreach my $partid (@{$parts}) {
 5398: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5399: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5400: 
 5401: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5402: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5403: 		my $partial = $newpts/$wgt;
 5404: 		my $score;
 5405: 		if ($partial > 0) {
 5406: 		    $score = 'correct_by_override';
 5407: 		} elsif ($newpts ne '') { #empty is taken as 0
 5408: 		    $score = 'incorrect_by_override';
 5409: 		}
 5410: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5411: 		if ($dropMenu eq 'excused') {
 5412: 		    $partial = '';
 5413: 		    $score = 'excused';
 5414: 		} elsif ($dropMenu eq 'reset status'
 5415: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5416: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5417: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5418: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5419: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5420: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5421: 		    $changeflag++;
 5422: 		    $newpts = '';
 5423:                     
 5424:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5425:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5426:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5427:                     if ($aggtries > 0) {
 5428:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5429:                         $aggregateflag = 1;
 5430:                     }
 5431: 		}
 5432: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5433: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5434: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5435: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5436: 		    '&nbsp;<br />';
 5437: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5438: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5439: 		    '&nbsp;<br />';
 5440: 		$question++;
 5441: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5442: 
 5443: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5444: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5445: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5446: 		    if (scalar(keys(%newrecord)) > 0);
 5447: 
 5448: 		$changeflag++;
 5449: 	    }
 5450: 	    if (scalar(keys(%newrecord)) > 0) {
 5451: 		my %record = 
 5452: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5453: 					     $udom,$uname);
 5454: 
 5455: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5456: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5457: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5458: 		    $newrecord{'resource.CODE'} = '';
 5459: 		}
 5460: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5461: 					$udom,$uname);
 5462: 		%record = &Apache::lonnet::restore($symbx,
 5463: 						   $env{'request.course.id'},
 5464: 						   $udom,$uname);
 5465: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5466: 					     $cdom,$cnum,$udom,$uname);
 5467: 	    }
 5468: 	    
 5469:             if ($aggregateflag) {
 5470:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5471:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5472:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5473:             }
 5474: 
 5475: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5476: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5477: 		&Apache::loncommon::end_data_table_row();
 5478: 
 5479: 	    $prob++;
 5480: 	}
 5481:         $curRes = $iterator->next();
 5482:     }
 5483: 
 5484:     $studentTable.=&Apache::loncommon::end_data_table();
 5485:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 5486:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5487: 		  &mt('The scores were changed for [quant,_1,problem].',
 5488: 		  $changeflag).'<br />');
 5489:     my $hidemsg=($hideflag == 0 ? '' :
 5490:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5491:                      $hideflag).'<br />');
 5492:     $request->print($hidemsg.$grademsg.$studentTable);
 5493: 
 5494:     return '';
 5495: }
 5496: 
 5497: #-------- end of section for handling grading by page/sequence ---------
 5498: #
 5499: #-------------------------------------------------------------------
 5500: 
 5501: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5502: #
 5503: #------ start of section for handling grading by page/sequence ---------
 5504: 
 5505: =pod
 5506: 
 5507: =head1 Bubble sheet grading routines
 5508: 
 5509:   For this documentation:
 5510: 
 5511:    'scanline' refers to the full line of characters
 5512:    from the file that we are parsing that represents one entire sheet
 5513: 
 5514:    'bubble line' refers to the data
 5515:    representing the line of bubbles that are on the physical bubblesheet
 5516: 
 5517: 
 5518: The overall process is that a scanned in bubblesheet data is uploaded
 5519: into a course. When a user wants to grade, they select a
 5520: sequence/folder of resources, a file of bubblesheet info, and pick
 5521: one of the predefined configurations for what each scanline looks
 5522: like.
 5523: 
 5524: Next each scanline is checked for any errors of either 'missing
 5525: bubbles' (it's an error because it may have been mis-scanned
 5526: because too light bubbling), 'double bubble' (each bubble line should
 5527: have no more than one letter picked), invalid or duplicated CODE,
 5528: invalid student/employee ID
 5529: 
 5530: If the CODE option is used that determines the randomization of the
 5531: homework problems, either way the student/employee ID is looked up into a
 5532: username:domain.
 5533: 
 5534: During the validation phase the instructor can choose to skip scanlines. 
 5535: 
 5536: After the validation phase, there are now 3 bubblesheet files
 5537: 
 5538:   scantron_original_filename (unmodified original file)
 5539:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5540:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5541: 
 5542: Also there is a separate hash nohist_scantrondata that contains extra
 5543: correction information that isn't representable in the bubblesheet
 5544: file (see &scantron_getfile() for more information)
 5545: 
 5546: After all scanlines are either valid, marked as valid or skipped, then
 5547: foreach line foreach problem in the picked sequence, an ssi request is
 5548: made that simulates a user submitting their selected letter(s) against
 5549: the homework problem.
 5550: 
 5551: =over 4
 5552: 
 5553: 
 5554: 
 5555: =item defaultFormData
 5556: 
 5557:   Returns html hidden inputs used to hold context/default values.
 5558: 
 5559:  Arguments:
 5560:   $symb - $symb of the current resource 
 5561: 
 5562: =cut
 5563: 
 5564: sub defaultFormData {
 5565:     my ($symb)=@_;
 5566:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5567:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 5568:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 5569: }
 5570: 
 5571: 
 5572: =pod 
 5573: 
 5574: =item getSequenceDropDown
 5575: 
 5576:    Return html dropdown of possible sequences to grade
 5577:  
 5578:  Arguments:
 5579:    $symb - $symb of the current resource
 5580:    $map_error - ref to scalar which will container error if
 5581:                 $navmap object is unavailable in &getSymbMap().
 5582: 
 5583: =cut
 5584: 
 5585: sub getSequenceDropDown {
 5586:     my ($symb,$map_error)=@_;
 5587:     my $result='<select name="selectpage">'."\n";
 5588:     my ($titles,$symbx) = &getSymbMap($map_error);
 5589:     if (ref($map_error)) {
 5590:         return if ($$map_error);
 5591:     }
 5592:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5593:     my $ctr=0;
 5594:     foreach (@$titles) {
 5595: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5596: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5597: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5598: 	    '>'.$showtitle.'</option>'."\n";
 5599: 	$ctr++;
 5600:     }
 5601:     $result.= '</select>';
 5602:     return $result;
 5603: }
 5604: 
 5605: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5606:                                    # key is zero-based index - 0, 1, 2 ...
 5607: 
 5608: my %first_bubble_line;             # First bubble line no. for each bubble.
 5609: 
 5610: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5611:                                    # matchresponse or rankresponse, where 
 5612:                                    # an individual response can have multiple 
 5613:                                    # lines
 5614: 
 5615: my %responsetype_per_response;     # responsetype for each response
 5616: 
 5617: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5618:                                    # numbered response. Needed when randomorder
 5619:                                    # or randompick are in use. Key is ID, value 
 5620:                                    # is response number.
 5621: 
 5622: # Save and restore the bubble lines array to the form env.
 5623: 
 5624: 
 5625: sub save_bubble_lines {
 5626:     foreach my $line (keys(%bubble_lines_per_response)) {
 5627: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5628: 	$env{"form.scantron.first_bubble_line.$line"} =
 5629: 	    $first_bubble_line{$line};
 5630:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5631:             $subdivided_bubble_lines{$line};
 5632:         $env{"form.scantron.responsetype.$line"} =
 5633:             $responsetype_per_response{$line};
 5634:     }
 5635:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5636:         my $line = $masterseq_id_responsenum{$resid};
 5637:         $env{"form.scantron.residpart.$line"} = $resid;
 5638:     }
 5639: }
 5640: 
 5641: 
 5642: sub restore_bubble_lines {
 5643:     my $line = 0;
 5644:     %bubble_lines_per_response = ();
 5645:     %masterseq_id_responsenum = ();
 5646:     while ($env{"form.scantron.bubblelines.$line"}) {
 5647: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5648: 	$bubble_lines_per_response{$line} = $value;
 5649: 	$first_bubble_line{$line}  =
 5650: 	    $env{"form.scantron.first_bubble_line.$line"};
 5651:         $subdivided_bubble_lines{$line} =
 5652:             $env{"form.scantron.sub_bubblelines.$line"};
 5653:         $responsetype_per_response{$line} =
 5654:             $env{"form.scantron.responsetype.$line"};
 5655:         my $id = $env{"form.scantron.residpart.$line"};
 5656:         $masterseq_id_responsenum{$id} = $line;
 5657: 	$line++;
 5658:     }
 5659: }
 5660: 
 5661: =pod 
 5662: 
 5663: =item scantron_filenames
 5664: 
 5665:    Returns a list of the scantron files in the current course 
 5666: 
 5667: =cut
 5668: 
 5669: sub scantron_filenames {
 5670:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5671:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5672:     my $getpropath = 1;
 5673:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5674:                                                         $cname,$getpropath);
 5675:     my @possiblenames;
 5676:     if (ref($dirlist) eq 'ARRAY') {
 5677:         foreach my $filename (sort(@{$dirlist})) {
 5678: 	    ($filename)=split(/&/,$filename);
 5679: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5680: 	    $filename=~s/^scantron_orig_//;
 5681: 	    push(@possiblenames,$filename);
 5682:         }
 5683:     }
 5684:     return @possiblenames;
 5685: }
 5686: 
 5687: =pod 
 5688: 
 5689: =item scantron_uploads
 5690: 
 5691:    Returns  html drop-down list of scantron files in current course.
 5692: 
 5693:  Arguments:
 5694:    $file2grade - filename to set as selected in the dropdown
 5695: 
 5696: =cut
 5697: 
 5698: sub scantron_uploads {
 5699:     my ($file2grade) = @_;
 5700:     my $result=	'<select name="scantron_selectfile">';
 5701:     $result.="<option></option>";
 5702:     foreach my $filename (sort(&scantron_filenames())) {
 5703: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5704:     }
 5705:     $result.="</select>";
 5706:     return $result;
 5707: }
 5708: 
 5709: =pod 
 5710: 
 5711: =item scantron_scantab
 5712: 
 5713:   Returns html drop down of the scantron formats in the scantronformat.tab
 5714:   file.
 5715: 
 5716: =cut
 5717: 
 5718: sub scantron_scantab {
 5719:     my $result='<select name="scantron_format">'."\n";
 5720:     $result.='<option></option>'."\n";
 5721:     my @lines = &get_scantronformat_file();
 5722:     if (@lines > 0) {
 5723:         foreach my $line (@lines) {
 5724:             next if (($line =~ /^\#/) || ($line eq ''));
 5725: 	    my ($name,$descrip)=split(/:/,$line);
 5726: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5727:         }
 5728:     }
 5729:     $result.='</select>'."\n";
 5730:     return $result;
 5731: }
 5732: 
 5733: =pod
 5734: 
 5735: =item get_scantronformat_file
 5736: 
 5737:   Returns an array containing lines from the scantron format file for
 5738:   the domain of the course.
 5739: 
 5740:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5741:   lines are from this file.
 5742: 
 5743:   Otherwise, if a default.tab has been published in RES space by the 
 5744:   domainconfig user, lines are from this file.
 5745: 
 5746:   Otherwise, fall back to getting lines from the legacy file on the
 5747:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5748: 
 5749: =cut
 5750: 
 5751: sub get_scantronformat_file {
 5752:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5753:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5754:     my $gottab = 0;
 5755:     my @lines;
 5756:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5757:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5758:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5759:             if ($formatfile ne '-1') {
 5760:                 @lines = split("\n",$formatfile,-1);
 5761:                 $gottab = 1;
 5762:             }
 5763:         }
 5764:     }
 5765:     if (!$gottab) {
 5766:         my $confname = $cdom.'-domainconfig';
 5767:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5768:         my $formatfile =  &Apache::lonnet::getfile($default);
 5769:         if ($formatfile ne '-1') {
 5770:             @lines = split("\n",$formatfile,-1);
 5771:             $gottab = 1;
 5772:         }
 5773:     }
 5774:     if (!$gottab) {
 5775:         my @domains = &Apache::lonnet::current_machine_domains();
 5776:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5777:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5778:             @lines = <$fh>;
 5779:             close($fh);
 5780:         } else {
 5781:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5782:             @lines = <$fh>;
 5783:             close($fh);
 5784:         }
 5785:     }
 5786:     return @lines;
 5787: }
 5788: 
 5789: =pod 
 5790: 
 5791: =item scantron_CODElist
 5792: 
 5793:   Returns html drop down of the saved CODE lists from current course,
 5794:   generated from earlier printings.
 5795: 
 5796: =cut
 5797: 
 5798: sub scantron_CODElist {
 5799:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5800:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5801:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5802:     my $namechoice='<option></option>';
 5803:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5804: 	if ($name =~ /^error: 2 /) { next; }
 5805: 	if ($name =~ /^type\0/) { next; }
 5806: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5807:     }
 5808:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5809:     return $namechoice;
 5810: }
 5811: 
 5812: =pod 
 5813: 
 5814: =item scantron_CODEunique
 5815: 
 5816:   Returns the html for "Each CODE to be used once" radio.
 5817: 
 5818: =cut
 5819: 
 5820: sub scantron_CODEunique {
 5821:     my $result='<span class="LC_nobreak">
 5822:                  <label><input type="radio" name="scantron_CODEunique"
 5823:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5824:                 </span>
 5825:                 <span class="LC_nobreak">
 5826:                  <label><input type="radio" name="scantron_CODEunique"
 5827:                         value="no" />'.&mt('No').' </label>
 5828:                 </span>';
 5829:     return $result;
 5830: }
 5831: 
 5832: =pod 
 5833: 
 5834: =item scantron_selectphase
 5835: 
 5836:   Generates the initial screen to start the bubblesheet process.
 5837:   Allows for - starting a grading run.
 5838:              - downloading existing scan data (original, corrected
 5839:                                                 or skipped info)
 5840: 
 5841:              - uploading new scan data
 5842: 
 5843:  Arguments:
 5844:   $r          - The Apache request object
 5845:   $file2grade - name of the file that contain the scanned data to score
 5846: 
 5847: =cut
 5848: 
 5849: sub scantron_selectphase {
 5850:     my ($r,$file2grade) = @_;
 5851:     my ($symb)=&get_symb($r);
 5852:     if (!$symb) {return '';}
 5853:     my $map_error;
 5854:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5855:     if ($map_error) {
 5856:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5857:         return;
 5858:     }
 5859:     my $default_form_data=&defaultFormData($symb);
 5860:     my $grading_menu_button=&show_grading_menu_form($symb);
 5861:     my $file_selector=&scantron_uploads($file2grade);
 5862:     my $format_selector=&scantron_scantab();
 5863:     my $CODE_selector=&scantron_CODElist();
 5864:     my $CODE_unique=&scantron_CODEunique();
 5865:     my $result;
 5866: 
 5867:     $ssi_error = 0;
 5868: 
 5869:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5870:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5871: 
 5872:         # Chunk of form to prompt for a scantron file upload.
 5873: 
 5874:         $r->print('
 5875:     <br />
 5876:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5877:        '.&Apache::loncommon::start_data_table_header_row().'
 5878:             <th>
 5879:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5880:             </th>
 5881:        '.&Apache::loncommon::end_data_table_header_row().'
 5882:        '.&Apache::loncommon::start_data_table_row().'
 5883:             <td>
 5884: ');
 5885:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5886:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5887:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5888:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5889:     &js_escape(\$alertmsg);
 5890:     $r->print('
 5891:               <script type="text/javascript" language="javascript">
 5892:     function checkUpload(formname) {
 5893:         if (formname.upfile.value == "") {
 5894:             alert("'.$alertmsg.'");
 5895:             return false;
 5896:         }
 5897:         formname.submit();
 5898:     }
 5899:               </script>
 5900: 
 5901:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5902:                 '.$default_form_data.'
 5903:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5904:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5905:                 <input name="command" value="scantronupload_save" type="hidden" />
 5906:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5907:                 <br />
 5908:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5909:               </form>
 5910: ');
 5911: 
 5912:         $r->print('
 5913:             </td>
 5914:        '.&Apache::loncommon::end_data_table_row().'
 5915:        '.&Apache::loncommon::end_data_table().'
 5916: ');
 5917:     }
 5918: 
 5919:     # Chunk of form to prompt for a file to grade and how:
 5920: 
 5921:     $result.= '
 5922:     <br />
 5923:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5924:     <input type="hidden" name="command" value="scantron_warning" />
 5925:     '.$default_form_data.'
 5926:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5927:        '.&Apache::loncommon::start_data_table_header_row().'
 5928:             <th colspan="2">
 5929:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5930:             </th>
 5931:        '.&Apache::loncommon::end_data_table_header_row().'
 5932:        '.&Apache::loncommon::start_data_table_row().'
 5933:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5934:        '.&Apache::loncommon::end_data_table_row().'
 5935:        '.&Apache::loncommon::start_data_table_row().'
 5936:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5937:        '.&Apache::loncommon::end_data_table_row().'
 5938:        '.&Apache::loncommon::start_data_table_row().'
 5939:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5940:        '.&Apache::loncommon::end_data_table_row().'
 5941:        '.&Apache::loncommon::start_data_table_row().'
 5942:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5943:        '.&Apache::loncommon::end_data_table_row().'
 5944:        '.&Apache::loncommon::start_data_table_row().'
 5945:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5946:        '.&Apache::loncommon::end_data_table_row().'
 5947:        '.&Apache::loncommon::start_data_table_row().'
 5948: 	    <td> '.&mt('Options:').' </td>
 5949:             <td>
 5950: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5951:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5952:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5953: 	    </td>
 5954:        '.&Apache::loncommon::end_data_table_row().'
 5955:        '.&Apache::loncommon::start_data_table_row().'
 5956:             <td colspan="2">
 5957:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5958:             </td>
 5959:        '.&Apache::loncommon::end_data_table_row().'
 5960:     '.&Apache::loncommon::end_data_table().'
 5961:     </form>
 5962: ';
 5963:    
 5964:     $r->print($result);
 5965: 
 5966:     # Chunk of the form that prompts to view a scoring office file,
 5967:     # corrected file, skipped records in a file.
 5968: 
 5969:     $r->print('
 5970:    <br />
 5971:    <form action="/adm/grades" name="scantron_download">
 5972:      '.$default_form_data.'
 5973:      <input type="hidden" name="command" value="scantron_download" />
 5974:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5975:        '.&Apache::loncommon::start_data_table_header_row().'
 5976:               <th>
 5977:                 &nbsp;'.&mt('Download a scoring office file').'
 5978:               </th>
 5979:        '.&Apache::loncommon::end_data_table_header_row().'
 5980:        '.&Apache::loncommon::start_data_table_row().'
 5981:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5982:                 <br />
 5983:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5984:        '.&Apache::loncommon::end_data_table_row().'
 5985:      '.&Apache::loncommon::end_data_table().'
 5986:    </form>
 5987:    <br />
 5988: ');
 5989: 
 5990:     &Apache::lonpickcode::code_list($r,2);
 5991: 
 5992:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 5993:              $default_form_data."\n".
 5994:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5995:              &Apache::loncommon::start_data_table_header_row()."\n".
 5996:              '<th colspan="2">
 5997:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5998:              '</th>'."\n".
 5999:               &Apache::loncommon::end_data_table_header_row()."\n".
 6000:               &Apache::loncommon::start_data_table_row()."\n".
 6001:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6002:               '<td> '.$sequence_selector.' </td>'.
 6003:               &Apache::loncommon::end_data_table_row()."\n".
 6004:               &Apache::loncommon::start_data_table_row()."\n".
 6005:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6006:               '<td> '.$file_selector.' </td>'."\n".
 6007:               &Apache::loncommon::end_data_table_row()."\n".
 6008:               &Apache::loncommon::start_data_table_row()."\n".
 6009:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6010:               '<td> '.$format_selector.' </td>'."\n".
 6011:               &Apache::loncommon::end_data_table_row()."\n".
 6012:               &Apache::loncommon::start_data_table_row()."\n".
 6013:               '<td> '.&mt('Options').' </td>'."\n".
 6014:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6015:               &Apache::loncommon::end_data_table_row()."\n".
 6016:               &Apache::loncommon::start_data_table_row()."\n".
 6017:               '<td colspan="2">'."\n".
 6018:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6019:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6020:               '</td>'."\n".
 6021:               &Apache::loncommon::end_data_table_row()."\n".
 6022:               &Apache::loncommon::end_data_table()."\n".
 6023:               '</form><br />');
 6024:     $r->print($grading_menu_button);
 6025:     return;
 6026: }
 6027: 
 6028: =pod
 6029: 
 6030: =item get_scantron_config
 6031: 
 6032:    Parse and return the scantron configuration line selected as a
 6033:    hash of configuration file fields.
 6034: 
 6035:  Arguments:
 6036:     which - the name of the configuration to parse from the file.
 6037: 
 6038: 
 6039:  Returns:
 6040:             If the named configuration is not in the file, an empty
 6041:             hash is returned.
 6042:     a hash with the fields
 6043:       name         - internal name for the this configuration setup
 6044:       description  - text to display to operator that describes this config
 6045:       CODElocation - if 0 or the string 'none'
 6046:                           - no CODE exists for this config
 6047:                      if -1 || the string 'letter'
 6048:                           - a CODE exists for this config and is
 6049:                             a string of letters
 6050:                      Unsupported value (but planned for future support)
 6051:                           if a positive integer
 6052:                                - The CODE exists as the first n items from
 6053:                                  the question section of the form
 6054:                           if the string 'number'
 6055:                                - The CODE exists for this config and is
 6056:                                  a string of numbers
 6057:       CODEstart   - (only matter if a CODE exists) column in the line where
 6058:                      the CODE starts
 6059:       CODElength  - length of the CODE
 6060:       IDstart     - column where the student/employee ID starts
 6061:       IDlength    - length of the student/employee ID info
 6062:       Qstart      - column where the information from the bubbled
 6063:                     'questions' start
 6064:       Qlength     - number of columns comprising a single bubble line from
 6065:                     the sheet. (usually either 1 or 10)
 6066:       Qon         - either a single character representing the character used
 6067:                     to signal a bubble was chosen in the positional setup, or
 6068:                     the string 'letter' if the letter of the chosen bubble is
 6069:                     in the final, or 'number' if a number representing the
 6070:                     chosen bubble is in the file (1->A 0->J)
 6071:       Qoff        - the character used to represent that a bubble was
 6072:                     left blank
 6073:       PaperID     - if the scanning process generates a unique number for each
 6074:                     sheet scanned the column that this ID number starts in
 6075:       PaperIDlength - number of columns that comprise the unique ID number
 6076:                       for the sheet of paper
 6077:       FirstName   - column that the first name starts in
 6078:       FirstNameLength - number of columns that the first name spans
 6079:  
 6080:       LastName    - column that the last name starts in
 6081:       LastNameLength - number of columns that the last name spans
 6082:       BubblesPerRow - number of bubbles available in each row used to
 6083:                       bubble an answer. (If not specified, 10 assumed).
 6084: 
 6085: =cut
 6086: 
 6087: sub get_scantron_config {
 6088:     my ($which) = @_;
 6089:     my @lines = &get_scantronformat_file();
 6090:     my %config;
 6091:     #FIXME probably should move to XML it has already gotten a bit much now
 6092:     foreach my $line (@lines) {
 6093: 	my ($name,$descrip)=split(/:/,$line);
 6094: 	if ($name ne $which ) { next; }
 6095: 	chomp($line);
 6096: 	my @config=split(/:/,$line);
 6097: 	$config{'name'}=$config[0];
 6098: 	$config{'description'}=$config[1];
 6099: 	$config{'CODElocation'}=$config[2];
 6100: 	$config{'CODEstart'}=$config[3];
 6101: 	$config{'CODElength'}=$config[4];
 6102: 	$config{'IDstart'}=$config[5];
 6103: 	$config{'IDlength'}=$config[6];
 6104: 	$config{'Qstart'}=$config[7];
 6105:  	$config{'Qlength'}=$config[8];
 6106: 	$config{'Qoff'}=$config[9];
 6107: 	$config{'Qon'}=$config[10];
 6108: 	$config{'PaperID'}=$config[11];
 6109: 	$config{'PaperIDlength'}=$config[12];
 6110: 	$config{'FirstName'}=$config[13];
 6111: 	$config{'FirstNamelength'}=$config[14];
 6112: 	$config{'LastName'}=$config[15];
 6113: 	$config{'LastNamelength'}=$config[16];
 6114:         $config{'BubblesPerRow'}=$config[17];
 6115: 	last;
 6116:     }
 6117:     return %config;
 6118: }
 6119: 
 6120: =pod 
 6121: 
 6122: =item username_to_idmap
 6123: 
 6124:     creates a hash keyed by student/employee ID with values of the corresponding
 6125:     student username:domain.
 6126: 
 6127:   Arguments:
 6128: 
 6129:     $classlist - reference to the class list hash. This is a hash
 6130:                  keyed by student name:domain  whose elements are references
 6131:                  to arrays containing various chunks of information
 6132:                  about the student. (See loncoursedata for more info).
 6133: 
 6134:   Returns
 6135:     %idmap - the constructed hash
 6136: 
 6137: =cut
 6138: 
 6139: sub username_to_idmap {
 6140:     my ($classlist)= @_;
 6141:     my %idmap;
 6142:     foreach my $student (keys(%$classlist)) {
 6143:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6144:         unless ($id eq '') {
 6145:             if (!exists($idmap{$id})) {
 6146:                 $idmap{$id} = $student;
 6147:             } else {
 6148:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6149:                 if ($status eq 'Active') {
 6150:                     $idmap{$id} = $student;
 6151:                 }
 6152:             }
 6153:         }
 6154:     }
 6155:     return %idmap;
 6156: }
 6157: 
 6158: =pod
 6159: 
 6160: =item scantron_fixup_scanline
 6161: 
 6162:    Process a requested correction to a scanline.
 6163: 
 6164:   Arguments:
 6165:     $scantron_config   - hash from &get_scantron_config()
 6166:     $scan_data         - hash of correction information 
 6167:                           (see &scantron_getfile())
 6168:     $line              - existing scanline
 6169:     $whichline         - line number of the passed in scanline
 6170:     $field             - type of change to process 
 6171:                          (either 
 6172:                           'ID'     -> correct the student/employee ID
 6173:                           'CODE'   -> correct the CODE
 6174:                           'answer' -> fixup the submitted answers)
 6175:     
 6176:    $args               - hash of additional info,
 6177:                           - 'ID' 
 6178:                                'newid' -> studentID to use in replacement
 6179:                                           of existing one
 6180:                           - 'CODE' 
 6181:                                'CODE_ignore_dup' - set to true if duplicates
 6182:                                                    should be ignored.
 6183: 	                       'CODE' - is new code or 'use_unfound'
 6184:                                         if the existing unfound code should
 6185:                                         be used as is
 6186:                           - 'answer'
 6187:                                'response' - new answer or 'none' if blank
 6188:                                'question' - the bubble line to change
 6189:                                'questionnum' - the question identifier,
 6190:                                                may include subquestion. 
 6191: 
 6192:   Returns:
 6193:     $line - the modified scanline
 6194: 
 6195:   Side effects: 
 6196:     $scan_data - may be updated
 6197: 
 6198: =cut
 6199: 
 6200: 
 6201: sub scantron_fixup_scanline {
 6202:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6203:     if ($field eq 'ID') {
 6204: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6205: 	    return ($line,1,'New value too large');
 6206: 	}
 6207: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6208: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6209: 				     $args->{'newid'});
 6210: 	}
 6211: 	substr($line,$$scantron_config{'IDstart'}-1,
 6212: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6213: 	if ($args->{'newid'}=~/^\s*$/) {
 6214: 	    &scan_data($scan_data,"$whichline.user",
 6215: 		       $args->{'username'}.':'.$args->{'domain'});
 6216: 	}
 6217:     } elsif ($field eq 'CODE') {
 6218: 	if ($args->{'CODE_ignore_dup'}) {
 6219: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6220: 	}
 6221: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6222: 	if ($args->{'CODE'} ne 'use_unfound') {
 6223: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6224: 		return ($line,1,'New CODE value too large');
 6225: 	    }
 6226: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6227: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6228: 	    }
 6229: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6230: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6231: 	}
 6232:     } elsif ($field eq 'answer') {
 6233: 	my $length=$scantron_config->{'Qlength'};
 6234: 	my $off=$scantron_config->{'Qoff'};
 6235: 	my $on=$scantron_config->{'Qon'};
 6236: 	my $answer=${off}x$length;
 6237: 	if ($args->{'response'} eq 'none') {
 6238: 	    &scan_data($scan_data,
 6239: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6240: 	} else {
 6241: 	    if ($on eq 'letter') {
 6242: 		my @alphabet=('A'..'Z');
 6243: 		$answer=$alphabet[$args->{'response'}];
 6244: 	    } elsif ($on eq 'number') {
 6245: 		$answer=$args->{'response'}+1;
 6246: 		if ($answer == 10) { $answer = '0'; }
 6247: 	    } else {
 6248: 		substr($answer,$args->{'response'},1)=$on;
 6249: 	    }
 6250: 	    &scan_data($scan_data,
 6251: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6252: 	}
 6253: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6254: 	substr($line,$where-1,$length)=$answer;
 6255:     }
 6256:     return $line;
 6257: }
 6258: 
 6259: =pod
 6260: 
 6261: =item scan_data
 6262: 
 6263:     Edit or look up  an item in the scan_data hash.
 6264: 
 6265:   Arguments:
 6266:     $scan_data  - The hash (see scantron_getfile)
 6267:     $key        - shorthand of the key to edit (actual key is
 6268:                   scantronfilename_key).
 6269:     $data        - New value of the hash entry.
 6270:     $delete      - If true, the entry is removed from the hash.
 6271: 
 6272:   Returns:
 6273:     The new value of the hash table field (undefined if deleted).
 6274: 
 6275: =cut
 6276: 
 6277: 
 6278: sub scan_data {
 6279:     my ($scan_data,$key,$value,$delete)=@_;
 6280:     my $filename=$env{'form.scantron_selectfile'};
 6281:     if (defined($value)) {
 6282: 	$scan_data->{$filename.'_'.$key} = $value;
 6283:     }
 6284:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6285:     return $scan_data->{$filename.'_'.$key};
 6286: }
 6287: 
 6288: # ----- These first few routines are general use routines.----
 6289: 
 6290: # Return the number of occurences of a pattern in a string.
 6291: 
 6292: sub occurence_count {
 6293:     my ($string, $pattern) = @_;
 6294: 
 6295:     my @matches = ($string =~ /$pattern/g);
 6296: 
 6297:     return scalar(@matches);
 6298: }
 6299: 
 6300: 
 6301: # Take a string known to have digits and convert all the
 6302: # digits into letters in the range J,A..I.
 6303: 
 6304: sub digits_to_letters {
 6305:     my ($input) = @_;
 6306: 
 6307:     my @alphabet = ('J', 'A'..'I');
 6308: 
 6309:     my @input    = split(//, $input);
 6310:     my $output ='';
 6311:     for (my $i = 0; $i < scalar(@input); $i++) {
 6312: 	if ($input[$i] =~ /\d/) {
 6313: 	    $output .= $alphabet[$input[$i]];
 6314: 	} else {
 6315: 	    $output .= $input[$i];
 6316: 	}
 6317:     }
 6318:     return $output;
 6319: }
 6320: 
 6321: =pod 
 6322: 
 6323: =item scantron_parse_scanline
 6324: 
 6325:   Decodes a scanline from the selected scantron file
 6326: 
 6327:  Arguments:
 6328:     line             - The text of the scantron file line to process
 6329:     whichline        - Line number
 6330:     scantron_config  - Hash describing the format of the scantron lines.
 6331:     scan_data        - Hash of extra information about the scanline
 6332:                        (see scantron_getfile for more information)
 6333:     just_header      - True if should not process question answers but only
 6334:                        the stuff to the left of the answers.
 6335:     randomorder      - True if randomorder in use
 6336:     randompick       - True if randompick in use
 6337:     sequence         - Exam folder URL
 6338:     master_seq       - Ref to array containing symbs in exam folder
 6339:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6340:                        (corresponding values are resource objects)
 6341:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6342:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6343:                        are refs to an array of resource objects, ordered
 6344:                        according to order used for CODE, when randomorder
 6345:                        and or randompick are in use.
 6346:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6347:                        for current line to question number used for same question
 6348:                         in "Master Sequence" (as seen by Course Coordinator).
 6349:     startline        - Ref to hash where key is question number (0 is first)
 6350:                        and value is number of first bubble line for current 
 6351:                        student or code-based randompick and/or randomorder.
 6352:     totalref         - Ref of scalar used to score total number of bubble
 6353:                        lines needed for responses in a scan line (used when
 6354:                        randompick in use. 
 6355: 
 6356:  Returns:
 6357:    Hash containing the result of parsing the scanline
 6358: 
 6359:    Keys are all proceeded by the string 'scantron.'
 6360: 
 6361:        CODE    - the CODE in use for this scanline
 6362:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6363:                  by the operator
 6364:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6365:                             CODEs were selected, but the usage has been
 6366:                             forced by the operator
 6367:        ID  - student/employee ID
 6368:        PaperID - if used, the ID number printed on the sheet when the 
 6369:                  paper was scanned
 6370:        FirstName - first name from the sheet
 6371:        LastName  - last name from the sheet
 6372: 
 6373:      if just_header was not true these key may also exist
 6374: 
 6375:        missingerror - a list of bubble ranges that are considered to be answers
 6376:                       to a single question that don't have any bubbles filled in.
 6377:                       Of the form questionnumber:firstbubblenumber:count.
 6378:        doubleerror  - a list of bubble ranges that are considered to be answers
 6379:                       to a single question that have more than one bubble filled in.
 6380:                       Of the form questionnumber::firstbubblenumber:count
 6381:    
 6382:                 In the above, count is the number of bubble responses in the
 6383:                 input line needed to represent the possible answers to the question.
 6384:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6385:                 per line would have count = 2.
 6386: 
 6387:        maxquest     - the number of the last bubble line that was parsed
 6388: 
 6389:        (<number> starts at 1)
 6390:        <number>.answer - zero or more letters representing the selected
 6391:                          letters from the scanline for the bubble line 
 6392:                          <number>.
 6393:                          if blank there was either no bubble or there where
 6394:                          multiple bubbles, (consult the keys missingerror and
 6395:                          doubleerror if this is an error condition)
 6396: 
 6397: =cut
 6398: 
 6399: sub scantron_parse_scanline {
 6400:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6401:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6402:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6403: 
 6404:     my %record;
 6405:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6406:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6407: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6408: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6409: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6410: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6411: 	    $record{'scantron.CODE'}=substr($data,
 6412: 					    $$scantron_config{'CODEstart'}-1,
 6413: 					    $$scantron_config{'CODElength'});
 6414: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6415: 		$record{'scantron.useCODE'}=1;
 6416: 	    }
 6417: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6418: 		$record{'scantron.CODE_ignore_dup'}=1;
 6419: 	    }
 6420: 	} else {
 6421: 	    #FIXME interpret first N questions
 6422: 	}
 6423:     }
 6424:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6425: 				  $$scantron_config{'IDlength'});
 6426:     $record{'scantron.PaperID'}=
 6427: 	substr($data,$$scantron_config{'PaperID'}-1,
 6428: 	       $$scantron_config{'PaperIDlength'});
 6429:     $record{'scantron.FirstName'}=
 6430: 	substr($data,$$scantron_config{'FirstName'}-1,
 6431: 	       $$scantron_config{'FirstNamelength'});
 6432:     $record{'scantron.LastName'}=
 6433: 	substr($data,$$scantron_config{'LastName'}-1,
 6434: 	       $$scantron_config{'LastNamelength'});
 6435:     if ($just_header) { return \%record; }
 6436: 
 6437:     my @alphabet=('A'..'Z');
 6438:     my $questnum=0;
 6439:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6440: 
 6441:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6442:     if ($randompick || $randomorder) {
 6443:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6444:                                          $master_seq,$symb_to_resource,
 6445:                                          $partids_by_symb,$orderedforcode,
 6446:                                          $respnumlookup,$startline);
 6447:         if ($total) {
 6448:             $lastpos = $total*$$scantron_config{'Qlength'};
 6449:         }
 6450:         if (ref($totalref)) {
 6451:             $$totalref = $total;
 6452:         }
 6453:     }
 6454:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6455:     chomp($questions);		# Get rid of any trailing \n.
 6456:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6457:     while (length($questions)) {
 6458:         my $answers_needed;
 6459:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6460:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6461:         } else {
 6462:             $answers_needed = $bubble_lines_per_response{$questnum};
 6463:         }
 6464:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6465:                              || 1;
 6466:         $questnum++;
 6467:         my $quest_id = $questnum;
 6468:         my $currentquest = substr($questions,0,$answer_length);
 6469:         $questions       = substr($questions,$answer_length);
 6470:         if (length($currentquest) < $answer_length) { next; }
 6471: 
 6472:         my $subdivided;
 6473:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6474:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6475:         } else {
 6476:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6477:         }
 6478:         if ($subdivided =~ /,/) {
 6479:             my $subquestnum = 1;
 6480:             my $subquestions = $currentquest;
 6481:             my @subanswers_needed = split(/,/,$subdivided);
 6482:             foreach my $subans (@subanswers_needed) {
 6483:                 my $subans_length =
 6484:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6485:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6486:                 $subquestions   = substr($subquestions,$subans_length);
 6487:                 $quest_id = "$questnum.$subquestnum";
 6488:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6489:                     ($$scantron_config{'Qon'} eq 'number')) {
 6490:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6491:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6492:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6493:                         $randomorder,$randompick,$respnumlookup);
 6494:                 } else {
 6495:                     $ansnum = &scantron_validator_positional($ansnum,
 6496:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6497:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6498:                         $randomorder,$randompick,$respnumlookup);
 6499:                 }
 6500:                 $subquestnum ++;
 6501:             }
 6502:         } else {
 6503:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6504:                 ($$scantron_config{'Qon'} eq 'number')) {
 6505:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6506:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6507:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6508:                     $randomorder,$randompick,$respnumlookup);
 6509:             } else {
 6510:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6511:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6512:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6513:                     $randomorder,$randompick,$respnumlookup);
 6514:             }
 6515:         }
 6516:     }
 6517:     $record{'scantron.maxquest'}=$questnum;
 6518:     return \%record;
 6519: }
 6520: 
 6521: sub get_master_seq {
 6522:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6523:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
 6524:                    (ref($symb_to_resource) eq 'HASH'));
 6525:     my $resource_error;
 6526:     foreach my $resource (@{$resources}) {
 6527:         my $ressymb;
 6528:         if (ref($resource)) {
 6529:             $ressymb = $resource->symb();
 6530:             push(@{$master_seq},$ressymb);
 6531:             $symb_to_resource->{$ressymb} = $resource;
 6532:         } else {
 6533:             $resource_error = 1;
 6534:             last;
 6535:         }
 6536:     }
 6537:     return $resource_error;
 6538: }
 6539: 
 6540: sub get_respnum_lookups {
 6541:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6542:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6543:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6544:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6545:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6546:                    (ref($startline) eq 'HASH'));
 6547:     my ($user,$scancode);
 6548:     if ((exists($record->{'scantron.CODE'})) &&
 6549:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6550:         $scancode = $record->{'scantron.CODE'};
 6551:     } else {
 6552:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6553:     }
 6554:     my @mapresources =
 6555:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6556:                      $orderedforcode);
 6557:     my $total = 0;
 6558:     my $count = 0;
 6559:     foreach my $resource (@mapresources) {
 6560:         my $id = $resource->id();
 6561:         my $symb = $resource->symb();
 6562:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6563:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6564:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6565:                 if ($respnum ne '') {
 6566:                     $respnumlookup->{$count} = $respnum;
 6567:                     $startline->{$count} = $total;
 6568:                     $total += $bubble_lines_per_response{$respnum};
 6569:                     $count ++;
 6570:                 }
 6571:             }
 6572:         }
 6573:     }
 6574:     return $total;
 6575: }
 6576: 
 6577: sub scantron_validator_lettnum {
 6578:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6579:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6580:         $randompick,$respnumlookup) = @_;
 6581: 
 6582:     # Qon 'letter' implies for each slot in currquest we have:
 6583:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6584:     #    about anything else (esp. a value of Qoff) for missing
 6585:     #    bubbles.
 6586:     #
 6587:     # Qon 'number' implies each slot gives a digit that indexes the
 6588:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6589:     #    and * or ? for double bubbles on a single line.
 6590:     #
 6591: 
 6592:     my $matchon;
 6593:     if ($$scantron_config{'Qon'} eq 'letter') {
 6594:         $matchon = '[A-Z]';
 6595:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6596:         $matchon = '\d';
 6597:     }
 6598:     my $occurrences = 0;
 6599:     my $responsenum = $questnum-1;
 6600:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6601:        $responsenum = $respnumlookup->{$questnum-1}
 6602:     }
 6603:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6604:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6605:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6606:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6607:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6608:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6609:         my @singlelines = split('',$currquest);
 6610:         foreach my $entry (@singlelines) {
 6611:             $occurrences = &occurence_count($entry,$matchon);
 6612:             if ($occurrences > 1) {
 6613:                 last;
 6614:             }
 6615:         }
 6616:     } else {
 6617:         $occurrences = &occurence_count($currquest,$matchon); 
 6618:     }
 6619:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6620:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6621:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6622:             my $bubble = substr($currquest,$ans,1);
 6623:             if ($bubble =~ /$matchon/ ) {
 6624:                 if ($$scantron_config{'Qon'} eq 'number') {
 6625:                     if ($bubble == 0) {
 6626:                         $bubble = 10; 
 6627:                     }
 6628:                     $record->{"scantron.$ansnum.answer"} = 
 6629:                         $alphabet->[$bubble-1];
 6630:                 } else {
 6631:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6632:                 }
 6633:             } else {
 6634:                 $record->{"scantron.$ansnum.answer"}='';
 6635:             }
 6636:             $ansnum++;
 6637:         }
 6638:     } elsif (!defined($currquest)
 6639:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6640:             || (&occurence_count($currquest,$matchon) == 0)) {
 6641:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6642:             $record->{"scantron.$ansnum.answer"}='';
 6643:             $ansnum++;
 6644:         }
 6645:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6646:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6647:         }
 6648:     } else {
 6649:         if ($$scantron_config{'Qon'} eq 'number') {
 6650:             $currquest = &digits_to_letters($currquest);            
 6651:         }
 6652:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6653:             my $bubble = substr($currquest,$ans,1);
 6654:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6655:             $ansnum++;
 6656:         }
 6657:     }
 6658:     return $ansnum;
 6659: }
 6660: 
 6661: sub scantron_validator_positional {
 6662:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6663:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6664:         $randomorder,$randompick,$respnumlookup) = @_;
 6665: 
 6666:     # Otherwise there's a positional notation;
 6667:     # each bubble line requires Qlength items, and there are filled in
 6668:     # bubbles for each case where there 'Qon' characters.
 6669:     #
 6670: 
 6671:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6672: 
 6673:     # If the split only gives us one element.. the full length of the
 6674:     # answer string, no bubbles are filled in:
 6675: 
 6676:     if ($answers_needed eq '') {
 6677:         return;
 6678:     }
 6679: 
 6680:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6681:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6682:             $record->{"scantron.$ansnum.answer"}='';
 6683:             $ansnum++;
 6684:         }
 6685:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6686:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6687:         }
 6688:     } elsif (scalar(@array) == 2) {
 6689:         my $location = length($array[0]);
 6690:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6691:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6692:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6693:             if ($ans eq $line_num) {
 6694:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6695:             } else {
 6696:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6697:             }
 6698:             $ansnum++;
 6699:          }
 6700:     } else {
 6701:         #  If there's more than one instance of a bubble character
 6702:         #  That's a double bubble; with positional notation we can
 6703:         #  record all the bubbles filled in as well as the
 6704:         #  fact this response consists of multiple bubbles.
 6705:         #
 6706:         my $responsenum = $questnum-1;
 6707:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6708:             $responsenum = $respnumlookup->{$questnum-1}
 6709:         }
 6710:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6711:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6712:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6713:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6714:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6715:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6716:             my $doubleerror = 0;
 6717:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6718:                    (!$doubleerror)) {
 6719:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6720:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6721:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6722:                if (length(@currarray) > 2) {
 6723:                    $doubleerror = 1;
 6724:                } 
 6725:             }
 6726:             if ($doubleerror) {
 6727:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6728:             }
 6729:         } else {
 6730:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6731:         }
 6732:         my $item = $ansnum;
 6733:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6734:             $record->{"scantron.$item.answer"} = '';
 6735:             $item ++;
 6736:         }
 6737: 
 6738:         my @ans=@array;
 6739:         my $i=0;
 6740:         my $increment = 0;
 6741:         while ($#ans) {
 6742:             $i+=length($ans[0]) + $increment;
 6743:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6744:             my $bubble = $i%$$scantron_config{'Qlength'};
 6745:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6746:             shift(@ans);
 6747:             $increment = 1;
 6748:         }
 6749:         $ansnum += $answers_needed;
 6750:     }
 6751:     return $ansnum;
 6752: }
 6753: 
 6754: =pod
 6755: 
 6756: =item scantron_add_delay
 6757: 
 6758:    Adds an error message that occurred during the grading phase to a
 6759:    queue of messages to be shown after grading pass is complete
 6760: 
 6761:  Arguments:
 6762:    $delayqueue  - arrary ref of hash ref of error messages
 6763:    $scanline    - the scanline that caused the error
 6764:    $errormesage - the error message
 6765:    $errorcode   - a numeric code for the error
 6766: 
 6767:  Side Effects:
 6768:    updates the $delayqueue to have a new hash ref of the error
 6769: 
 6770: =cut
 6771: 
 6772: sub scantron_add_delay {
 6773:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6774:     push(@$delayqueue,
 6775: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6776: 	  'ecode' => $errorcode }
 6777: 	 );
 6778: }
 6779: 
 6780: =pod
 6781: 
 6782: =item scantron_find_student
 6783: 
 6784:    Finds the username for the current scanline
 6785: 
 6786:   Arguments:
 6787:    $scantron_record - hash result from scantron_parse_scanline
 6788:    $scan_data       - hash of correction information 
 6789:                       (see &scantron_getfile() form more information)
 6790:    $idmap           - hash from &username_to_idmap()
 6791:    $line            - number of current scanline
 6792:  
 6793:   Returns:
 6794:    Either 'username:domain' or undef if unknown
 6795: 
 6796: =cut
 6797: 
 6798: sub scantron_find_student {
 6799:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6800:     my $scanID=$$scantron_record{'scantron.ID'};
 6801:     if ($scanID =~ /^\s*$/) {
 6802:  	return &scan_data($scan_data,"$line.user");
 6803:     }
 6804:     foreach my $id (keys(%$idmap)) {
 6805:  	if (lc($id) eq lc($scanID)) {
 6806:  	    return $$idmap{$id};
 6807:  	}
 6808:     }
 6809:     return undef;
 6810: }
 6811: 
 6812: =pod
 6813: 
 6814: =item scantron_filter
 6815: 
 6816:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6817:    hidden resources was selected
 6818: 
 6819: =cut
 6820: 
 6821: sub scantron_filter {
 6822:     my ($curres)=@_;
 6823: 
 6824:     if (ref($curres) && $curres->is_problem()) {
 6825: 	# if the user has asked to not have either hidden
 6826: 	# or 'randomout' controlled resources to be graded
 6827: 	# don't include them
 6828: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6829: 	    && $curres->randomout) {
 6830: 	    return 0;
 6831: 	}
 6832: 	return 1;
 6833:     }
 6834:     return 0;
 6835: }
 6836: 
 6837: =pod
 6838: 
 6839: =item scantron_process_corrections
 6840: 
 6841:    Gets correction information out of submitted form data and corrects
 6842:    the scanline
 6843: 
 6844: =cut
 6845: 
 6846: sub scantron_process_corrections {
 6847:     my ($r) = @_;
 6848:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6849:     my ($scanlines,$scan_data)=&scantron_getfile();
 6850:     my $classlist=&Apache::loncoursedata::get_classlist();
 6851:     my $which=$env{'form.scantron_line'};
 6852:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6853:     my ($skip,$err,$errmsg);
 6854:     if ($env{'form.scantron_skip_record'}) {
 6855: 	$skip=1;
 6856:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6857: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6858: 	    $env{'form.scantron_domain'};
 6859: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6860: 	($line,$err,$errmsg)=
 6861: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6862: 				     'ID',{'newid'=>$newid,
 6863: 				    'username'=>$env{'form.scantron_username'},
 6864: 				    'domain'=>$env{'form.scantron_domain'}});
 6865:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6866: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6867: 	my $newCODE;
 6868: 	my %args;
 6869: 	if      ($resolution eq 'use_unfound') {
 6870: 	    $newCODE='use_unfound';
 6871: 	} elsif ($resolution eq 'use_found') {
 6872: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6873: 	} elsif ($resolution eq 'use_typed') {
 6874: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6875: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6876: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6877: 	}
 6878: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6879: 	    $args{'CODE_ignore_dup'}=1;
 6880: 	}
 6881: 	$args{'CODE'}=$newCODE;
 6882: 	($line,$err,$errmsg)=
 6883: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6884: 				     'CODE',\%args);
 6885:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6886: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6887: 	    ($line,$err,$errmsg)=
 6888: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6889: 					 $which,'answer',
 6890: 					 { 'question'=>$question,
 6891: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6892:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6893: 	    if ($err) { last; }
 6894: 	}
 6895:     }
 6896:     if ($err) {
 6897: 	$r->print(
 6898:             '<p class="LC_error">'
 6899:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6900:                 $errmsg)
 6901:            .'</p>');
 6902:     } else {
 6903: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6904: 	&scantron_putfile($scanlines,$scan_data);
 6905:     }
 6906: }
 6907: 
 6908: =pod
 6909: 
 6910: =item reset_skipping_status
 6911: 
 6912:    Forgets the current set of remember skipped scanlines (and thus
 6913:    reverts back to considering all lines in the
 6914:    scantron_skipped_<filename> file)
 6915: 
 6916: =cut
 6917: 
 6918: sub reset_skipping_status {
 6919:     my ($scanlines,$scan_data)=&scantron_getfile();
 6920:     &scan_data($scan_data,'remember_skipping',undef,1);
 6921:     &scantron_putfile(undef,$scan_data);
 6922: }
 6923: 
 6924: =pod
 6925: 
 6926: =item start_skipping
 6927: 
 6928:    Marks a scanline to be skipped. 
 6929: 
 6930: =cut
 6931: 
 6932: sub start_skipping {
 6933:     my ($scan_data,$i)=@_;
 6934:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6935:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6936: 	$remembered{$i}=2;
 6937:     } else {
 6938: 	$remembered{$i}=1;
 6939:     }
 6940:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6941: }
 6942: 
 6943: =pod
 6944: 
 6945: =item should_be_skipped
 6946: 
 6947:    Checks whether a scanline should be skipped.
 6948: 
 6949: =cut
 6950: 
 6951: sub should_be_skipped {
 6952:     my ($scanlines,$scan_data,$i)=@_;
 6953:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6954: 	# not redoing old skips
 6955: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6956: 	return 0;
 6957:     }
 6958:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6959: 
 6960:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6961: 	return 0;
 6962:     }
 6963:     return 1;
 6964: }
 6965: 
 6966: =pod
 6967: 
 6968: =item remember_current_skipped
 6969: 
 6970:    Discovers what scanlines are in the scantron_skipped_<filename>
 6971:    file and remembers them into scan_data for later use.
 6972: 
 6973: =cut
 6974: 
 6975: sub remember_current_skipped {
 6976:     my ($scanlines,$scan_data)=&scantron_getfile();
 6977:     my %to_remember;
 6978:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6979: 	if ($scanlines->{'skipped'}[$i]) {
 6980: 	    $to_remember{$i}=1;
 6981: 	}
 6982:     }
 6983: 
 6984:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6985:     &scantron_putfile(undef,$scan_data);
 6986: }
 6987: 
 6988: =pod
 6989: 
 6990: =item check_for_error
 6991: 
 6992:     Checks if there was an error when attempting to remove a specific
 6993:     scantron_.. bubblesheet data file. Prints out an error if
 6994:     something went wrong.
 6995: 
 6996: =cut
 6997: 
 6998: sub check_for_error {
 6999:     my ($r,$result)=@_;
 7000:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7001: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7002:     }
 7003: }
 7004: 
 7005: =pod
 7006: 
 7007: =item scantron_warning_screen
 7008: 
 7009:    Interstitial screen to make sure the operator has selected the
 7010:    correct options before we start the validation phase.
 7011: 
 7012: =cut
 7013: 
 7014: sub scantron_warning_screen {
 7015:     my ($button_text)=@_;
 7016:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7017:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7018:     my $CODElist;
 7019:     if ($scantron_config{'CODElocation'} &&
 7020: 	$scantron_config{'CODEstart'} &&
 7021: 	$scantron_config{'CODElength'}) {
 7022: 	$CODElist=$env{'form.scantron_CODElist'};
 7023: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7024: 	$CODElist=
 7025: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7026: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7027:     }
 7028:     my $lastbubblepoints;
 7029:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7030:         $lastbubblepoints =
 7031:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7032:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7033:     }
 7034:     return ('
 7035: <p>
 7036: <span class="LC_warning">
 7037: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7038: </p>
 7039: <table>
 7040: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7041: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7042: '.$CODElist.$lastbubblepoints.'
 7043: </table>
 7044: <br />
 7045: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
 7046: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
 7047: 
 7048: <br />
 7049: ');
 7050: }
 7051: 
 7052: =pod
 7053: 
 7054: =item scantron_do_warning
 7055: 
 7056:    Check if the operator has picked something for all required
 7057:    fields. Error out if something is missing.
 7058: 
 7059: =cut
 7060: 
 7061: sub scantron_do_warning {
 7062:     my ($r)=@_;
 7063:     my ($symb)=&get_symb($r);
 7064:     if (!$symb) {return '';}
 7065:     my $default_form_data=&defaultFormData($symb);
 7066:     $r->print(&scantron_form_start().$default_form_data);
 7067:     if ( $env{'form.selectpage'} eq '' ||
 7068: 	 $env{'form.scantron_selectfile'} eq '' ||
 7069: 	 $env{'form.scantron_format'} eq '' ) {
 7070: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7071: 	if ( $env{'form.selectpage'} eq '') {
 7072: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7073: 	} 
 7074: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7075: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7076: 	} 
 7077: 	if ( $env{'form.scantron_format'} eq '') {
 7078: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7079: 	} 
 7080:     } else {
 7081: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 7082:         my $bubbledbyhand=&hand_bubble_option();
 7083: 	$r->print('
 7084: '.$warning.$bubbledbyhand.'
 7085: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7086: <input type="hidden" name="command" value="scantron_validate" />
 7087: ');
 7088:     }
 7089:     $r->print("</form><br />".&show_grading_menu_form($symb));
 7090:     return '';
 7091: }
 7092: 
 7093: =pod
 7094: 
 7095: =item scantron_form_start
 7096: 
 7097:     html hidden input for remembering all selected grading options
 7098: 
 7099: =cut
 7100: 
 7101: sub scantron_form_start {
 7102:     my ($max_bubble)=@_;
 7103:     my $result= <<SCANTRONFORM;
 7104: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7105:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7106:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7107:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7108:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7109:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7110:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7111:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7112:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7113:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7114: SCANTRONFORM
 7115: 
 7116:   my $line = 0;
 7117:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7118:        my $chunk =
 7119: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7120:        $chunk .=
 7121: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7122:        $chunk .= 
 7123:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7124:        $chunk .=
 7125:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7126:        $chunk .=
 7127:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7128:        $result .= $chunk;
 7129:        $line++;
 7130:     }
 7131:     return $result;
 7132: }
 7133: 
 7134: =pod
 7135: 
 7136: =item scantron_validate_file
 7137: 
 7138:     Dispatch routine for doing validation of a bubblesheet data file.
 7139: 
 7140:     Also processes any necessary information resets that need to
 7141:     occur before validation begins (ignore previous corrections,
 7142:     restarting the skipped records processing)
 7143: 
 7144: =cut
 7145: 
 7146: sub scantron_validate_file {
 7147:     my ($r) = @_;
 7148:     my ($symb)=&get_symb($r);
 7149:     if (!$symb) {return '';}
 7150:     my $default_form_data=&defaultFormData($symb);
 7151:     
 7152:     # do the detection of only doing skipped records first before we delete
 7153:     # them when doing the corrections reset
 7154:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7155: 	&reset_skipping_status();
 7156:     }
 7157:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7158: 	&remember_current_skipped();
 7159: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7160:     }
 7161: 
 7162:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7163: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7164: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7165: 	&check_for_error($r,&scantron_remove_scan_data());
 7166: 	$env{'form.scantron_options_ignore'}='done';
 7167:     }
 7168: 
 7169:     if ($env{'form.scantron_corrections'}) {
 7170: 	&scantron_process_corrections($r);
 7171:     }
 7172:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7173:     #get the student pick code ready
 7174:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7175:     my $nav_error;
 7176:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7177:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7178:     if ($nav_error) {
 7179:         $r->print(&navmap_errormsg());
 7180:         return '';
 7181:     }
 7182:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7183:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7184:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7185:     }
 7186:     $r->print($result);
 7187:     
 7188:     my @validate_phases=( 'sequence',
 7189: 			  'ID',
 7190: 			  'CODE',
 7191: 			  'doublebubble',
 7192: 			  'missingbubbles');
 7193:     if (!$env{'form.validatepass'}) {
 7194: 	$env{'form.validatepass'} = 0;
 7195:     }
 7196:     my $currentphase=$env{'form.validatepass'};
 7197: 
 7198: 
 7199:     my $stop=0;
 7200:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7201: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7202: 	$r->rflush();
 7203: 
 7204: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7205: 	{
 7206: 	    no strict 'refs';
 7207: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7208: 	}
 7209:     }
 7210:     if (!$stop) {
 7211: 	my $warning=&scantron_warning_screen('Start Grading');
 7212: 	$r->print(&mt('Validation process complete.').'<br />'.
 7213:                   $warning.
 7214:                   &mt('Perform verification for each student after storage of submissions?').
 7215:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7216:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7217:                   ('&nbsp;'x3).'<label>'.
 7218:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7219:                   '</label></span><br />'.
 7220:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7221:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 7222:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7223:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7224:     } else {
 7225: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7226: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7227:     }
 7228:     if ($stop) {
 7229: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7230: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7231: 	    $r->print(' '.&mt('this error').' <br />');
 7232: 
 7233: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 7234: 	} else {
 7235:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7236: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7237:             } else {
 7238:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7239:             }
 7240: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7241: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7242: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7243: 	}
 7244:     }
 7245:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 7246:     return '';
 7247: }
 7248: 
 7249: 
 7250: =pod
 7251: 
 7252: =item scantron_remove_file
 7253: 
 7254:    Removes the requested bubblesheet data file, makes sure that
 7255:    scantron_original_<filename> is never removed
 7256: 
 7257: 
 7258: =cut
 7259: 
 7260: sub scantron_remove_file {
 7261:     my ($which)=@_;
 7262:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7263:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7264:     my $file='scantron_';
 7265:     if ($which eq 'corrected' || $which eq 'skipped') {
 7266: 	$file.=$which.'_';
 7267:     } else {
 7268: 	return 'refused';
 7269:     }
 7270:     $file.=$env{'form.scantron_selectfile'};
 7271:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7272: }
 7273: 
 7274: 
 7275: =pod
 7276: 
 7277: =item scantron_remove_scan_data
 7278: 
 7279:    Removes all scan_data correction for the requested bubblesheet
 7280:    data file.  (In the case that both the are doing skipped records we need
 7281:    to remember the old skipped lines for the time being so that element
 7282:    persists for a while.)
 7283: 
 7284: =cut
 7285: 
 7286: sub scantron_remove_scan_data {
 7287:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7288:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7289:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7290:     my @todelete;
 7291:     my $filename=$env{'form.scantron_selectfile'};
 7292:     foreach my $key (@keys) {
 7293: 	if ($key=~/^\Q$filename\E_/) {
 7294: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7295: 		$key=~/remember_skipping/) {
 7296: 		next;
 7297: 	    }
 7298: 	    push(@todelete,$key);
 7299: 	}
 7300:     }
 7301:     my $result;
 7302:     if (@todelete) {
 7303: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7304: 				       \@todelete,$cdom,$cname);
 7305:     } else {
 7306: 	$result = 'ok';
 7307:     }
 7308:     return $result;
 7309: }
 7310: 
 7311: 
 7312: =pod
 7313: 
 7314: =item scantron_getfile
 7315: 
 7316:     Fetches the requested bubblesheet data file (all 3 versions), and
 7317:     the scan_data hash
 7318:   
 7319:   Arguments:
 7320:     None
 7321: 
 7322:   Returns:
 7323:     2 hash references
 7324: 
 7325:      - first one has 
 7326:          orig      -
 7327:          corrected -
 7328:          skipped   -  each of which points to an array ref of the specified
 7329:                       file broken up into individual lines
 7330:          count     - number of scanlines
 7331:  
 7332:      - second is the scan_data hash possible keys are
 7333:        ($number refers to scanline numbered $number and thus the key affects
 7334:         only that scanline
 7335:         $bubline refers to the specific bubble line element and the aspects
 7336:         refers to that specific bubble line element)
 7337: 
 7338:        $number.user - username:domain to use
 7339:        $number.CODE_ignore_dup 
 7340:                     - ignore the duplicate CODE error 
 7341:        $number.useCODE
 7342:                     - use the CODE in the scanline as is
 7343:        $number.no_bubble.$bubline
 7344:                     - it is valid that there is no bubbled in bubble
 7345:                       at $number $bubline
 7346:        remember_skipping
 7347:                     - a frozen hash containing keys of $number and values
 7348:                       of either 
 7349:                         1 - we are on a 'do skipped records pass' and plan
 7350:                             on processing this line
 7351:                         2 - we are on a 'do skipped records pass' and this
 7352:                             scanline has been marked to skip yet again
 7353: 
 7354: =cut
 7355: 
 7356: sub scantron_getfile {
 7357:     #FIXME really would prefer a scantron directory
 7358:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7359:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7360:     my $lines;
 7361:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7362: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7363:     my %scanlines;
 7364:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7365:     my $temp=$scanlines{'orig'};
 7366:     $scanlines{'count'}=$#$temp;
 7367: 
 7368:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7369: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7370:     if ($lines eq '-1') {
 7371: 	$scanlines{'corrected'}=[];
 7372:     } else {
 7373: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7374:     }
 7375:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7376: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7377:     if ($lines eq '-1') {
 7378: 	$scanlines{'skipped'}=[];
 7379:     } else {
 7380: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7381:     }
 7382:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7383:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7384:     my %scan_data = @tmp;
 7385:     return (\%scanlines,\%scan_data);
 7386: }
 7387: 
 7388: =pod
 7389: 
 7390: =item lonnet_putfile
 7391: 
 7392:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7393: 
 7394:  Arguments:
 7395:    $contents - data to store
 7396:    $filename - filename to store $contents into
 7397: 
 7398:  Returns:
 7399:    result value from &Apache::lonnet::finishuserfileupload
 7400: 
 7401: =cut
 7402: 
 7403: sub lonnet_putfile {
 7404:     my ($contents,$filename)=@_;
 7405:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7406:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7407:     $env{'form.sillywaytopassafilearound'}=$contents;
 7408:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7409: 
 7410: }
 7411: 
 7412: =pod
 7413: 
 7414: =item scantron_putfile
 7415: 
 7416:     Stores the current version of the bubblesheet data files, and the
 7417:     scan_data hash. (Does not modify the original version only the
 7418:     corrected and skipped versions.
 7419: 
 7420:  Arguments:
 7421:     $scanlines - hash ref that looks like the first return value from
 7422:                  &scantron_getfile()
 7423:     $scan_data - hash ref that looks like the second return value from
 7424:                  &scantron_getfile()
 7425: 
 7426: =cut
 7427: 
 7428: sub scantron_putfile {
 7429:     my ($scanlines,$scan_data) = @_;
 7430:     #FIXME really would prefer a scantron directory
 7431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:     if ($scanlines) {
 7434: 	my $prefix='scantron_';
 7435: # no need to update orig, shouldn't change
 7436: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7437: #		    $env{'form.scantron_selectfile'});
 7438: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7439: 			$prefix.'corrected_'.
 7440: 			$env{'form.scantron_selectfile'});
 7441: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7442: 			$prefix.'skipped_'.
 7443: 			$env{'form.scantron_selectfile'});
 7444:     }
 7445:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7446: }
 7447: 
 7448: =pod
 7449: 
 7450: =item scantron_get_line
 7451: 
 7452:    Returns the correct version of the scanline
 7453: 
 7454:  Arguments:
 7455:     $scanlines - hash ref that looks like the first return value from
 7456:                  &scantron_getfile()
 7457:     $scan_data - hash ref that looks like the second return value from
 7458:                  &scantron_getfile()
 7459:     $i         - number of the requested line (starts at 0)
 7460: 
 7461:  Returns:
 7462:    A scanline, (either the original or the corrected one if it
 7463:    exists), or undef if the requested scanline should be
 7464:    skipped. (Either because it's an skipped scanline, or it's an
 7465:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7466:    pass.
 7467: 
 7468: =cut
 7469: 
 7470: sub scantron_get_line {
 7471:     my ($scanlines,$scan_data,$i)=@_;
 7472:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7473:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7474:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7475:     return $scanlines->{'orig'}[$i]; 
 7476: }
 7477: 
 7478: =pod
 7479: 
 7480: =item scantron_todo_count
 7481: 
 7482:     Counts the number of scanlines that need processing.
 7483: 
 7484:  Arguments:
 7485:     $scanlines - hash ref that looks like the first return value from
 7486:                  &scantron_getfile()
 7487:     $scan_data - hash ref that looks like the second return value from
 7488:                  &scantron_getfile()
 7489: 
 7490:  Returns:
 7491:     $count - number of scanlines to process
 7492: 
 7493: =cut
 7494: 
 7495: sub get_todo_count {
 7496:     my ($scanlines,$scan_data)=@_;
 7497:     my $count=0;
 7498:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7499: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7500: 	if ($line=~/^[\s\cz]*$/) { next; }
 7501: 	$count++;
 7502:     }
 7503:     return $count;
 7504: }
 7505: 
 7506: =pod
 7507: 
 7508: =item scantron_put_line
 7509: 
 7510:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7511:     data file.
 7512: 
 7513:  Arguments:
 7514:     $scanlines - hash ref that looks like the first return value from
 7515:                  &scantron_getfile()
 7516:     $scan_data - hash ref that looks like the second return value from
 7517:                  &scantron_getfile()
 7518:     $i         - line number to update
 7519:     $newline   - contents of the updated scanline
 7520:     $skip      - if true make the line for skipping and update the
 7521:                  'skipped' file
 7522: 
 7523: =cut
 7524: 
 7525: sub scantron_put_line {
 7526:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7527:     if ($skip) {
 7528: 	$scanlines->{'skipped'}[$i]=$newline;
 7529: 	&start_skipping($scan_data,$i);
 7530: 	return;
 7531:     }
 7532:     $scanlines->{'corrected'}[$i]=$newline;
 7533: }
 7534: 
 7535: =pod
 7536: 
 7537: =item scantron_clear_skip
 7538: 
 7539:    Remove a line from the 'skipped' file
 7540: 
 7541:  Arguments:
 7542:     $scanlines - hash ref that looks like the first return value from
 7543:                  &scantron_getfile()
 7544:     $scan_data - hash ref that looks like the second return value from
 7545:                  &scantron_getfile()
 7546:     $i         - line number to update
 7547: 
 7548: =cut
 7549: 
 7550: sub scantron_clear_skip {
 7551:     my ($scanlines,$scan_data,$i)=@_;
 7552:     if (exists($scanlines->{'skipped'}[$i])) {
 7553: 	undef($scanlines->{'skipped'}[$i]);
 7554: 	return 1;
 7555:     }
 7556:     return 0;
 7557: }
 7558: 
 7559: =pod
 7560: 
 7561: =item scantron_filter_not_exam
 7562: 
 7563:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7564:    filter out resources that are not marked as 'exam' mode
 7565: 
 7566: =cut
 7567: 
 7568: sub scantron_filter_not_exam {
 7569:     my ($curres)=@_;
 7570:     
 7571:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7572: 	# if the user has asked to not have either hidden
 7573: 	# or 'randomout' controlled resources to be graded
 7574: 	# don't include them
 7575: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7576: 	    && $curres->randomout) {
 7577: 	    return 0;
 7578: 	}
 7579: 	return 1;
 7580:     }
 7581:     return 0;
 7582: }
 7583: 
 7584: =pod
 7585: 
 7586: =item scantron_validate_sequence
 7587: 
 7588:     Validates the selected sequence, checking for resource that are
 7589:     not set to exam mode.
 7590: 
 7591: =cut
 7592: 
 7593: sub scantron_validate_sequence {
 7594:     my ($r,$currentphase) = @_;
 7595: 
 7596:     my $navmap=Apache::lonnavmaps::navmap->new();
 7597:     unless (ref($navmap)) {
 7598:         $r->print(&navmap_errormsg());
 7599:         return (1,$currentphase);
 7600:     }
 7601:     my (undef,undef,$sequence)=
 7602: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7603: 
 7604:     my $map=$navmap->getResourceByUrl($sequence);
 7605: 
 7606:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7607:                                     value="ignore" />');
 7608:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7609: 	my @resources=
 7610: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7611: 	if (@resources) {
 7612: 	    $r->print('<p class="LC_warning">'
 7613:                .&mt('Some resources in the sequence currently are not set to'
 7614:                    .' exam mode. Grading these resources currently may not'
 7615:                    .' work correctly.')
 7616:                .'</p>'
 7617:             );
 7618: 	    return (1,$currentphase);
 7619: 	}
 7620:     }
 7621: 
 7622:     return (0,$currentphase+1);
 7623: }
 7624: 
 7625: 
 7626: 
 7627: sub scantron_validate_ID {
 7628:     my ($r,$currentphase) = @_;
 7629:     
 7630:     #get student info
 7631:     my $classlist=&Apache::loncoursedata::get_classlist();
 7632:     my %idmap=&username_to_idmap($classlist);
 7633: 
 7634:     #get scantron line setup
 7635:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7636:     my ($scanlines,$scan_data)=&scantron_getfile();
 7637: 
 7638:     my $nav_error;
 7639:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7640:     if ($nav_error) {
 7641:         $r->print(&navmap_errormsg());
 7642:         return(1,$currentphase);
 7643:     }
 7644: 
 7645:     my %found=('ids'=>{},'usernames'=>{});
 7646:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7647: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7648: 	if ($line=~/^[\s\cz]*$/) { next; }
 7649: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7650: 						 $scan_data);
 7651: 	my $id=$$scan_record{'scantron.ID'};
 7652: 	my $found;
 7653: 	foreach my $checkid (keys(%idmap)) {
 7654: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7655: 	}
 7656: 	if ($found) {
 7657: 	    my $username=$idmap{$found};
 7658: 	    if ($found{'ids'}{$found}) {
 7659: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7660: 					 $line,'duplicateID',$found);
 7661: 		return(1,$currentphase);
 7662: 	    } elsif ($found{'usernames'}{$username}) {
 7663: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7664: 					 $line,'duplicateID',$username);
 7665: 		return(1,$currentphase);
 7666: 	    }
 7667: 	    #FIXME store away line we previously saw the ID on to use above
 7668: 	    $found{'ids'}{$found}++;
 7669: 	    $found{'usernames'}{$username}++;
 7670: 	} else {
 7671: 	    if ($id =~ /^\s*$/) {
 7672: 		my $username=&scan_data($scan_data,"$i.user");
 7673: 		if (defined($username) && $found{'usernames'}{$username}) {
 7674: 		    &scantron_get_correction($r,$i,$scan_record,
 7675: 					     \%scantron_config,
 7676: 					     $line,'duplicateID',$username);
 7677: 		    return(1,$currentphase);
 7678: 		} elsif (!defined($username)) {
 7679: 		    &scantron_get_correction($r,$i,$scan_record,
 7680: 					     \%scantron_config,
 7681: 					     $line,'incorrectID');
 7682: 		    return(1,$currentphase);
 7683: 		}
 7684: 		$found{'usernames'}{$username}++;
 7685: 	    } else {
 7686: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7687: 					 $line,'incorrectID');
 7688: 		return(1,$currentphase);
 7689: 	    }
 7690: 	}
 7691:     }
 7692: 
 7693:     return (0,$currentphase+1);
 7694: }
 7695: 
 7696: 
 7697: sub scantron_get_correction {
 7698:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7699:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7700: #FIXME in the case of a duplicated ID the previous line, probably need
 7701: #to show both the current line and the previous one and allow skipping
 7702: #the previous one or the current one
 7703: 
 7704:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7705:         $r->print(
 7706:             '<p class="LC_warning">'
 7707:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7708:                 "<b>$error</b>",
 7709:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7710:            ."</p> \n");
 7711:     } else {
 7712:         $r->print(
 7713:             '<p class="LC_warning">'
 7714:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7715:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7716:            ."</p> \n");
 7717:     }
 7718:     my $message =
 7719:         '<p>'
 7720:        .&mt('The ID on the form is [_1]',
 7721:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7722:        .'<br />'
 7723:        .&mt('The name on the paper is [_1], [_2]',
 7724:             $$scan_record{'scantron.LastName'},
 7725:             $$scan_record{'scantron.FirstName'})
 7726:        .'</p>';
 7727: 
 7728:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7729:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7730:                            # Array populated for doublebubble or
 7731:     my @lines_to_correct;  # missingbubble errors to build javascript
 7732:                            # to validate radio button checking   
 7733: 
 7734:     if ($error =~ /ID$/) {
 7735: 	if ($error eq 'incorrectID') {
 7736: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7737: 		      "</p>\n");
 7738: 	} elsif ($error eq 'duplicateID') {
 7739: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7740: 	}
 7741: 	$r->print($message);
 7742: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7743: 	$r->print("\n<ul><li> ");
 7744: 	#FIXME it would be nice if this sent back the user ID and
 7745: 	#could do partial userID matches
 7746: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7747: 				       'scantron_username','scantron_domain'));
 7748: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7749: 	$r->print("\n:\n".
 7750: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7751: 
 7752: 	$r->print('</li>');
 7753:     } elsif ($error =~ /CODE$/) {
 7754: 	if ($error eq 'incorrectCODE') {
 7755: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7756: 	} elsif ($error eq 'duplicateCODE') {
 7757: 	    $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");
 7758: 	}
 7759:         $r->print("<p>".&mt('The CODE on the form is [_1]',
 7760:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7761:                  ."</p>\n");
 7762: 	$r->print($message);
 7763: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7764: 	$r->print("\n<br /> ");
 7765: 	my $i=0;
 7766: 	if ($error eq 'incorrectCODE' 
 7767: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7768: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7769: 	    if ($closest > 0) {
 7770: 		foreach my $testcode (@{$closest}) {
 7771: 		    my $checked='';
 7772: 		    if (!$i) { $checked=' checked="checked"'; }
 7773: 		    $r->print("
 7774:    <label>
 7775:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7776:        ".&mt("Use the similar CODE [_1] instead.",
 7777: 	    "<b><tt>".$testcode."</tt></b>")."
 7778:     </label>
 7779:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7780: 		    $r->print("\n<br />");
 7781: 		    $i++;
 7782: 		}
 7783: 	    }
 7784: 	}
 7785: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7786: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7787: 	    $r->print("
 7788:     <label>
 7789:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7790:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7791: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7792:     </label>");
 7793: 	    $r->print("\n<br />");
 7794: 	}
 7795: 
 7796: 	$r->print(<<ENDSCRIPT);
 7797: <script type="text/javascript">
 7798: function change_radio(field) {
 7799:     var slct=document.scantronupload.scantron_CODE_resolution;
 7800:     var i;
 7801:     for (i=0;i<slct.length;i++) {
 7802:         if (slct[i].value==field) { slct[i].checked=true; }
 7803:     }
 7804: }
 7805: </script>
 7806: ENDSCRIPT
 7807: 	my $href="/adm/pickcode?".
 7808: 	   "form=".&escape("scantronupload").
 7809: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7810: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7811: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7812: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7813: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7814: 	    $r->print("
 7815:     <label>
 7816:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7817:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7818: 	     "<a target='_blank' href='$href'>","</a>")."
 7819:     </label> 
 7820:     ".&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\')" />'));
 7821: 	    $r->print("\n<br />");
 7822: 	}
 7823: 	$r->print("
 7824:     <label>
 7825:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7826:        ".&mt("Use [_1] as the CODE.",
 7827: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7828: 	$r->print("\n<br /><br />");
 7829:     } elsif ($error eq 'doublebubble') {
 7830: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7831: 
 7832: 	# The form field scantron_questions is acutally a list of line numbers.
 7833: 	# represented by this form so:
 7834: 
 7835: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7836:                                                 $respnumlookup,$startline);
 7837: 
 7838: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7839: 		  $line_list.'" />');
 7840: 	$r->print($message);
 7841: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7842: 	foreach my $question (@{$arg}) {
 7843: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7844:                                                    $scan_record, $error,
 7845:                                                    $randomorder,$randompick,
 7846:                                                    $respnumlookup,$startline);
 7847:             push(@lines_to_correct,@linenums);
 7848: 	}
 7849:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7850:     } elsif ($error eq 'missingbubble') {
 7851: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7852: 	$r->print($message);
 7853: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7854: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7855: 
 7856: 	# The form field scantron_questions is actually a list of line numbers not
 7857: 	# a list of question numbers. Therefore:
 7858: 	#
 7859: 	
 7860: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7861:                                                 $respnumlookup,$startline);
 7862: 
 7863: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7864: 		  $line_list.'" />');
 7865: 	foreach my $question (@{$arg}) {
 7866: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7867:                                                    $scan_record, $error,
 7868:                                                    $randomorder,$randompick,
 7869:                                                    $respnumlookup,$startline);
 7870:             push(@lines_to_correct,@linenums);
 7871: 	}
 7872:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7873:     } else {
 7874: 	$r->print("\n<ul>");
 7875:     }
 7876:     $r->print("\n</li></ul>");
 7877: }
 7878: 
 7879: sub verify_bubbles_checked {
 7880:     my (@ansnums) = @_;
 7881:     my $ansnumstr = join('","',@ansnums);
 7882:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7883:     &js_escape(\$warning);
 7884:     my $output = (<<ENDSCRIPT);
 7885: <script type="text/javascript">
 7886: function verify_bubble_radio(form) {
 7887:     var ansnumArray = new Array ("$ansnumstr");
 7888:     var need_bubble_count = 0;
 7889:     for (var i=0; i<ansnumArray.length; i++) {
 7890:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7891:             var bubble_picked = 0; 
 7892:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7893:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7894:                     bubble_picked = 1;
 7895:                 }
 7896:             }
 7897:             if (bubble_picked == 0) {
 7898:                 need_bubble_count ++;
 7899:             }
 7900:         }
 7901:     }
 7902:     if (need_bubble_count) {
 7903:         alert("$warning");
 7904:         return;
 7905:     }
 7906:     form.submit(); 
 7907: }
 7908: </script>
 7909: ENDSCRIPT
 7910:     return $output;
 7911: }
 7912: 
 7913: =pod
 7914: 
 7915: =item  questions_to_line_list
 7916: 
 7917: Converts a list of questions into a string of comma separated
 7918: line numbers in the answer sheet used by the questions.  This is
 7919: used to fill in the scantron_questions form field.
 7920: 
 7921:   Arguments:
 7922:      questions    - Reference to an array of questions.
 7923:      randomorder  - True if randomorder in use.
 7924:      randompick   - True if randompick in use.
 7925:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7926:                      for current line to question number used for same question
 7927:                      in "Master Seqence" (as seen by Course Coordinator).
 7928:      startline    - Reference to hash where key is question number (0 is first)
 7929:                     and key is number of first bubble line for current student
 7930:                     or code-based randompick and/or randomorder.
 7931: 
 7932: =cut
 7933: 
 7934: 
 7935: sub questions_to_line_list {
 7936:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7937:     my @lines;
 7938: 
 7939:     foreach my $item (@{$questions}) {
 7940:         my $question = $item;
 7941:         my ($first,$count,$last);
 7942:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7943:             $question = $1;
 7944:             my $subquestion = $2;
 7945:             my $responsenum = $question-1;
 7946:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7947:                 $responsenum = $respnumlookup->{$question-1};
 7948:                 if (ref($startline) eq 'HASH') {
 7949:                     $first = $startline->{$question-1} + 1;
 7950:                 }
 7951:             } else {
 7952:                 $first = $first_bubble_line{$responsenum} + 1;
 7953:             }
 7954:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7955:             my $subcount = 1;
 7956:             while ($subcount<$subquestion) {
 7957:                 $first += $subans[$subcount-1];
 7958:                 $subcount ++;
 7959:             }
 7960:             $count = $subans[$subquestion-1];
 7961:         } else {
 7962:             my $responsenum = $question-1;
 7963:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7964:                 $responsenum = $respnumlookup->{$question-1};
 7965:                 if (ref($startline) eq 'HASH') {
 7966:                     $first = $startline->{$question-1} + 1;
 7967:                 }
 7968:             } else {
 7969:                 $first = $first_bubble_line{$responsenum} + 1;
 7970:             }
 7971:             $count   = $bubble_lines_per_response{$responsenum};
 7972:         }
 7973:         $last = $first+$count-1;
 7974:         push(@lines, ($first..$last));
 7975:     }
 7976:     return join(',', @lines);
 7977: }
 7978: 
 7979: =pod 
 7980: 
 7981: =item prompt_for_corrections
 7982: 
 7983: Prompts for a potentially multiline correction to the
 7984: user's bubbling (factors out common code from scantron_get_correction
 7985: for multi and missing bubble cases).
 7986: 
 7987:  Arguments:
 7988:    $r           - Apache request object.
 7989:    $question    - The question number to prompt for.
 7990:    $scan_config - The scantron file configuration hash.
 7991:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7992:    $error       - Type of error
 7993:    $randomorder - True if randomorder in use.
 7994:    $randompick  - True if randompick in use.
 7995:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7996:                     for current line to question number used for same question
 7997:                     in "Master Seqence" (as seen by Course Coordinator).
 7998:    $startline   - Reference to hash where key is question number (0 is first)
 7999:                   and value is number of first bubble line for current student
 8000:                   or code-based randompick and/or randomorder.
 8001: 
 8002:  Implicit inputs:
 8003:    %bubble_lines_per_response   - Starting line numbers for each question.
 8004:                                   Numbered from 0 (but question numbers are from
 8005:                                   1.
 8006:    %first_bubble_line           - Starting bubble line for each question.
 8007:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8008:                                   type problems render as separate sub-questions, 
 8009:                                   in exam mode. This hash contains a 
 8010:                                   comma-separated list of the lines per 
 8011:                                   sub-question.
 8012:    %responsetype_per_response   - essayresponse, formularesponse,
 8013:                                   stringresponse, imageresponse, reactionresponse,
 8014:                                   and organicresponse type problem parts can have
 8015:                                   multiple lines per response if the weight
 8016:                                   assigned exceeds 10.  In this case, only
 8017:                                   one bubble per line is permitted, but more 
 8018:                                   than one line might contain bubbles, e.g.
 8019:                                   bubbling of: line 1 - J, line 2 - J, 
 8020:                                   line 3 - B would assign 22 points.  
 8021: 
 8022: =cut
 8023: 
 8024: sub prompt_for_corrections {
 8025:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8026:         $randompick, $respnumlookup, $startline) = @_;
 8027:     my ($current_line,$lines);
 8028:     my @linenums;
 8029:     my $questionnum = $question;
 8030:     my ($first,$responsenum);
 8031:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8032:         $question = $1;
 8033:         my $subquestion = $2;
 8034:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8035:             $responsenum = $respnumlookup->{$question-1};
 8036:             if (ref($startline) eq 'HASH') {
 8037:                 $first = $startline->{$question-1};
 8038:             }
 8039:         } else {
 8040:             $responsenum = $question-1;
 8041:             $first = $first_bubble_line{$responsenum};
 8042:         }
 8043:         $current_line = $first + 1 ;
 8044:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8045:         my $subcount = 1;
 8046:         while ($subcount<$subquestion) {
 8047:             $current_line += $subans[$subcount-1];
 8048:             $subcount ++;
 8049:         }
 8050:         $lines = $subans[$subquestion-1];
 8051:     } else {
 8052:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8053:             $responsenum = $respnumlookup->{$question-1};
 8054:             if (ref($startline) eq 'HASH') {
 8055:                 $first = $startline->{$question-1};
 8056:             }
 8057:         } else {
 8058:             $responsenum = $question-1;
 8059:             $first = $first_bubble_line{$responsenum};
 8060:         }
 8061:         $current_line = $first + 1;
 8062:         $lines        = $bubble_lines_per_response{$responsenum};
 8063:     }
 8064:     if ($lines > 1) {
 8065:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8066:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8067:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8068:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8069:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8070:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8071:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8072:             $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 />');
 8073:         } else {
 8074:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8075:         }
 8076:     }
 8077:     for (my $i =0; $i < $lines; $i++) {
 8078:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8079: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8080: 	        		  $questionnum,$error,split('', $selected));
 8081:         push(@linenums,$current_line);
 8082: 	$current_line++;
 8083:     }
 8084:     if ($lines > 1) {
 8085: 	$r->print("<hr /><br />");
 8086:     }
 8087:     return @linenums;
 8088: }
 8089: 
 8090: =pod
 8091: 
 8092: =item scantron_bubble_selector
 8093:   
 8094:    Generates the html radiobuttons to correct a single bubble line
 8095:    possibly showing the existing the selected bubbles if known
 8096: 
 8097:  Arguments:
 8098:     $r           - Apache request object
 8099:     $scan_config - hash from &get_scantron_config()
 8100:     $line        - Number of the line being displayed.
 8101:     $questionnum - Question number (may include subquestion)
 8102:     $error       - Type of error.
 8103:     @selected    - Array of bubbles picked on this line.
 8104: 
 8105: =cut
 8106: 
 8107: sub scantron_bubble_selector {
 8108:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8109:     my $max=$$scan_config{'Qlength'};
 8110: 
 8111:     my $scmode=$$scan_config{'Qon'};
 8112:     if ($scmode eq 'number' || $scmode eq 'letter') {
 8113:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8114:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8115:             $max=$$scan_config{'BubblesPerRow'};
 8116:             if (($scmode eq 'number') && ($max > 10)) {
 8117:                 $max = 10;
 8118:             } elsif (($scmode eq 'letter') && $max > 26) {
 8119:                 $max = 26;
 8120:             }
 8121:         } else {
 8122:             $max = 10;
 8123:         }
 8124:     }
 8125: 
 8126:     my @alphabet=('A'..'Z');
 8127:     $r->print(&Apache::loncommon::start_data_table().
 8128:               &Apache::loncommon::start_data_table_row());
 8129:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8130:     for (my $i=0;$i<$max+1;$i++) {
 8131: 	$r->print("\n".'<td align="center">');
 8132: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8133: 	else { $r->print('&nbsp;'); }
 8134: 	$r->print('</td>');
 8135:     }
 8136:     $r->print(&Apache::loncommon::end_data_table_row().
 8137:               &Apache::loncommon::start_data_table_row());
 8138:     for (my $i=0;$i<$max;$i++) {
 8139: 	$r->print("\n".
 8140: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8141: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8142:     }
 8143:     my $nobub_checked = ' ';
 8144:     if ($error eq 'missingbubble') {
 8145:         $nobub_checked = ' checked = "checked" ';
 8146:     }
 8147:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8148: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8149:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8150:               $line.'" value="'.$questionnum.'" /></td>');
 8151:     $r->print(&Apache::loncommon::end_data_table_row().
 8152:               &Apache::loncommon::end_data_table());
 8153: }
 8154: 
 8155: =pod
 8156: 
 8157: =item num_matches
 8158: 
 8159:    Counts the number of characters that are the same between the two arguments.
 8160: 
 8161:  Arguments:
 8162:    $orig - CODE from the scanline
 8163:    $code - CODE to match against
 8164: 
 8165:  Returns:
 8166:    $count - integer count of the number of same characters between the
 8167:             two arguments
 8168: 
 8169: =cut
 8170: 
 8171: sub num_matches {
 8172:     my ($orig,$code) = @_;
 8173:     my @code=split(//,$code);
 8174:     my @orig=split(//,$orig);
 8175:     my $same=0;
 8176:     for (my $i=0;$i<scalar(@code);$i++) {
 8177: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8178:     }
 8179:     return $same;
 8180: }
 8181: 
 8182: =pod
 8183: 
 8184: =item scantron_get_closely_matching_CODEs
 8185: 
 8186:    Cycles through all CODEs and finds the set that has the greatest
 8187:    number of same characters as the provided CODE
 8188: 
 8189:  Arguments:
 8190:    $allcodes - hash ref returned by &get_codes()
 8191:    $CODE     - CODE from the current scanline
 8192: 
 8193:  Returns:
 8194:    2 element list
 8195:     - first elements is number of how closely matching the best fit is 
 8196:       (5 means best set has 5 matching characters)
 8197:     - second element is an arrary ref containing the set of valid CODEs
 8198:       that best fit the passed in CODE
 8199: 
 8200: =cut
 8201: 
 8202: sub scantron_get_closely_matching_CODEs {
 8203:     my ($allcodes,$CODE)=@_;
 8204:     my @CODEs;
 8205:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8206: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8207:     }
 8208: 
 8209:     return ($#CODEs,$CODEs[-1]);
 8210: }
 8211: 
 8212: =pod
 8213: 
 8214: =item get_codes
 8215: 
 8216:    Builds a hash which has keys of all of the valid CODEs from the selected
 8217:    set of remembered CODEs.
 8218: 
 8219:  Arguments:
 8220:   $old_name - name of the set of remembered CODEs
 8221:   $cdom     - domain of the course
 8222:   $cnum     - internal course name
 8223: 
 8224:  Returns:
 8225:   %allcodes - keys are the valid CODEs, values are all 1
 8226: 
 8227: =cut
 8228: 
 8229: sub get_codes {
 8230:     my ($old_name, $cdom, $cnum) = @_;
 8231:     if (!$old_name) {
 8232: 	$old_name=$env{'form.scantron_CODElist'};
 8233:     }
 8234:     if (!$cdom) {
 8235: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8236:     }
 8237:     if (!$cnum) {
 8238: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8239:     }
 8240:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8241: 				    $cdom,$cnum);
 8242:     my %allcodes;
 8243:     if ($result{"type\0$old_name"} eq 'number') {
 8244: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8245:     } else {
 8246: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8247:     }
 8248:     return %allcodes;
 8249: }
 8250: 
 8251: =pod
 8252: 
 8253: =item scantron_validate_CODE
 8254: 
 8255:    Validates all scanlines in the selected file to not have any
 8256:    invalid or underspecified CODEs and that none of the codes are
 8257:    duplicated if this was requested.
 8258: 
 8259: =cut
 8260: 
 8261: sub scantron_validate_CODE {
 8262:     my ($r,$currentphase) = @_;
 8263:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8264:     if ($scantron_config{'CODElocation'} &&
 8265: 	$scantron_config{'CODEstart'} &&
 8266: 	$scantron_config{'CODElength'}) {
 8267: 	if (!defined($env{'form.scantron_CODElist'})) {
 8268: 	    &FIXME_blow_up()
 8269: 	}
 8270:     } else {
 8271: 	return (0,$currentphase+1);
 8272:     }
 8273:     
 8274:     my %usedCODEs;
 8275: 
 8276:     my %allcodes=&get_codes();
 8277: 
 8278:     my $nav_error;
 8279:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8280:     if ($nav_error) {
 8281:         $r->print(&navmap_errormsg());
 8282:         return(1,$currentphase);
 8283:     }
 8284: 
 8285:     my ($scanlines,$scan_data)=&scantron_getfile();
 8286:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8287: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8288: 	if ($line=~/^[\s\cz]*$/) { next; }
 8289: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8290: 						 $scan_data);
 8291: 	my $CODE=$$scan_record{'scantron.CODE'};
 8292: 	my $error=0;
 8293: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8294: 	    &scantron_get_correction($r,$i,$scan_record,
 8295: 				     \%scantron_config,
 8296: 				     $line,'incorrectCODE',\%allcodes);
 8297: 	    return(1,$currentphase);
 8298: 	}
 8299: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8300: 	    && !$$scan_record{'scantron.useCODE'}) {
 8301: 	    &scantron_get_correction($r,$i,$scan_record,
 8302: 				     \%scantron_config,
 8303: 				     $line,'incorrectCODE',\%allcodes);
 8304: 	    return(1,$currentphase);
 8305: 	}
 8306: 	if (exists($usedCODEs{$CODE}) 
 8307: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8308: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8309: 	    &scantron_get_correction($r,$i,$scan_record,
 8310: 				     \%scantron_config,
 8311: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8312: 	    return(1,$currentphase);
 8313: 	}
 8314: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8315:     }
 8316:     return (0,$currentphase+1);
 8317: }
 8318: 
 8319: =pod
 8320: 
 8321: =item scantron_validate_doublebubble
 8322: 
 8323:    Validates all scanlines in the selected file to not have any
 8324:    bubble lines with multiple bubbles marked.
 8325: 
 8326: =cut
 8327: 
 8328: sub scantron_validate_doublebubble {
 8329:     my ($r,$currentphase) = @_;
 8330:     #get student info
 8331:     my $classlist=&Apache::loncoursedata::get_classlist();
 8332:     my %idmap=&username_to_idmap($classlist);
 8333:     my (undef,undef,$sequence)=
 8334:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8335: 
 8336:     #get scantron line setup
 8337:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8338:     my ($scanlines,$scan_data)=&scantron_getfile();
 8339: 
 8340:     my $navmap = Apache::lonnavmaps::navmap->new();
 8341:     unless (ref($navmap)) {
 8342:         $r->print(&navmap_errormsg());
 8343:         return(1,$currentphase);
 8344:     }
 8345:     my $map=$navmap->getResourceByUrl($sequence);
 8346:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8347:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8348:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8349:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8350: 
 8351:     my $nav_error;
 8352:     if (ref($map)) {
 8353:         $randomorder = $map->randomorder();
 8354:         $randompick = $map->randompick();
 8355:         if ($randomorder || $randompick) {
 8356:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8357:             if ($nav_error) {
 8358:                 $r->print(&navmap_errormsg());
 8359:                 return(1,$currentphase);
 8360:             }
 8361:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8362:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8363:         }
 8364:     } else {
 8365:         $r->print(&navmap_errormsg());
 8366:         return(1,$currentphase);
 8367:     }
 8368: 
 8369:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8370:     if ($nav_error) {
 8371:         $r->print(&navmap_errormsg());
 8372:         return(1,$currentphase);
 8373:     }
 8374: 
 8375:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8376: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8377: 	if ($line=~/^[\s\cz]*$/) { next; }
 8378: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8379: 						 $scan_data,undef,\%idmap,$randomorder,
 8380:                                                  $randompick,$sequence,\@master_seq,
 8381:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8382:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8383: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8384: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8385: 				 'doublebubble',
 8386: 				 $$scan_record{'scantron.doubleerror'},
 8387:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8388:     	return (1,$currentphase);
 8389:     }
 8390:     return (0,$currentphase+1);
 8391: }
 8392: 
 8393: 
 8394: sub scantron_get_maxbubble {
 8395:     my ($nav_error,$scantron_config) = @_;
 8396:     if (defined($env{'form.scantron_maxbubble'}) &&
 8397: 	$env{'form.scantron_maxbubble'}) {
 8398: 	&restore_bubble_lines();
 8399: 	return $env{'form.scantron_maxbubble'};
 8400:     }
 8401: 
 8402:     my (undef, undef, $sequence) =
 8403: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8404: 
 8405:     my $navmap=Apache::lonnavmaps::navmap->new();
 8406:     unless (ref($navmap)) {
 8407:         if (ref($nav_error)) {
 8408:             $$nav_error = 1;
 8409:         }
 8410:         return;
 8411:     }
 8412:     my $map=$navmap->getResourceByUrl($sequence);
 8413:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8414:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8415: 
 8416:     &Apache::lonxml::clear_problem_counter();
 8417: 
 8418:     my $uname       = $env{'user.name'};
 8419:     my $udom        = $env{'user.domain'};
 8420:     my $cid         = $env{'request.course.id'};
 8421:     my $total_lines = 0;
 8422:     %bubble_lines_per_response = ();
 8423:     %first_bubble_line         = ();
 8424:     %subdivided_bubble_lines   = ();
 8425:     %responsetype_per_response = ();
 8426:     %masterseq_id_responsenum  = ();
 8427: 
 8428:     my $response_number = 0;
 8429:     my $bubble_line     = 0;
 8430:     foreach my $resource (@resources) {
 8431:         my $resid = $resource->id();
 8432:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8433:                                                           $udom,undef,$bubbles_per_row);
 8434:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8435: 	    foreach my $part_id (@{$parts}) {
 8436:                 my $lines;
 8437: 
 8438: 	        # TODO - make this a persistent hash not an array.
 8439: 
 8440:                 # optionresponse, matchresponse and rankresponse type items 
 8441:                 # render as separate sub-questions in exam mode.
 8442:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8443:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8444:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8445:                     my ($numbub,$numshown);
 8446:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8447:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8448:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8449:                         }
 8450:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8451:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8452:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8453:                         }
 8454:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8455:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8456:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8457:                         }
 8458:                     }
 8459:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8460:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8461:                     }
 8462:                     my $bubbles_per_row =
 8463:                         &bubblesheet_bubbles_per_row($scantron_config);
 8464:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8465:                     if (($numbub % $bubbles_per_row) != 0) {
 8466:                         $inner_bubble_lines++;
 8467:                     }
 8468:                     for (my $i=0; $i<$numshown; $i++) {
 8469:                         $subdivided_bubble_lines{$response_number} .= 
 8470:                             $inner_bubble_lines.',';
 8471:                     }
 8472:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8473:                     $lines = $numshown * $inner_bubble_lines;
 8474:                 } else {
 8475:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8476:                 }
 8477: 
 8478:                 $first_bubble_line{$response_number} = $bubble_line;
 8479: 	        $bubble_lines_per_response{$response_number} = $lines;
 8480:                 $responsetype_per_response{$response_number} = 
 8481:                     $analysis->{$part_id.'.type'};
 8482:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
 8483: 	        $response_number++;
 8484: 
 8485: 	        $bubble_line +=  $lines;
 8486: 	        $total_lines +=  $lines;
 8487: 	    }
 8488:         }
 8489:     }
 8490:     &Apache::lonnet::delenv('scantron.');
 8491: 
 8492:     &save_bubble_lines();
 8493:     $env{'form.scantron_maxbubble'} =
 8494: 	$total_lines;
 8495:     return $env{'form.scantron_maxbubble'};
 8496: }
 8497: 
 8498: sub bubblesheet_bubbles_per_row {
 8499:     my ($scantron_config) = @_;
 8500:     my $bubbles_per_row;
 8501:     if (ref($scantron_config) eq 'HASH') {
 8502:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8503:     }
 8504:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8505:         $bubbles_per_row = 10;
 8506:     }
 8507:     return $bubbles_per_row;
 8508: }
 8509: 
 8510: sub scantron_validate_missingbubbles {
 8511:     my ($r,$currentphase) = @_;
 8512:     #get student info
 8513:     my $classlist=&Apache::loncoursedata::get_classlist();
 8514:     my %idmap=&username_to_idmap($classlist);
 8515:     my (undef,undef,$sequence)=
 8516:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8517: 
 8518:     #get scantron line setup
 8519:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8520:     my ($scanlines,$scan_data)=&scantron_getfile();
 8521: 
 8522:     my $navmap = Apache::lonnavmaps::navmap->new();
 8523:     unless (ref($navmap)) {
 8524:         $r->print(&navmap_errormsg());
 8525:         return(1,$currentphase);
 8526:     }
 8527: 
 8528:     my $map=$navmap->getResourceByUrl($sequence);
 8529:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8530:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8531:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8532:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8533: 
 8534:     my $nav_error;
 8535:     if (ref($map)) {
 8536:         $randomorder = $map->randomorder();
 8537:         $randompick = $map->randompick();
 8538:         if ($randomorder || $randompick) {
 8539:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8540:             if ($nav_error) {
 8541:                 $r->print(&navmap_errormsg());
 8542:                 return(1,$currentphase);
 8543:             }
 8544:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8545:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8546:         }
 8547:     } else {
 8548:         $r->print(&navmap_errormsg());
 8549:         return(1,$currentphase);
 8550:     }
 8551: 
 8552: 
 8553:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8554:     if ($nav_error) {
 8555:         $r->print(&navmap_errormsg());
 8556:         return(1,$currentphase);
 8557:     }
 8558: 
 8559:     if (!$max_bubble) { $max_bubble=2**31; }
 8560:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8561: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8562: 	if ($line=~/^[\s\cz]*$/) { next; }
 8563:         my $scan_record =
 8564:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8565:                                      $randomorder,$randompick,$sequence,\@master_seq,
 8566:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8567:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8568: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8569: 	my @to_correct;
 8570: 	
 8571: 	# Probably here's where the error is...
 8572: 
 8573: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8574:             my $lastbubble;
 8575:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8576:                 my $question = $1;
 8577:                 my $subquestion = $2;
 8578:                 my ($first,$responsenum);
 8579:                 if ($randomorder || $randompick) {
 8580:                     $responsenum = $respnumlookup{$question-1};
 8581:                     $first = $startline{$question-1};
 8582:                 } else {
 8583:                     $responsenum = $question-1;
 8584:                     $first = $first_bubble_line{$responsenum};
 8585:                 }
 8586:                 if (!defined($first)) { next; }
 8587:                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8588:                 my $subcount = 1;
 8589:                 while ($subcount<$subquestion) {
 8590:                     $first += $subans[$subcount-1];
 8591:                     $subcount ++;
 8592:                 }
 8593:                 my $count = $subans[$subquestion-1];
 8594:                 $lastbubble = $first + $count;
 8595:             } else {
 8596:                 my ($first,$responsenum);
 8597:                 if ($randomorder || $randompick) {
 8598:                     $responsenum = $respnumlookup{$missing-1};
 8599:                     $first = $startline{$missing-1};
 8600:                 } else {
 8601:                     $responsenum = $missing-1;
 8602:                     $first = $first_bubble_line{$responsenum};
 8603:                 }
 8604:                 if (!defined($first)) { next; }
 8605:                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8606:             }
 8607:             if ($lastbubble > $max_bubble) { next; }
 8608: 	    push(@to_correct,$missing);
 8609: 	}
 8610: 	if (@to_correct) {
 8611: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8612: 				     $line,'missingbubble',\@to_correct,
 8613:                                      $randomorder,$randompick,\%respnumlookup,
 8614:                                      \%startline);
 8615: 	    return (1,$currentphase);
 8616: 	}
 8617: 
 8618:     }
 8619:     return (0,$currentphase+1);
 8620: }
 8621: 
 8622: sub hand_bubble_option {
 8623:     my (undef, undef, $sequence) =
 8624:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8625:     return if ($sequence eq '');
 8626:     my $navmap = Apache::lonnavmaps::navmap->new();
 8627:     unless (ref($navmap)) {
 8628:         return;
 8629:     }
 8630:     my $needs_hand_bubbles;
 8631:     my $map=$navmap->getResourceByUrl($sequence);
 8632:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8633:     foreach my $res (@resources) {
 8634:         if (ref($res)) {
 8635:             if ($res->is_problem()) {
 8636:                 my $partlist = $res->parts();
 8637:                 foreach my $part (@{ $partlist }) {
 8638:                     my @types = $res->responseType($part);
 8639:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8640:                         $needs_hand_bubbles = 1;
 8641:                         last;
 8642:                     }
 8643:                 }
 8644:             }
 8645:         }
 8646:     }
 8647:     if ($needs_hand_bubbles) {
 8648:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8649:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8650:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8651:                &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 />').
 8652:                '<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;'.
 8653:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8654:     }
 8655:     return;
 8656: }
 8657: 
 8658: sub scantron_process_students {
 8659:     my ($r) = @_;
 8660: 
 8661:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8662:     my ($symb)=&get_symb($r);
 8663:     if (!$symb) {
 8664: 	return '';
 8665:     }
 8666:     my $default_form_data=&defaultFormData($symb);
 8667: 
 8668:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8669:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8670:     my ($scanlines,$scan_data)=&scantron_getfile();
 8671:     my $classlist=&Apache::loncoursedata::get_classlist();
 8672:     my %idmap=&username_to_idmap($classlist);
 8673:     my $navmap=Apache::lonnavmaps::navmap->new();
 8674:     unless (ref($navmap)) {
 8675:         $r->print(&navmap_errormsg());
 8676:         return '';
 8677:     }
 8678:     my $map=$navmap->getResourceByUrl($sequence);
 8679:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8680:         %grader_randomlists_by_symb);
 8681:     if (ref($map)) {
 8682:         $randomorder = $map->randomorder();
 8683:         $randompick = $map->randompick();
 8684:     } else {
 8685:         $r->print(&navmap_errormsg());
 8686:         return '';
 8687:     }
 8688:     my $nav_error;
 8689:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8690:     if ($randomorder || $randompick) {
 8691:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8692:         if ($nav_error) {
 8693:             $r->print(&navmap_errormsg());
 8694:             return '';
 8695:         }
 8696:     }
 8697:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8698:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8699: 
 8700:     my ($uname,$udom);
 8701:     my $result= <<SCANTRONFORM;
 8702: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8703:   <input type="hidden" name="command" value="scantron_configphase" />
 8704:   $default_form_data
 8705: SCANTRONFORM
 8706:     $r->print($result);
 8707: 
 8708:     my @delayqueue;
 8709:     my (%completedstudents,%scandata);
 8710:     
 8711:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8712:     my $count=&get_todo_count($scanlines,$scan_data);
 8713:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8714:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8715: 					  'Processing first student');
 8716:     $r->print('<br />');
 8717:     my $start=&Time::HiRes::time();
 8718:     my $i=-1;
 8719:     my $started;
 8720: 
 8721:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8722:     if ($nav_error) {
 8723:         $r->print(&navmap_errormsg());
 8724:         return '';
 8725:     }
 8726: 
 8727:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8728:     # the user and return.
 8729: 
 8730:     if ($ssi_error) {
 8731: 	$r->print("</form>");
 8732: 	&ssi_print_error($r);
 8733: 	$r->print(&show_grading_menu_form($symb));
 8734:         &Apache::lonnet::remove_lock($lock);
 8735: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8736:     }
 8737: 
 8738:     my %lettdig = &letter_to_digits();
 8739:     my $numletts = scalar(keys(%lettdig));
 8740:     my %orderedforcode;
 8741: 
 8742:     while ($i<$scanlines->{'count'}) {
 8743:  	($uname,$udom)=('','');
 8744:  	$i++;
 8745:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8746:  	if ($line=~/^[\s\cz]*$/) { next; }
 8747: 	if ($started) {
 8748: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8749: 						     'last student');
 8750: 	}
 8751: 	$started=1;
 8752:         my %respnumlookup = ();
 8753:         my %startline = ();
 8754:         my $total;
 8755:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8756:  						 $scan_data,undef,\%idmap,$randomorder,
 8757:                                                  $randompick,$sequence,\@master_seq,
 8758:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8759:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8760:                                                  \$total);
 8761:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8762:  					      \%idmap,$i)) {
 8763:   	    &scantron_add_delay(\@delayqueue,$line,
 8764:  				'Unable to find a student that matches',1);
 8765:  	    next;
 8766:   	}
 8767:  	if (exists $completedstudents{$uname}) {
 8768:  	    &scantron_add_delay(\@delayqueue,$line,
 8769:  				'Student '.$uname.' has multiple sheets',2);
 8770:  	    next;
 8771:  	}
 8772:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8773:         my $user = $uname.':'.$usec;
 8774:   	($uname,$udom)=split(/:/,$uname);
 8775: 
 8776:         my $scancode;
 8777:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8778:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8779:             $scancode = $scan_record->{'scantron.CODE'};
 8780:         } else {
 8781:             $scancode = '';
 8782:         }
 8783: 
 8784:         my @mapresources = @resources;
 8785:         if ($randomorder || $randompick) {
 8786:             @mapresources =
 8787:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8788:                              \%orderedforcode);
 8789:         }
 8790:         my (%partids_by_symb,$res_error);
 8791:         foreach my $resource (@mapresources) {
 8792:             my $ressymb;
 8793:             if (ref($resource)) {
 8794:                 $ressymb = $resource->symb();
 8795:             } else {
 8796:                 $res_error = 1;
 8797:                 last;
 8798:             }
 8799:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8800:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8801:                 my $currcode;
 8802:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8803:                     $currcode = $scancode;
 8804:                 }
 8805:                 my ($analysis,$parts) =
 8806:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8807:                                               $uname,$udom,undef,$bubbles_per_row,
 8808:                                               $currcode);
 8809:                 $partids_by_symb{$ressymb} = $parts;
 8810:             } else {
 8811:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8812:             }
 8813:         }
 8814: 
 8815:         if ($res_error) {
 8816:             &scantron_add_delay(\@delayqueue,$line,
 8817:                                 'An error occurred while grading student '.$uname,2);
 8818:             next;
 8819:         }
 8820: 
 8821: 	&Apache::lonxml::clear_problem_counter();
 8822:   	&Apache::lonnet::appenv($scan_record);
 8823: 
 8824: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8825: 	    &scantron_putfile($scanlines,$scan_data);
 8826: 	}
 8827: 	
 8828:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8829:                                    \@mapresources,\%partids_by_symb,
 8830:                                    $bubbles_per_row,$randomorder,$randompick,
 8831:                                    \%respnumlookup,\%startline) 
 8832:             eq 'ssi_error') {
 8833:             $ssi_error = 0; # So end of handler error message does not trigger.
 8834:             $r->print("</form>");
 8835:             &ssi_print_error($r);
 8836:             $r->print(&show_grading_menu_form($symb));
 8837:             &Apache::lonnet::remove_lock($lock);
 8838:             return '';      # Why return ''?  Beats me.
 8839:         }
 8840: 
 8841:         if (($scancode) && ($randomorder || $randompick)) {
 8842:             my $parmresult =
 8843:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8844:                                                        '0_examcode',2,$scancode,
 8845:                                                        'string_examcode',$uname,
 8846:                                                        $udom);
 8847:         }
 8848: 	$completedstudents{$uname}={'line'=>$line};
 8849:         if ($env{'form.verifyrecord'}) {
 8850:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8851:             if ($randompick) {
 8852:                 if ($total) {
 8853:                     $lastpos = $total*$scantron_config{'Qlength'};
 8854:                 }
 8855:             }
 8856: 
 8857:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8858:             chomp($studentdata);
 8859:             $studentdata =~ s/\r$//;
 8860:             my $studentrecord = '';
 8861:             my $counter = -1;
 8862:             foreach my $resource (@mapresources) {
 8863:                 my $ressymb = $resource->symb();
 8864:                 ($counter,my $recording) =
 8865:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8866:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8867:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8868:                                              $randompick,\%respnumlookup,\%startline);
 8869:                 $studentrecord .= $recording;
 8870:             }
 8871:             if ($studentrecord ne $studentdata) {
 8872:                 &Apache::lonxml::clear_problem_counter();
 8873:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8874:                                            \@mapresources,\%partids_by_symb,
 8875:                                            $bubbles_per_row,$randomorder,$randompick,
 8876:                                            \%respnumlookup,\%startline)
 8877:                     eq 'ssi_error') {
 8878:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8879:                     $r->print("</form>");
 8880:                     &ssi_print_error($r);
 8881:                     $r->print(&show_grading_menu_form($symb));
 8882:                     &Apache::lonnet::remove_lock($lock);
 8883:                     delete($completedstudents{$uname});
 8884:                     return '';
 8885:                 }
 8886:                 $counter = -1;
 8887:                 $studentrecord = '';
 8888:                 foreach my $resource (@mapresources) {
 8889:                     my $ressymb = $resource->symb();
 8890:                     ($counter,my $recording) =
 8891:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8892:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8893:                                                  \%scantron_config,\%lettdig,$numletts,
 8894:                                                  $randomorder,$randompick,\%respnumlookup,
 8895:                                                  \%startline);
 8896:                     $studentrecord .= $recording;
 8897:                 }
 8898:                 if ($studentrecord ne $studentdata) {
 8899:                     $r->print('<p><span class="LC_warning">');
 8900:                     if ($scancode eq '') {
 8901:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8902:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8903:                     } else {
 8904:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8905:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8906:                     }
 8907:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8908:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8909:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8910:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8911:                               &Apache::loncommon::start_data_table_row().
 8912:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8913:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8914:                               &Apache::loncommon::end_data_table_row().
 8915:                               &Apache::loncommon::start_data_table_row().
 8916:                               '<td>'.&mt('Stored submissions').'</td>'.
 8917:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8918:                               &Apache::loncommon::end_data_table_row().
 8919:                               &Apache::loncommon::end_data_table().'</p>');
 8920:                 } else {
 8921:                     $r->print('<br /><span class="LC_warning">'.
 8922:                              &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 />'.
 8923:                              &mt("As a consequence, this user's submission history records two tries.").
 8924:                                  '</span><br />');
 8925:                 }
 8926:             }
 8927:         }
 8928:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8929:     } continue {
 8930: 	&Apache::lonxml::clear_problem_counter();
 8931: 	&Apache::lonnet::delenv('scantron.');
 8932:     }
 8933:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8934:     &Apache::lonnet::remove_lock($lock);
 8935: #    my $lasttime = &Time::HiRes::time()-$start;
 8936: #    $r->print("<p>took $lasttime</p>");
 8937: 
 8938:     $r->print("</form>");
 8939:     $r->print(&show_grading_menu_form($symb));
 8940:     return '';
 8941: }
 8942: 
 8943: sub graders_resources_pass {
 8944:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8945:         $bubbles_per_row) = @_;
 8946:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8947:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8948:         foreach my $resource (@{$resources}) {
 8949:             my $ressymb = $resource->symb();
 8950:             my ($analysis,$parts) =
 8951:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8952:                                           $env{'user.name'},$env{'user.domain'},
 8953:                                           1,$bubbles_per_row);
 8954:             $grader_partids_by_symb->{$ressymb} = $parts;
 8955:             if (ref($analysis) eq 'HASH') {
 8956:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8957:                     $grader_randomlists_by_symb->{$ressymb} =
 8958:                         $analysis->{'parts_withrandomlist'};
 8959:                 }
 8960:             }
 8961:         }
 8962:     }
 8963:     return;
 8964: }
 8965: 
 8966: =pod
 8967: 
 8968: =item users_order
 8969: 
 8970:   Returns array of resources in current map, ordered based on either CODE,
 8971:   if this is a CODEd exam, or based on student's identity if this is a
 8972:   "NAMEd" exam.
 8973: 
 8974:   Should be used when randomorder and/or randompick applied when the 
 8975:   corresponding exam was printed, prior to students completing bubblesheets 
 8976:   for the version of the exam the student received.
 8977: 
 8978: =cut
 8979: 
 8980: sub users_order  {
 8981:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 8982:     my @mapresources;
 8983:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 8984:         return @mapresources;
 8985:     }
 8986:     if ($scancode) {
 8987:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 8988:             @mapresources = @{$orderedforcode->{$scancode}};
 8989:         } else {
 8990:             $env{'form.CODE'} = $scancode;
 8991:             my $actual_seq =
 8992:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 8993:                                                                $master_seq,
 8994:                                                                $user,$scancode,1);
 8995:             if (ref($actual_seq) eq 'ARRAY') {
 8996:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 8997:                 if (ref($orderedforcode) eq 'HASH') {
 8998:                     if (@mapresources > 0) {
 8999:                         $orderedforcode->{$scancode} = \@mapresources;
 9000:                     }
 9001:                 }
 9002:             }
 9003:             delete($env{'form.CODE'});
 9004:         }
 9005:     } else {
 9006:         my $actual_seq =
 9007:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9008:                                                            $master_seq,
 9009:                                                            $user,undef,1);
 9010:         if (ref($actual_seq) eq 'ARRAY') {
 9011:             @mapresources =
 9012:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9013:         }
 9014:     }
 9015:     return @mapresources;
 9016: }
 9017: 
 9018: sub grade_student_bubbles {
 9019:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9020:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9021:     my $uselookup = 0;
 9022:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9023:         (ref($startline) eq 'HASH')) {
 9024:         $uselookup = 1;
 9025:     }
 9026: 
 9027:     if (ref($resources) eq 'ARRAY') {
 9028:         my $count = 0;
 9029:         foreach my $resource (@{$resources}) {
 9030:             my $ressymb = $resource->symb();
 9031:             my %form = ('submitted'      => 'scantron',
 9032:                         'grade_target'   => 'grade',
 9033:                         'grade_username' => $uname,
 9034:                         'grade_domain'   => $udom,
 9035:                         'grade_courseid' => $env{'request.course.id'},
 9036:                         'grade_symb'     => $ressymb,
 9037:                         'CODE'           => $scancode
 9038:                        );
 9039:             if ($bubbles_per_row ne '') {
 9040:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9041:             }
 9042:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9043:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9044:             }
 9045:             if (ref($parts) eq 'HASH') {
 9046:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9047:                     foreach my $part (@{$parts->{$ressymb}}) {
 9048:                         if ($uselookup) {
 9049:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9050:                         } else {
 9051:                             $form{'scantron_questnum_start.'.$part} =
 9052:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9053:                         }
 9054:                         $count++;
 9055:                     }
 9056:                 }
 9057:             }
 9058:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9059:             return 'ssi_error' if ($ssi_error);
 9060:             last if (&Apache::loncommon::connection_aborted($r));
 9061:         }
 9062:     }
 9063:     return;
 9064: }
 9065: 
 9066: sub scantron_upload_scantron_data {
 9067:     my ($r)=@_;
 9068:     my $dom = $env{'request.role.domain'};
 9069:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9070:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9071:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9072: 							  'domainid',
 9073: 							  'coursename',$dom);
 9074:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9075:                        ('&nbsp'x2).&mt('(shows course personnel)');
 9076:     my ($symb) = &get_symb($r,1);
 9077:     my $default_form_data=&defaultFormData($symb);
 9078:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9079:     &js_escape(\$nofile_alert);
 9080:     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.");
 9081:     &js_escape(\$nocourseid_alert);
 9082:     $r->print('
 9083: <script type="text/javascript" language="javascript">
 9084:     function checkUpload(formname) {
 9085: 	if (formname.upfile.value == "") {
 9086: 	    alert("'.$nofile_alert.'");
 9087: 	    return false;
 9088: 	}
 9089:         if (formname.courseid.value == "") {
 9090:             alert("'.$nocourseid_alert.'");
 9091:             return false;
 9092:         }
 9093: 	formname.submit();
 9094:     }
 9095: 
 9096:     function ToSyllabus() {
 9097:         var cdom = '."'$dom'".';
 9098:         var cnum = document.rules.courseid.value;
 9099:         if (cdom == "" || cdom == null) {
 9100:             return;
 9101:         }
 9102:         if (cnum == "" || cnum == null) {
 9103:            return;
 9104:         }
 9105:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9106:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9107:         return;
 9108:     }
 9109: 
 9110: </script>
 9111: 
 9112: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9113: 
 9114: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9115: '.$default_form_data.
 9116:   &Apache::lonhtmlcommon::start_pick_box().
 9117:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9118:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9119:   &Apache::lonhtmlcommon::row_closure().
 9120:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9121:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9122:   &Apache::lonhtmlcommon::row_closure().
 9123:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9124:   '<input name="domainid" type="hidden" />'.$domdesc.
 9125:   &Apache::lonhtmlcommon::row_closure().
 9126:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9127:   '<input type="file" name="upfile" size="50" />'.
 9128:   &Apache::lonhtmlcommon::row_closure(1).
 9129:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9130: 
 9131: <input name="command" value="scantronupload_save" type="hidden" />
 9132: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9133: </form>
 9134: ');
 9135:     return '';
 9136: }
 9137: 
 9138: 
 9139: sub scantron_upload_scantron_data_save {
 9140:     my($r)=@_;
 9141:     my ($symb)=&get_symb($r,1);
 9142:     my $doanotherupload=
 9143: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9144: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9145: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9146: 	'</form>'."\n";
 9147:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9148: 	!&Apache::lonnet::allowed('usc',
 9149: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9150: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9151: 	if ($symb) {
 9152: 	    $r->print(&show_grading_menu_form($symb));
 9153: 	} else {
 9154: 	    $r->print($doanotherupload);
 9155: 	}
 9156: 	return '';
 9157:     }
 9158:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9159:     my $uploadedfile;
 9160:     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
 9161:     if (length($env{'form.upfile'}) < 2) {
 9162:         $r->print(
 9163:             &Apache::lonhtmlcommon::confirm_success(
 9164:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9165:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9166:     } else {
 9167:         my $result = 
 9168:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9169:                                             $env{'form.courseid'},$env{'form.domainid'});
 9170: 	if ($result =~ m{^/uploaded/}) {
 9171:             $r->print(
 9172:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9173:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9174:                         (length($env{'form.upfile'})-1),
 9175:                         '<span class="LC_filename">'.$result.'</span>'));
 9176:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9177:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9178:                                                        $env{'form.courseid'},$uploadedfile));
 9179: 	} else {
 9180:             $r->print(
 9181:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9182:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9183:                           $result,
 9184: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9185: 	}
 9186:     }
 9187:     if ($symb) {
 9188: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 9189:     } else {
 9190: 	$r->print($doanotherupload);
 9191:     }
 9192:     return '';
 9193: }
 9194: 
 9195: sub validate_uploaded_scantron_file {
 9196:     my ($cdom,$cname,$fname) = @_;
 9197:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9198:     my @lines;
 9199:     if ($scanlines ne '-1') {
 9200:         @lines=split("\n",$scanlines,-1);
 9201:     }
 9202:     my $output;
 9203:     if (@lines) {
 9204:         my (%counts,$max_match_format);
 9205:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9206:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9207:         my %idmap = &username_to_idmap($classlist);
 9208:         foreach my $key (keys(%idmap)) {
 9209:             my $lckey = lc($key);
 9210:             $idmap{$lckey} = $idmap{$key};
 9211:         }
 9212:         my %unique_formats;
 9213:         my @formatlines = &get_scantronformat_file();
 9214:         foreach my $line (@formatlines) {
 9215:             chomp($line);
 9216:             my @config = split(/:/,$line);
 9217:             my $idstart = $config[5];
 9218:             my $idlength = $config[6];
 9219:             if (($idstart ne '') && ($idlength > 0)) {
 9220:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9221:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9222:                 } else {
 9223:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9224:                 }
 9225:             }
 9226:         }
 9227:         foreach my $key (keys(%unique_formats)) {
 9228:             my ($idstart,$idlength) = split(':',$key);
 9229:             %{$counts{$key}} = (
 9230:                                'found'   => 0,
 9231:                                'total'   => 0,
 9232:                               );
 9233:             foreach my $line (@lines) {
 9234:                 next if ($line =~ /^#/);
 9235:                 next if ($line =~ /^[\s\cz]*$/);
 9236:                 my $id = substr($line,$idstart-1,$idlength);
 9237:                 $id = lc($id);
 9238:                 if (exists($idmap{$id})) {
 9239:                     $counts{$key}{'found'} ++;
 9240:                 }
 9241:                 $counts{$key}{'total'} ++;
 9242:             }
 9243:             if ($counts{$key}{'total'}) {
 9244:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9245:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9246:                     $max_match_pct = $percent_match;
 9247:                     $max_match_format = $key;
 9248:                     $found_match_count = $counts{$key}{'found'};
 9249:                     $max_match_count = $counts{$key}{'total'};
 9250:                 }
 9251:             }
 9252:         }
 9253:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9254:             my $format_descs;
 9255:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9256:             for (my $i=0; $i<$numwithformat; $i++) {
 9257:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9258:                 if ($i<$numwithformat-2) {
 9259:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9260:                 } elsif ($i==$numwithformat-2) {
 9261:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9262:                 } elsif ($i==$numwithformat-1) {
 9263:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9264:                 }
 9265:             }
 9266:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9267:             $output .= '<br />';
 9268:             if ($found_match_count == $max_match_count) {
 9269:                 # 100% matching entries
 9270:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9271:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9272:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9273:                 &mt('Comparison of student IDs in the uploaded file with'.
 9274:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9275:                     ' in the file (for the format defined for [_3]).',
 9276:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9277:             } else {
 9278:                 # Not all entries matching? -> Show warning and additional info
 9279:                 $output .=
 9280:                     &Apache::lonhtmlcommon::confirm_success(
 9281:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9282:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9283:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9284:                     &mt('Comparison of student IDs in the uploaded file with'.
 9285:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9286:                         ' in the file (for the format defined for [_3]).',
 9287:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9288:                     '<p class="LC_info">'.
 9289:                     &mt('A low percentage of matches results from one of the following:').
 9290:                     '</p><ul>'.
 9291:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9292:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9293:                                '<i>'.$cdom.'</i>').'</li>'.
 9294:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9295:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9296:                     '</ul>';
 9297:             }
 9298:         }
 9299:     } else {
 9300:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9301:     }
 9302:     return $output;
 9303: }
 9304: 
 9305: sub valid_file {
 9306:     my ($requested_file)=@_;
 9307:     foreach my $filename (sort(&scantron_filenames())) {
 9308: 	if ($requested_file eq $filename) { return 1; }
 9309:     }
 9310:     return 0;
 9311: }
 9312: 
 9313: sub scantron_download_scantron_data {
 9314:     my ($r)=@_;
 9315:     my ($symb) = &get_symb($r,1);
 9316:     my $default_form_data=&defaultFormData($symb);
 9317:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9318:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9319:     my $file=$env{'form.scantron_selectfile'};
 9320:     if (! &valid_file($file)) {
 9321: 	$r->print('
 9322: 	<p>
 9323: 	    '.&mt('The requested filename was invalid.').'
 9324:         </p>
 9325: ');
 9326: 	$r->print(&show_grading_menu_form($symb));
 9327: 	return;
 9328:     }
 9329:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9330:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9331:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9332:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9333:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9334:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9335:     $r->print('
 9336:     <p>
 9337: 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
 9338: 	      '<a href="'.$orig.'">','</a>').'
 9339:     </p>
 9340:     <p>
 9341: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9342: 	      '<a href="'.$corrected.'">','</a>').'
 9343:     </p>
 9344:     <p>
 9345: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9346: 	      '<a href="'.$skipped.'">','</a>').'
 9347:     </p>
 9348: ');
 9349:     $r->print(&show_grading_menu_form($symb));
 9350:     return '';
 9351: }
 9352: 
 9353: sub checkscantron_results {
 9354:     my ($r) = @_;
 9355:     my ($symb)=&get_symb($r);
 9356:     if (!$symb) {return '';}
 9357:     my $grading_menu_button=&show_grading_menu_form($symb);
 9358:     my $cid = $env{'request.course.id'};
 9359:     my %lettdig = &letter_to_digits();
 9360:     my $numletts = scalar(keys(%lettdig));
 9361:     my $cnum = $env{'course.'.$cid.'.num'};
 9362:     my $cdom = $env{'course.'.$cid.'.domain'};
 9363:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9364:     my %record;
 9365:     my %scantron_config =
 9366:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9367:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9368:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9369:     my $classlist=&Apache::loncoursedata::get_classlist();
 9370:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9371:     my $navmap=Apache::lonnavmaps::navmap->new();
 9372:     unless (ref($navmap)) {
 9373:         $r->print(&navmap_errormsg());
 9374:         return '';
 9375:     }
 9376:     my $map=$navmap->getResourceByUrl($sequence);
 9377:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9378:         %grader_randomlists_by_symb,%orderedforcode);
 9379:     if (ref($map)) {
 9380:         $randomorder=$map->randomorder();
 9381:         $randompick=$map->randompick();
 9382:     }
 9383:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9384:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9385:     if ($nav_error) {
 9386:         $r->print(&navmap_errormsg());
 9387:         return '';
 9388:     }
 9389:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9390:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9391:     my ($uname,$udom);
 9392:     my (%scandata,%lastname,%bylast);
 9393:     $r->print('
 9394: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9395: 
 9396:     my @delayqueue;
 9397:     my %completedstudents;
 9398: 
 9399:     my $count=&get_todo_count($scanlines,$scan_data);
 9400:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9401:     my ($username,$domain,$started);
 9402:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9403:     if ($nav_error) {
 9404:         $r->print(&navmap_errormsg());
 9405:         return '';
 9406:     }
 9407: 
 9408:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 9409:                                           'Processing first student');
 9410:     my $start=&Time::HiRes::time();
 9411:     my $i=-1;
 9412: 
 9413:     while ($i<$scanlines->{'count'}) {
 9414:         ($username,$domain,$uname)=('','','');
 9415:         $i++;
 9416:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9417:         if ($line=~/^[\s\cz]*$/) { next; }
 9418:         if ($started) {
 9419:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 9420:                                                      'last student');
 9421:         }
 9422:         $started=1;
 9423:         my $scan_record=
 9424:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9425:                                                      $scan_data);
 9426:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9427:                                               \%idmap,$i)) {
 9428:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9429:                                 'Unable to find a student that matches',1);
 9430:             next;
 9431:         }
 9432:         if (exists $completedstudents{$uname}) {
 9433:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9434:                                 'Student '.$uname.' has multiple sheets',2);
 9435:             next;
 9436:         }
 9437:         my $pid = $scan_record->{'scantron.ID'};
 9438:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9439:         push(@{$bylast{$lastname{$pid}}},$pid);
 9440:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9441:         my $user = $uname.':'.$usec;
 9442:         ($username,$domain)=split(/:/,$uname);
 9443: 
 9444:         my $scancode;
 9445:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9446:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9447:             $scancode = $scan_record->{'scantron.CODE'};
 9448:         } else {
 9449:             $scancode = '';
 9450:         }
 9451: 
 9452:         my @mapresources = @resources;
 9453:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9454:         my %respnumlookup=();
 9455:         my %startline=();
 9456:         if ($randomorder || $randompick) {
 9457:             @mapresources =
 9458:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9459:                              \%orderedforcode);
 9460:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9461:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9462:                                              \%grader_partids_by_symb,\%orderedforcode,
 9463:                                              \%respnumlookup,\%startline);
 9464:             if ($randompick && $total) {
 9465:                 $lastpos = $total*$scantron_config{'Qlength'};
 9466:             }
 9467:         }
 9468:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9469:         chomp($scandata{$pid});
 9470:         $scandata{$pid} =~ s/\r$//;
 9471: 
 9472:         my $counter = -1;
 9473:         foreach my $resource (@mapresources) {
 9474:             my $parts;
 9475:             my $ressymb = $resource->symb();
 9476:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9477:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9478:                 my $currcode;
 9479:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9480:                     $currcode = $scancode;
 9481:                 }
 9482:                 (my $analysis,$parts) =
 9483:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9484:                                               $username,$domain,undef,
 9485:                                               $bubbles_per_row,$currcode);
 9486:             } else {
 9487:                 $parts = $grader_partids_by_symb{$ressymb};
 9488:             }
 9489:             ($counter,my $recording) =
 9490:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9491:                                          $scandata{$pid},$parts,
 9492:                                          \%scantron_config,\%lettdig,$numletts,
 9493:                                          $randomorder,$randompick,
 9494:                                          \%respnumlookup,\%startline);
 9495:             $record{$pid} .= $recording;
 9496:         }
 9497:     }
 9498:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9499:     $r->print('<br />');
 9500:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9501:     $passed = 0;
 9502:     $failed = 0;
 9503:     $numstudents = 0;
 9504:     foreach my $last (sort(keys(%bylast))) {
 9505:         if (ref($bylast{$last}) eq 'ARRAY') {
 9506:             foreach my $pid (sort(@{$bylast{$last}})) {
 9507:                 my $showscandata = $scandata{$pid};
 9508:                 my $showrecord = $record{$pid};
 9509:                 $showscandata =~ s/\s/&nbsp;/g;
 9510:                 $showrecord =~ s/\s/&nbsp;/g;
 9511:                 if ($scandata{$pid} eq $record{$pid}) {
 9512:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9513:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9514: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9515: '</tr>'."\n".
 9516: '<tr class="'.$css_class.'">'."\n".
 9517: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9518:                     $passed ++;
 9519:                 } else {
 9520:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9521:                     $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".
 9522: '</tr>'."\n".
 9523: '<tr class="'.$css_class.'">'."\n".
 9524: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9525: '</tr>'."\n";
 9526:                     $failed ++;
 9527:                 }
 9528:                 $numstudents ++;
 9529:             }
 9530:         }
 9531:     }
 9532:     $r->print('<p>'.
 9533:               &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).',
 9534:                   '<b>',
 9535:                   $numstudents,
 9536:                   '</b>',
 9537:                   $env{'form.scantron_maxbubble'}).
 9538:               '</p>'
 9539:     );
 9540:     $r->print('<p>'
 9541:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9542:              .'<br />'
 9543:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9544:              .'</p>');
 9545:     if ($passed) {
 9546:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9547:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9548:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9549:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9550:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9551:                  $okstudents."\n".
 9552:                  &Apache::loncommon::end_data_table().'<br />');
 9553:     }
 9554:     if ($failed) {
 9555:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9556:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9557:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9558:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9559:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9560:                  $badstudents."\n".
 9561:                  &Apache::loncommon::end_data_table()).'<br />'.
 9562:                  &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.');  
 9563:     }
 9564:     $r->print('</form><br />'.$grading_menu_button);
 9565:     return;
 9566: }
 9567: 
 9568: sub verify_scantron_grading {
 9569:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9570:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9571:         $respnumlookup,$startline) = @_;
 9572:     my ($record,%expected,%startpos);
 9573:     return ($counter,$record) if (!ref($resource));
 9574:     return ($counter,$record) if (!$resource->is_problem());
 9575:     my $symb = $resource->symb();
 9576:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9577:     foreach my $part_id (@{$partids}) {
 9578:         $counter ++;
 9579:         $expected{$part_id} = 0;
 9580:         my $respnum = $counter;
 9581:         if ($randomorder || $randompick) {
 9582:             $respnum = $respnumlookup->{$counter};
 9583:             $startpos{$part_id} = $startline->{$counter} + 1;
 9584:         } else {
 9585:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9586:         }
 9587:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9588:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9589:             foreach my $item (@sub_lines) {
 9590:                 $expected{$part_id} += $item;
 9591:             }
 9592:         } else {
 9593:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9594:         }
 9595:     }
 9596:     if ($symb) {
 9597:         my %recorded;
 9598:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9599:         if ($returnhash{'version'}) {
 9600:             my %lasthash=();
 9601:             my $version;
 9602:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9603:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9604:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9605:                 }
 9606:             }
 9607:             foreach my $key (keys(%lasthash)) {
 9608:                 if ($key =~ /\.scantron$/) {
 9609:                     my $value = &unescape($lasthash{$key});
 9610:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9611:                     if ($value eq '') {
 9612:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9613:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9614:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9615:                             }
 9616:                         }
 9617:                     } else {
 9618:                         my @tocheck;
 9619:                         my @items = split(//,$value);
 9620:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9621:                             ($scantron_config->{'Qon'} eq 'number')) {
 9622:                             if (@items < $expected{$part_id}) {
 9623:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9624:                                 my @singles = split(//,$fragment);
 9625:                                 foreach my $pos (@singles) {
 9626:                                     if ($pos eq ' ') {
 9627:                                         push(@tocheck,$pos);
 9628:                                     } else {
 9629:                                         my $next = shift(@items);
 9630:                                         push(@tocheck,$next);
 9631:                                     }
 9632:                                 }
 9633:                             } else {
 9634:                                 @tocheck = @items;
 9635:                             }
 9636:                             foreach my $letter (@tocheck) {
 9637:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9638:                                     if ($letter !~ /^[A-J]$/) {
 9639:                                         $letter = $scantron_config->{'Qoff'};
 9640:                                     }
 9641:                                     $recorded{$part_id} .= $letter;
 9642:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9643:                                     my $digit;
 9644:                                     if ($letter !~ /^[A-J]$/) {
 9645:                                         $digit = $scantron_config->{'Qoff'};
 9646:                                     } else {
 9647:                                         $digit = $lettdig->{$letter};
 9648:                                     }
 9649:                                     $recorded{$part_id} .= $digit;
 9650:                                 }
 9651:                             }
 9652:                         } else {
 9653:                             @tocheck = @items;
 9654:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9655:                                 my $curr_sub = shift(@tocheck);
 9656:                                 my $digit;
 9657:                                 if ($curr_sub =~ /^[A-J]$/) {
 9658:                                     $digit = $lettdig->{$curr_sub}-1;
 9659:                                 }
 9660:                                 if ($curr_sub eq 'J') {
 9661:                                     $digit += scalar($numletts);
 9662:                                 }
 9663:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9664:                                     if ($j == $digit) {
 9665:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9666:                                     } else {
 9667:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9668:                                     }
 9669:                                 }
 9670:                             }
 9671:                         }
 9672:                     }
 9673:                 }
 9674:             }
 9675:         }
 9676:         foreach my $part_id (@{$partids}) {
 9677:             if ($recorded{$part_id} eq '') {
 9678:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9679:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9680:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9681:                     }
 9682:                 }
 9683:             }
 9684:             $record .= $recorded{$part_id};
 9685:         }
 9686:     }
 9687:     return ($counter,$record);
 9688: }
 9689: 
 9690: sub letter_to_digits {
 9691:     my %lettdig = (
 9692:                     A => 1,
 9693:                     B => 2,
 9694:                     C => 3,
 9695:                     D => 4,
 9696:                     E => 5,
 9697:                     F => 6,
 9698:                     G => 7,
 9699:                     H => 8,
 9700:                     I => 9,
 9701:                     J => 0,
 9702:                   );
 9703:     return %lettdig;
 9704: }
 9705: 
 9706: 
 9707: #-------- end of section for handling grading scantron forms -------
 9708: #
 9709: #-------------------------------------------------------------------
 9710: 
 9711: #-------------------------- Menu interface -------------------------
 9712: #
 9713: #--- Show a Grading Menu button - Calls the next routine ---
 9714: sub show_grading_menu_form {
 9715:     my ($symb)=@_;
 9716:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 9717: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9718: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 9719: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 9720: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 9721: 	'</form>'."\n";
 9722:     return $result;
 9723: }
 9724: 
 9725: # -- Retrieve choices for grading form
 9726: sub savedState {
 9727:     my %savedState = ();
 9728:     if ($env{'form.saveState'}) {
 9729: 	foreach (split(/:/,$env{'form.saveState'})) {
 9730: 	    my ($key,$value) = split(/=/,$_,2);
 9731: 	    $savedState{$key} = $value;
 9732: 	}
 9733:     }
 9734:     return \%savedState;
 9735: }
 9736: 
 9737: #--- Href with symb and command ---
 9738: 
 9739: sub href_symb_cmd {
 9740:     my ($symb,$cmd)=@_;
 9741:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9742: }
 9743: 
 9744: sub grading_menu {
 9745:     my ($request) = @_;
 9746:     my ($symb)=&get_symb($request);
 9747:     if (!$symb) {return '';}
 9748:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9749:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9750: 
 9751:     $request->print($table);
 9752:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9753:                   'handgrade'=>$hdgrade,
 9754:                   'probTitle'=>$probTitle,
 9755:                   'command'=>'submit_options',
 9756:                   'saveState'=>"",
 9757:                   'gradingMenu'=>1,
 9758:                   'showgrading'=>"yes");
 9759:     
 9760:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9761:     
 9762:     $fields{'command'} = 'csvform';
 9763:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9764:     
 9765:     $fields{'command'} = 'processclicker';
 9766:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9767:     
 9768:     $fields{'command'} = 'scantron_selectphase';
 9769:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9770:     
 9771:     my @menu = ({	categorytitle=>'Course Grading',
 9772:             items =>[
 9773:                         {	linktext => 'Manual Grading/View Submissions',
 9774:                     		url => $url1,
 9775:                     		permission => 'F',
 9776:                     		icon => 'edit-find-replace.png',
 9777:                     		linktitle => 'Start the process of hand grading submissions.'
 9778:                         },
 9779:                 	    {	linktext => 'Upload Scores',
 9780:                     		url => $url2,
 9781:                     		permission => 'F',
 9782:                     		icon => 'uploadscores.png',
 9783:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9784:                 	    },
 9785:                 	    {	linktext => 'Process Clicker',
 9786:                     		url => $url3,
 9787:                     		permission => 'F',
 9788:                     		icon => 'addClickerInfoFile.png',
 9789:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9790:                 	    },
 9791:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9792:                     		url => $url4,
 9793:                     		permission => 'F',
 9794:                     		icon => 'stat.png',
 9795:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9796:                 	    }
 9797:                     ]
 9798:             });
 9799: 
 9800:     #$fields{'command'} = 'verify';
 9801:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9802:     #
 9803:     # Create the menu
 9804:     my $Str;
 9805:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 9806:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9807:     $Str .= '<input type="hidden" name="command" value="" />'.
 9808:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9809: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9810: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9811: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9812: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9813: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9814: 
 9815:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 9816:     #$menudata->{'jscript'}
 9817:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 9818:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 9819:         ' /> '.
 9820:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 9821:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 9822: 
 9823:     $Str .="</form>\n";
 9824:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 9825:     $request->print(<<GRADINGMENUJS);
 9826: <script type="text/javascript" language="javascript">
 9827:     function checkChoice(formname,val,cmdx) {
 9828: 	if (val <= 2) {
 9829: 	    var cmd = radioSelection(formname.radioChoice);
 9830: 	    var cmdsave = cmd;
 9831: 	} else {
 9832: 	    cmd = cmdx;
 9833: 	    cmdsave = 'submission';
 9834: 	}
 9835: 	formname.command.value = cmd;
 9836: 	if (val < 5) formname.submit();
 9837: 	if (val == 5) {
 9838: 	    if (!checkReceiptNo(formname,'notOK')) { 
 9839: 	        return false;
 9840: 	    } else {
 9841: 	        formname.submit();
 9842: 	    }
 9843: 	}
 9844:     }
 9845: 
 9846:     function checkReceiptNo(formname,nospace) {
 9847: 	var receiptNo = formname.receipt.value;
 9848: 	var checkOpt = false;
 9849: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9850: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9851: 	if (checkOpt) {
 9852: 	    alert("$receiptalert");
 9853: 	    formname.receipt.value = "";
 9854: 	    formname.receipt.focus();
 9855: 	    return false;
 9856: 	}
 9857: 	return true;
 9858:     }
 9859: </script>
 9860: GRADINGMENUJS
 9861:     &commonJSfunctions($request);
 9862:     return $Str;    
 9863: }
 9864: 
 9865: 
 9866: #--- Displays the submissions first page -------
 9867: sub submit_options {
 9868:     my ($request) = @_;
 9869:     my ($symb)=&get_symb($request);
 9870:     if (!$symb) {return '';}
 9871:     my $probTitle = &Apache::lonnet::gettitle($symb);
 9872: 
 9873:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 9874:     $request->print(<<GRADINGMENUJS);
 9875: <script type="text/javascript" language="javascript">
 9876:     function checkChoice(formname,val,cmdx) {
 9877: 	if (val <= 2) {
 9878: 	    var cmd = radioSelection(formname.radioChoice);
 9879: 	    var cmdsave = cmd;
 9880: 	} else {
 9881: 	    cmd = cmdx;
 9882: 	    cmdsave = 'submission';
 9883: 	}
 9884: 	formname.command.value = cmd;
 9885: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 9886: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 9887: 	if (val < 5) formname.submit();
 9888: 	if (val == 5) {
 9889: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 9890: 	    formname.submit();
 9891: 	}
 9892: 	if (val < 7) formname.submit();
 9893:     }
 9894: 
 9895:     function checkReceiptNo(formname,nospace) {
 9896: 	var receiptNo = formname.receipt.value;
 9897: 	var checkOpt = false;
 9898: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 9899: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 9900: 	if (checkOpt) {
 9901: 	    alert("$receiptalert");
 9902: 	    formname.receipt.value = "";
 9903: 	    formname.receipt.focus();
 9904: 	    return false;
 9905: 	}
 9906: 	return true;
 9907:     }
 9908: </script>
 9909: GRADINGMENUJS
 9910:     &commonJSfunctions($request);
 9911:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 9912:     my $result;
 9913:     my (undef,$sections) = &getclasslist('all','0');
 9914:     my $savedState = &savedState();
 9915:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 9916:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 9917:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 9918:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 9919: 
 9920:     # Preselect sections
 9921:     my $selsec="";
 9922:     if (ref($sections)) {
 9923:         foreach my $section (sort(@$sections)) {
 9924:             $selsec.='<option value="'.$section.'" '.
 9925:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 9926:         }
 9927:     }
 9928: 
 9929:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9930: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 9931: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 9932: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 9933: 	'<input type="hidden" name="command"     value="" />'."\n".
 9934: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 9935: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 9936: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 9937: 
 9938:     $result.='
 9939: <h2>
 9940:   '.&mt('Grade Current Resource').'
 9941: </h2>
 9942: <div>
 9943:   '.$table.'
 9944: </div>
 9945: 
 9946: <div class="LC_columnSection">
 9947:   
 9948:     <fieldset>
 9949:       <legend>
 9950:        '.&mt('Sections').'
 9951:       </legend>
 9952:       <select name="section" multiple="multiple" size="5">'."\n";
 9953:     $result.= $selsec;
 9954:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 9955:     $result.='
 9956:     </fieldset>
 9957:   
 9958:     <fieldset>
 9959:       <legend>
 9960:         '.&mt('Groups').'
 9961:       </legend>
 9962:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9963:     </fieldset>
 9964:   
 9965:     <fieldset>
 9966:       <legend>
 9967:         '.&mt('Access Status').'
 9968:       </legend>
 9969:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 9970:     </fieldset>
 9971:   
 9972:     <fieldset>
 9973:       <legend>
 9974:         '.&mt('Submission Status').'
 9975:       </legend>
 9976:       <select name="submitonly" size="5">
 9977: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 9978: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 9979: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 9980: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 9981:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 9982:       </select>
 9983:     </fieldset>
 9984:   
 9985: </div>
 9986: 
 9987: <br />
 9988:           <div>
 9989:             <div>
 9990:               <label>
 9991:                 <input type="radio" name="radioChoice" value="submission" '.
 9992:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 9993:              &mt('Select individual students to grade and view submissions.').'
 9994: 	      </label> 
 9995:             </div>
 9996:             <div>
 9997: 	      <label>
 9998:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 9999:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
10000:                     &mt('Grade all selected students in a grading table.').'
10001:               </label>
10002:             </div>
10003:             <div>
10004: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10005:             </div>
10006:           </div>
10007: 
10008: 
10009:         <h2>
10010:          '.&mt('Grade Complete Folder for One Student').'
10011:         </h2>
10012:         <div>
10013:             <div>
10014:               <label>
10015:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
10016: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
10017:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
10018:               </label>
10019:             </div>
10020:             <div>
10021: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
10022:             </div>
10023:         </div>
10024:   </form>';
10025:     $result .= &show_grading_menu_form($symb);
10026:     return $result;
10027: }
10028: 
10029: sub substatus_options {
10030:     return &Apache::lonlocal::texthash(
10031:                                       'yes'       => 'with submissions',
10032:                                       'queued'    => 'in grading queue',
10033:                                       'graded'    => 'with ungraded submissions',
10034:                                       'incorrect' => 'with incorrect submissions',
10035:                                       'all'       => 'with any status',
10036:                                       );
10037: }
10038: 
10039: sub reset_perm {
10040:     undef(%perm);
10041: }
10042: 
10043: sub init_perm {
10044:     &reset_perm();
10045:     foreach my $test_perm ('vgr','mgr','opa') {
10046: 
10047: 	my $scope = $env{'request.course.id'};
10048: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10049: 
10050: 	    $scope .= '/'.$env{'request.course.sec'};
10051: 	    if ( $perm{$test_perm}=
10052: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10053: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10054: 	    } else {
10055: 		delete($perm{$test_perm});
10056: 	    }
10057: 	}
10058:     }
10059: }
10060: 
10061: sub init_old_essays {
10062:     my ($symb,$apath,$adom,$aname) = @_;
10063:     if ($symb ne '') {
10064:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10065:         if (keys(%essays) > 0) {
10066:             $old_essays{$symb} = \%essays;
10067:         }
10068:     }
10069:     return;
10070: }
10071: 
10072: sub reset_old_essays {
10073:     undef(%old_essays);
10074: }
10075: 
10076: sub gather_clicker_ids {
10077:     my %clicker_ids;
10078: 
10079:     my $classlist = &Apache::loncoursedata::get_classlist();
10080: 
10081:     # Set up a couple variables.
10082:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10083:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10084:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10085: 
10086:     foreach my $student (keys(%$classlist)) {
10087:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10088:         my $username = $classlist->{$student}->[$username_idx];
10089:         my $domain   = $classlist->{$student}->[$domain_idx];
10090:         my $clickers =
10091: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10092:         foreach my $id (split(/\,/,$clickers)) {
10093:             $id=~s/^[\#0]+//;
10094:             $id=~s/[\-\:]//g;
10095:             if (exists($clicker_ids{$id})) {
10096: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10097:             } else {
10098: 		$clicker_ids{$id}=$username.':'.$domain;
10099:             }
10100:         }
10101:     }
10102:     return %clicker_ids;
10103: }
10104: 
10105: sub gather_adv_clicker_ids {
10106:     my %clicker_ids;
10107:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10108:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10109:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10110:     foreach my $element (sort(keys(%coursepersonnel))) {
10111:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10112:             my ($puname,$pudom)=split(/\:/,$person);
10113:             my $clickers =
10114: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10115:             foreach my $id (split(/\,/,$clickers)) {
10116: 		$id=~s/^[\#0]+//;
10117:                 $id=~s/[\-\:]//g;
10118: 		if (exists($clicker_ids{$id})) {
10119: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10120: 		} else {
10121: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10122: 		}
10123:             }
10124:         }
10125:     }
10126:     return %clicker_ids;
10127: }
10128: 
10129: sub clicker_grading_parameters {
10130:     return ('gradingmechanism' => 'scalar',
10131:             'upfiletype' => 'scalar',
10132:             'specificid' => 'scalar',
10133:             'pcorrect' => 'scalar',
10134:             'pincorrect' => 'scalar');
10135: }
10136: 
10137: sub process_clicker {
10138:     my ($r)=@_;
10139:     my ($symb)=&get_symb($r);
10140:     if (!$symb) {return '';}
10141:     my $result=&checkforfile_js();
10142:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10143:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10144:     $result.=$table;
10145:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10146:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10147:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
10148:         '</b></td></tr>'."\n";
10149:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10150: # Attempt to restore parameters from last session, set defaults if not present
10151:     my %Saveable_Parameters=&clicker_grading_parameters();
10152:     &Apache::loncommon::restore_course_settings('grades_clicker',
10153:                                                  \%Saveable_Parameters);
10154:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10155:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10156:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10157:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10158: 
10159:     my %checked;
10160:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10161:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10162:           $checked{$gradingmechanism}=' checked="checked"';
10163:        }
10164:     }
10165: 
10166:     my $upload=&mt("Upload File");
10167:     my $type=&mt("Type");
10168:     my $attendance=&mt("Award points just for participation");
10169:     my $personnel=&mt("Correctness determined from response by course personnel");
10170:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10171:     my $given=&mt("Correctness determined from given list of answers").' '.
10172:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10173:     my $pcorrect=&mt("Percentage points for correct solution");
10174:     my $pincorrect=&mt("Percentage points for incorrect solution");
10175:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10176:                                                    {'iclicker' => 'i>clicker',
10177:                                                     'interwrite' => 'interwrite PRS',
10178:                                                     'turning' => 'Turning Technologies'});
10179:     $symb = &Apache::lonenc::check_encrypt($symb);
10180:     $result.=<<ENDUPFORM;
10181: <script type="text/javascript">
10182: function sanitycheck() {
10183: // Accept only integer percentages
10184:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10185:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10186: // Find out grading choice
10187:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10188:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10189:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10190:       }
10191:    }
10192: // By default, new choice equals user selection
10193:    newgradingchoice=gradingchoice;
10194: // Not good to give more points for false answers than correct ones
10195:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10196:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10197:    }
10198: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10199:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10200:       document.forms.gradesupload.pcorrect.value=100;
10201:       document.forms.gradesupload.pincorrect.value=100;
10202:    }
10203: // If the values are different, cannot be attendance only
10204:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10205:        (gradingchoice=='attendance')) {
10206:        newgradingchoice='personnel';
10207:    }
10208: // Change grading choice to new one
10209:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10210:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10211:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10212:       } else {
10213:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10214:       }
10215:    }
10216: // Remember the old state
10217:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10218: }
10219: </script>
10220: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10221: <input type="hidden" name="symb" value="$symb" />
10222: <input type="hidden" name="command" value="processclickerfile" />
10223: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10224: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10225: <input type="file" name="upfile" size="50" />
10226: <br /><label>$type: $selectform</label>
10227: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10228: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10229: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10230: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10231: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10232: <br />&nbsp;&nbsp;&nbsp;
10233: <input type="text" name="givenanswer" size="50" />
10234: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10235: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10236: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10237: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10238: </form>
10239: ENDUPFORM
10240:     $result.='</td></tr></table>'."\n".
10241:              '</td></tr></table><br /><br />'."\n";
10242:     $result.=&show_grading_menu_form($symb);
10243:     return $result;
10244: }
10245: 
10246: sub process_clicker_file {
10247:     my ($r)=@_;
10248:     my ($symb)=&get_symb($r);
10249:     if (!$symb) {return '';}
10250: 
10251:     my %Saveable_Parameters=&clicker_grading_parameters();
10252:     &Apache::loncommon::store_course_settings('grades_clicker',
10253:                                               \%Saveable_Parameters);
10254: 
10255:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10256:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10257: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10258: 	return $result.&show_grading_menu_form($symb);
10259:     }
10260:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10261:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10262:         return $result.&show_grading_menu_form($symb);
10263:     }
10264:     my $foundgiven=0;
10265:     if ($env{'form.gradingmechanism'} eq 'given') {
10266:         $env{'form.givenanswer'}=~s/^\s*//gs;
10267:         $env{'form.givenanswer'}=~s/\s*$//gs;
10268:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10269:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10270:         my @answers=split(/\,/,$env{'form.givenanswer'});
10271:         $foundgiven=$#answers+1;
10272:     }
10273:     my %clicker_ids=&gather_clicker_ids();
10274:     my %correct_ids;
10275:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10276: 	%correct_ids=&gather_adv_clicker_ids();
10277:     }
10278:     if ($env{'form.gradingmechanism'} eq 'specific') {
10279: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10280: 	   $correct_id=~tr/a-z/A-Z/;
10281: 	   $correct_id=~s/\s//gs;
10282: 	   $correct_id=~s/^[\#0]+//;
10283:            $correct_id=~s/[\-\:]//g;
10284:            if ($correct_id) {
10285: 	      $correct_ids{$correct_id}='specified';
10286:            }
10287:         }
10288:     }
10289:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10290: 	$result.=&mt('Score based on attendance only');
10291:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10292:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10293:     } else {
10294: 	my $number=0;
10295: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10296: 	foreach my $id (sort(keys(%correct_ids))) {
10297: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10298: 	    if ($correct_ids{$id} eq 'specified') {
10299: 		$result.=&mt('specified');
10300: 	    } else {
10301: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10302: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10303: 	    }
10304: 	    $number++;
10305: 	}
10306:         $result.="</p>\n";
10307:         if ($number==0) {
10308:             $result .=
10309:                  &Apache::lonhtmlcommon::confirm_success(
10310:                      &mt('No IDs found to determine correct answer'),1);
10311:             return $result,.&show_grading_menu_form($symb);
10312:         }
10313:     }
10314:     if (length($env{'form.upfile'}) < 2) {
10315:         $result .=
10316:             &Apache::lonhtmlcommon::confirm_success(
10317:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10318:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10319:         return $result.&show_grading_menu_form($symb);
10320:     }
10321: 
10322: # Were able to get all the info needed, now analyze the file
10323: 
10324:     $result.=&Apache::loncommon::studentbrowser_javascript();
10325:     $symb = &Apache::lonenc::check_encrypt($symb);
10326:     my $heading=&mt('Scanning clicker file');
10327:     $result.=(<<ENDHEADER);
10328: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10329: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10330: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10331: <form method="post" action="/adm/grades" name="clickeranalysis">
10332: <input type="hidden" name="symb" value="$symb" />
10333: <input type="hidden" name="command" value="assignclickergrades" />
10334: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10335: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
10336: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10337: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10338: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10339: ENDHEADER
10340:     if ($env{'form.gradingmechanism'} eq 'given') {
10341:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10342:     } 
10343:     my %responses;
10344:     my @questiontitles;
10345:     my $errormsg='';
10346:     my $number=0;
10347:     if ($env{'form.upfiletype'} eq 'iclicker') {
10348: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10349:     }
10350:     if ($env{'form.upfiletype'} eq 'interwrite') {
10351:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10352:     }
10353:     if ($env{'form.upfiletype'} eq 'turning') {
10354:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10355:     }
10356:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10357:              '<input type="hidden" name="number" value="'.$number.'" />'.
10358:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10359:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10360:              '<br />';
10361:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10362:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10363:        return $result.&show_grading_menu_form($symb);
10364:     } 
10365: # Remember Question Titles
10366: # FIXME: Possibly need delimiter other than ":"
10367:     for (my $i=0;$i<$number;$i++) {
10368:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10369:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10370:     }
10371:     my $correct_count=0;
10372:     my $student_count=0;
10373:     my $unknown_count=0;
10374: # Match answers with usernames
10375: # FIXME: Possibly need delimiter other than ":"
10376:     foreach my $id (keys(%responses)) {
10377:        if ($correct_ids{$id}) {
10378:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10379:           $correct_count++;
10380:        } elsif ($clicker_ids{$id}) {
10381:           if ($clicker_ids{$id}=~/\,/) {
10382: # More than one user with the same clicker!
10383:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10384:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10385:                            "<select name='multi".$id."'>";
10386:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10387:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10388:              }
10389:              $result.='</select>';
10390:              $unknown_count++;
10391:           } else {
10392: # Good: found one and only one user with the right clicker
10393:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10394:              $student_count++;
10395:           }
10396:        } else {
10397:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10398:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10399:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10400:                    "\n".&mt("Domain").": ".
10401:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10402:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10403:           $unknown_count++;
10404:        }
10405:     }
10406:     $result.='<hr />'.
10407:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10408:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10409:        if ($correct_count==0) {
10410:           $errormsg.="Found no correct answers for grading!";
10411:        } elsif ($correct_count>1) {
10412:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10413:        }
10414:     }
10415:     if ($number<1) {
10416:        $errormsg.="Found no questions.";
10417:     }
10418:     if ($errormsg) {
10419:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10420:     } else {
10421:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10422:     }
10423:     $result.='</form></td></tr></table>'."\n".
10424:              '</td></tr></table><br /><br />'."\n";
10425:     return $result.&show_grading_menu_form($symb);
10426: }
10427: 
10428: sub iclicker_eval {
10429:     my ($questiontitles,$responses)=@_;
10430:     my $number=0;
10431:     my $errormsg='';
10432:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10433:         my %components=&Apache::loncommon::record_sep($line);
10434:         my @entries=map {$components{$_}} (sort(keys(%components)));
10435: 	if ($entries[0] eq 'Question') {
10436: 	    for (my $i=3;$i<$#entries;$i+=6) {
10437: 		$$questiontitles[$number]=$entries[$i];
10438: 		$number++;
10439: 	    }
10440: 	}
10441: 	if ($entries[0]=~/^\#/) {
10442: 	    my $id=$entries[0];
10443: 	    my @idresponses;
10444: 	    $id=~s/^[\#0]+//;
10445: 	    for (my $i=0;$i<$number;$i++) {
10446: 		my $idx=3+$i*6;
10447:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10448: 		push(@idresponses,$entries[$idx]);
10449: 	    }
10450: 	    $$responses{$id}=join(',',@idresponses);
10451: 	}
10452:     }
10453:     return ($errormsg,$number);
10454: }
10455: 
10456: sub interwrite_eval {
10457:     my ($questiontitles,$responses)=@_;
10458:     my $number=0;
10459:     my $errormsg='';
10460:     my $skipline=1;
10461:     my $questionnumber=0;
10462:     my %idresponses=();
10463:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10464:         my %components=&Apache::loncommon::record_sep($line);
10465:         my @entries=map {$components{$_}} (sort(keys(%components)));
10466:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10467:         if ($entries[1] eq 'Response') { $skipline=1; }
10468:         next if $skipline;
10469:         if ($entries[0]!=$questionnumber) {
10470:            $questionnumber=$entries[0];
10471:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10472:            $number++;
10473:         }
10474:         my $id=$entries[4];
10475:         $id=~s/^[\#0]+//;
10476:         $id=~s/^v\d*\://i;
10477:         $id=~s/[\-\:]//g;
10478:         $idresponses{$id}[$number]=$entries[6];
10479:     }
10480:     foreach my $id (keys(%idresponses)) {
10481:        $$responses{$id}=join(',',@{$idresponses{$id}});
10482:        $$responses{$id}=~s/^\s*\,//;
10483:     }
10484:     return ($errormsg,$number);
10485: }
10486: 
10487: sub turning_eval {
10488:     my ($questiontitles,$responses)=@_;
10489:     my $number=0;
10490:     my $errormsg='';
10491:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10492:         my %components=&Apache::loncommon::record_sep($line);
10493:         my @entries=map {$components{$_}} (sort(keys(%components)));
10494:         if ($#entries>$number) { $number=$#entries; }
10495:         my $id=$entries[0];
10496:         my @idresponses;
10497:         $id=~s/^[\#0]+//;
10498:         unless ($id) { next; }
10499:         for (my $idx=1;$idx<=$#entries;$idx++) {
10500:             $entries[$idx]=~s/\,/\;/g;
10501:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10502:             push(@idresponses,$entries[$idx]);
10503:         }
10504:         $$responses{$id}=join(',',@idresponses);
10505:     }
10506:     for (my $i=1; $i<=$number; $i++) {
10507:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10508:     }
10509:     return ($errormsg,$number);
10510: }
10511: 
10512: sub assign_clicker_grades {
10513:     my ($r)=@_;
10514:     my ($symb)=&get_symb($r);
10515:     if (!$symb) {return '';}
10516: # See which part we are saving to
10517:     my $res_error;
10518:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10519:     if ($res_error) {
10520:         return &navmap_errormsg();
10521:     }
10522: # FIXME: This should probably look for the first handgradeable part
10523:     my $part=$$partlist[0];
10524: # Start screen output
10525:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10526: 
10527:     $result .= '<br />'.
10528:                &Apache::loncommon::start_data_table().
10529:                &Apache::loncommon::start_data_table_header_row().
10530:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10531:                &Apache::loncommon::end_data_table_header_row().
10532:                &Apache::loncommon::start_data_table_row().'<td>';
10533: 
10534: # Get correct result
10535: # FIXME: Possibly need delimiter other than ":"
10536:     my @correct=();
10537:     my $gradingmechanism=$env{'form.gradingmechanism'};
10538:     my $number=$env{'form.number'};
10539:     if ($gradingmechanism ne 'attendance') {
10540:        foreach my $key (keys(%env)) {
10541:           if ($key=~/^form\.correct\:/) {
10542:              my @input=split(/\,/,$env{$key});
10543:              for (my $i=0;$i<=$#input;$i++) {
10544:                  if (($correct[$i]) && ($input[$i]) &&
10545:                      ($correct[$i] ne $input[$i])) {
10546:                     $result.='<br /><span class="LC_warning">'.
10547:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10548:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10549:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10550:                     $correct[$i]=$input[$i];
10551:                  }
10552:              }
10553:           }
10554:        }
10555:        for (my $i=0;$i<$number;$i++) {
10556:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10557:              $result.='<br /><span class="LC_error">'.
10558:                       &mt('No correct result given for question "[_1]"!',
10559:                           $env{'form.question:'.$i}).'</span>';
10560:           }
10561:        }
10562:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10563:     }
10564: # Start grading
10565:     my $pcorrect=$env{'form.pcorrect'};
10566:     my $pincorrect=$env{'form.pincorrect'};
10567:     my $storecount=0;
10568:     my %users=();
10569:     foreach my $key (keys(%env)) {
10570:        my $user='';
10571:        if ($key=~/^form\.student\:(.*)$/) {
10572:           $user=$1;
10573:        }
10574:        if ($key=~/^form\.unknown\:(.*)$/) {
10575:           my $id=$1;
10576:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10577:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10578:           } elsif ($env{'form.multi'.$id}) {
10579:              $user=$env{'form.multi'.$id};
10580:           }
10581:        }
10582:        if ($user) {
10583:           if ($users{$user}) {
10584:              $result.='<br /><span class="LC_warning">'.
10585:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10586:                       '</span><br />';
10587:           }
10588:           $users{$user}=1;
10589:           my @answer=split(/\,/,$env{$key});
10590:           my $sum=0;
10591:           my $realnumber=$number;
10592:           for (my $i=0;$i<$number;$i++) {
10593:              if  ($correct[$i] eq '-') {
10594:                 $realnumber--;
10595:              } elsif ($answer[$i]) {
10596:                 if ($gradingmechanism eq 'attendance') {
10597:                    $sum+=$pcorrect;
10598:                 } elsif ($correct[$i] eq '*') {
10599:                    $sum+=$pcorrect;
10600:                 } else {
10601: # We actually grade if correct or not
10602:                    my $increment=$pincorrect;
10603: # Special case: numerical answer "0"
10604:                    if ($correct[$i] eq '0') {
10605:                       if ($answer[$i]=~/^[0\.]+$/) {
10606:                          $increment=$pcorrect;
10607:                       }
10608: # General numerical answer, both evaluate to something non-zero
10609:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10610:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10611:                          $increment=$pcorrect;
10612:                       }
10613: # Must be just alphanumeric
10614:                    } elsif ($answer[$i] eq $correct[$i]) {
10615:                       $increment=$pcorrect;
10616:                    }
10617:                    $sum+=$increment;
10618:                 }
10619:              }
10620:           }
10621:           my $ave=$sum/(100*$realnumber);
10622: # Store
10623:           my ($username,$domain)=split(/\:/,$user);
10624:           my %grades=();
10625:           $grades{"resource.$part.solved"}='correct_by_override';
10626:           $grades{"resource.$part.awarded"}=$ave;
10627:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10628:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10629:                                                  $env{'request.course.id'},
10630:                                                  $domain,$username);
10631:           if ($returncode ne 'ok') {
10632:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10633:           } else {
10634:              $storecount++;
10635:           }
10636:        }
10637:     }
10638: # We are done
10639:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10640:              '</td>'.
10641:              &Apache::loncommon::end_data_table_row().
10642:              &Apache::loncommon::end_data_table()."<br /><br />\n";
10643:     return $result.&show_grading_menu_form($symb);
10644: }
10645: 
10646: sub navmap_errormsg {
10647:     return '<div class="LC_error">'.
10648:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10649:            &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>').
10650:            '</div>';
10651: }
10652: 
10653: sub startpage {
10654:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10655:     if ($nomenu) {
10656:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10657:     } else {
10658:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10659:                                                  {'bread_crumbs' => $crumbs}));
10660:     }
10661:     unless ($nodisplayflag) {
10662:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10663:     }
10664: }
10665: 
10666: sub handler {
10667:     my $request=$_[0];
10668:     &reset_caches();
10669:     if ($request->header_only) {
10670:         &Apache::loncommon::content_type($request,'text/html');
10671:         $request->send_http_header;
10672:         return OK;
10673:     }
10674:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10675: 
10676:     my $symb=&get_symb($request,1);
10677:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10678:     my $command=$commands[0];
10679: 
10680:     if ($#commands > 0) {
10681: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10682:     }
10683: 
10684:     $ssi_error = 0;
10685:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10686:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
10687:                                                     {'bread_crumbs' => $brcrum});
10688:     if ($symb eq '' && $command eq '') {
10689: 	if ($env{'user.adv'}) {
10690:             &Apache::loncommon::content_type($request,'text/html');
10691:             $request->send_http_header;
10692:             $request->print($start_page);
10693: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10694: 		($env{'form.codethree'})) {
10695: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10696: 		    $env{'form.codethree'};
10697: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
10698: 		    &Apache::lonnet::checkin($token);
10699: 		if ($tsymb) {
10700: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10701: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10702: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10703: 					  ('grade_username' => $tuname,
10704: 					   'grade_domain' => $tudom,
10705: 					   'grade_courseid' => $tcrsid,
10706: 					   'grade_symb' => $tsymb)));
10707: 		    } else {
10708: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
10709: 		    }
10710: 		} else {
10711: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10712: 		}
10713: 	    } else {
10714: 		$request->print(&Apache::lonxml::tokeninputfield());
10715: 	    }
10716:         } elsif ($env{'request.course.id'}) {
10717:             &init_perm(); 
10718:             if (!%perm) {
10719:                 $request->internal_redirect('/adm/quickgrades');
10720:                 return OK;
10721:             } else {
10722:                 &Apache::loncommon::content_type($request,'text/html');
10723:                 $request->send_http_header;
10724:                 $request->print($start_page);
10725:             }
10726:         }
10727:     } else {
10728:         &init_perm();
10729:         if (!$env{'request.course.id'}) {
10730:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10731:                     ($command =~ /^scantronupload/)) {
10732:                 # Not in a course.
10733:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10734:                 return HTTP_NOT_ACCEPTABLE;
10735:             }
10736:         } elsif (!%perm) {
10737:             $request->internal_redirect('/adm/quickgrades');
10738:         }
10739:         &Apache::loncommon::content_type($request,'text/html');
10740:         $request->send_http_header;
10741:         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10742:             $request->print($start_page); 
10743:         }
10744: 	if ($command eq 'submission' && $perm{'vgr'}) {
10745:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10746:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10747:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10748:                     &choose_task_version_form($symb,$env{'form.student'},
10749:                                               $env{'form.userdom'});
10750:             }
10751:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10752:             if ($versionform) {
10753:                 $request->print($versionform);
10754:             }
10755:             $request->print('<br clear="all" />');
10756: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10757:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10758:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10759:                 &choose_task_version_form($symb,$env{'form.student'},
10760:                                           $env{'form.userdom'},
10761:                                           $env{'form.inhibitmenu'});
10762:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10763:             if ($versionform) {
10764:                 $request->print($versionform);
10765:             }
10766:             $request->print('<br clear="all" />');
10767:             $request->print(&show_previous_task_version($request,$symb));
10768: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10769: 	    &pickStudentPage($request);
10770: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10771: 	    &displayPage($request);
10772: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10773: 	    &updateGradeByPage($request);
10774: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10775: 	    &processGroup($request);
10776: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10777: 	    $request->print(&grading_menu($request));
10778: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10779: 	    $request->print(&submit_options($request));
10780: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10781: 	    $request->print(&viewgrades($request));
10782: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10783: 	    $request->print(&processHandGrade($request));
10784: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10785: 	    $request->print(&editgrades($request));
10786: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10787: 	    $request->print(&verifyreceipt($request));
10788:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10789:             $request->print(&process_clicker($request));
10790:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10791:             $request->print(&process_clicker_file($request));
10792:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10793:             $request->print(&assign_clicker_grades($request));
10794: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10795: 	    $request->print(&upcsvScores_form($request));
10796: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10797: 	    $request->print(&csvupload($request));
10798: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10799: 	    $request->print(&csvuploadmap($request));
10800: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10801: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10802: 		$request->print(&csvuploadoptions($request));
10803: 	    } else {
10804: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10805: 		    $env{'form.upfile_associate'} = 'reverse';
10806: 		} else {
10807: 		    $env{'form.upfile_associate'} = 'forward';
10808: 		}
10809: 		$request->print(&csvuploadmap($request));
10810: 	    }
10811: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10812: 	    $request->print(&csvuploadassign($request));
10813: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10814: 	    $request->print(&scantron_selectphase($request));
10815:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10816:  	    $request->print(&scantron_do_warning($request));
10817: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10818: 	    $request->print(&scantron_validate_file($request));
10819: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10820: 	    $request->print(&scantron_process_students($request));
10821:  	} elsif ($command eq 'scantronupload' && 
10822:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10823: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10824:  	    $request->print(&scantron_upload_scantron_data($request)); 
10825:  	} elsif ($command eq 'scantronupload_save' &&
10826:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10827: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10828:  	    $request->print(&scantron_upload_scantron_data_save($request));
10829:  	} elsif ($command eq 'scantron_download' &&
10830: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10831:  	    $request->print(&scantron_download_scantron_data($request));
10832:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10833:             $request->print(&checkscantron_results($request));     
10834: 	} elsif ($command) {
10835: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10836: 	}
10837:     }
10838:     if ($ssi_error) {
10839: 	&ssi_print_error($request);
10840:     }
10841:     $request->print(&Apache::loncommon::end_page());
10842:     &reset_caches();
10843:     return OK;
10844: }
10845: 
10846: 1;
10847: 
10848: __END__;
10849: 
10850: 
10851: =head1 NAME
10852: 
10853: Apache::grades
10854: 
10855: =head1 SYNOPSIS
10856: 
10857: Handles the viewing of grades.
10858: 
10859: This is part of the LearningOnline Network with CAPA project
10860: described at http://www.lon-capa.org.
10861: 
10862: =head1 OVERVIEW
10863: 
10864: Do an ssi with retries:
10865: While I'd love to factor out this with the vesrion in lonprintout,
10866: 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
10867: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10868: 
10869: At least the logic that drives this has been pulled out into loncommon.
10870: 
10871: 
10872: 
10873: ssi_with_retries - Does the server side include of a resource.
10874:                      if the ssi call returns an error we'll retry it up to
10875:                      the number of times requested by the caller.
10876:                      If we still have a problem, no text is appended to the
10877:                      output and we set some global variables.
10878:                      to indicate to the caller an SSI error occurred.  
10879:                      All of this is supposed to deal with the issues described
10880:                      in LON-CAPA BZ 5631 see:
10881:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10882:                      by informing the user that this happened.
10883: 
10884: Parameters:
10885:   resource   - The resource to include.  This is passed directly, without
10886:                interpretation to lonnet::ssi.
10887:   form       - The form hash parameters that guide the interpretation of the resource
10888:                
10889:   retries    - Number of retries allowed before giving up completely.
10890: Returns:
10891:   On success, returns the rendered resource identified by the resource parameter.
10892: Side Effects:
10893:   The following global variables can be set:
10894:    ssi_error                - If an unrecoverable error occurred this becomes true.
10895:                               It is up to the caller to initialize this to false
10896:                               if desired.
10897:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10898:                               of the resource that could not be rendered by the ssi
10899:                               call.
10900:    ssi_error_message   - The error string fetched from the ssi response
10901:                               in the event of an error.
10902: 
10903: 
10904: =head1 HANDLER SUBROUTINE
10905: 
10906: ssi_with_retries()
10907: 
10908: =head1 SUBROUTINES
10909: 
10910: =over
10911: 
10912: =item scantron_get_correction() : 
10913: 
10914:    Builds the interface screen to interact with the operator to fix a
10915:    specific error condition in a specific scanline
10916: 
10917:  Arguments:
10918:     $r           - Apache request object
10919:     $i           - number of the current scanline
10920:     $scan_record - hash ref as returned from &scantron_parse_scanline()
10921:     $scan_config - hash ref as returned from &get_scantron_config()
10922:     $line        - full contents of the current scanline
10923:     $error       - error condition, valid values are
10924:                    'incorrectCODE', 'duplicateCODE',
10925:                    'doublebubble', 'missingbubble',
10926:                    'duplicateID', 'incorrectID'
10927:     $arg         - extra information needed
10928:        For errors:
10929:          - duplicateID   - paper number that this studentID was seen before on
10930:          - duplicateCODE - array ref of the paper numbers this CODE was
10931:                            seen on before
10932:          - incorrectCODE - current incorrect CODE 
10933:          - doublebubble  - array ref of the bubble lines that have double
10934:                            bubble errors
10935:          - missingbubble - array ref of the bubble lines that have missing
10936:                            bubble errors
10937: 
10938:    $randomorder - True if exam folder has randomorder set
10939:    $randompick  - True if exam folder has randompick set
10940:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10941:                      for current line to question number used for same question
10942:                      in "Master Seqence" (as seen by Course Coordinator).
10943:    $startline   - Reference to hash where key is question number (0 is first)
10944:                   and value is number of first bubble line for current student
10945:                   or code-based randompick and/or randomorder.
10946: 
10947: 
10948: =item  scantron_get_maxbubble() : 
10949: 
10950:    Arguments:
10951:        $nav_error  - Reference to scalar which is a flag to indicate a
10952:                       failure to retrieve a navmap object.
10953:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
10954:        calling routine should trap the error condition and display the warning
10955:        found in &navmap_errormsg().
10956: 
10957:        $scantron_config - Reference to bubblesheet format configuration hash.
10958: 
10959:    Returns the maximum number of bubble lines that are expected to
10960:    occur. Does this by walking the selected sequence rendering the
10961:    resource and then checking &Apache::lonxml::get_problem_counter()
10962:    for what the current value of the problem counter is.
10963: 
10964:    Caches the results to $env{'form.scantron_maxbubble'},
10965:    $env{'form.scantron.bubble_lines.n'}, 
10966:    $env{'form.scantron.first_bubble_line.n'} and
10967:    $env{"form.scantron.sub_bubblelines.n"}
10968:    which are the total number of bubble lines, the number of bubble
10969:    lines for response n and number of the first bubble line for response n,
10970:    and a comma separated list of numbers of bubble lines for sub-questions
10971:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
10972: 
10973: 
10974: =item  scantron_validate_missingbubbles() : 
10975: 
10976:    Validates all scanlines in the selected file to not have any
10977:     answers that don't have bubbles that have not been verified
10978:     to be bubble free.
10979: 
10980: =item  scantron_process_students() : 
10981: 
10982:    Routine that does the actual grading of the bubblesheet information.
10983: 
10984:    The parsed scanline hash is added to %env 
10985: 
10986:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10987:    foreach resource , with the form data of
10988: 
10989: 	'submitted'     =>'scantron' 
10990: 	'grade_target'  =>'grade',
10991: 	'grade_username'=> username of student
10992: 	'grade_domain'  => domain of student
10993: 	'grade_courseid'=> of course
10994: 	'grade_symb'    => symb of resource to grade
10995: 
10996:     This triggers a grading pass. The problem grading code takes care
10997:     of converting the bubbled letter information (now in %env) into a
10998:     valid submission.
10999: 
11000: =item  scantron_upload_scantron_data() :
11001: 
11002:     Creates the screen for adding a new bubblesheet data file to a course.
11003: 
11004: =item  scantron_upload_scantron_data_save() : 
11005: 
11006:    Adds a provided bubble information data file to the course if user
11007:    has the correct privileges to do so. 
11008: 
11009: =item  valid_file() :
11010: 
11011:    Validates that the requested bubble data file exists in the course.
11012: 
11013: =item  scantron_download_scantron_data() : 
11014: 
11015:    Shows a list of the three internal files (original, corrected,
11016:    skipped) for a specific bubblesheet data file that exists in the
11017:    course.
11018: 
11019: =item  scantron_validate_ID() : 
11020: 
11021:    Validates all scanlines in the selected file to not have any
11022:    invalid or underspecified student/employee IDs
11023: 
11024: =item navmap_errormsg() :
11025: 
11026:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11027:    Should be called whenever the request to instantiate a navmap object fails.  
11028: 
11029: =back
11030: 
11031: =cut

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