File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.750: download - view: text, annotated - select for diffs
Fri May 4 15:15:05 2018 UTC (6 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Three new args added to &getclasslist() to support filtering by submission
  status.
- Download Submissions selection for Sections, Groups, Access Status, and
  Submission Status now used to populate list of students for use by
  multidownload.pl

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.750 2018/05/04 15:15:05 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common :http);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use Apache::lonstathelpers;
   47: use Apache::lonquickgrades;
   48: use Apache::bridgetask();
   49: use String::Similarity;
   50: use LONCAPA;
   51: 
   52: use POSIX qw(floor);
   53: 
   54: 
   55: 
   56: my %perm=();
   57: my %old_essays=();
   58: 
   59: #  These variables are used to recover from ssi errors
   60: 
   61: my $ssi_retries = 5;
   62: my $ssi_error;
   63: my $ssi_error_resource;
   64: my $ssi_error_message;
   65: 
   66: 
   67: sub ssi_with_retries {
   68:     my ($resource, $retries, %form) = @_;
   69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   70:     if ($response->is_error) {
   71: 	$ssi_error          = 1;
   72: 	$ssi_error_resource = $resource;
   73: 	$ssi_error_message  = $response->code . " " . $response->message;
   74:     }
   75: 
   76:     return $content;
   77: 
   78: }
   79: #
   80: #  Prodcuces an ssi retry failure error message to the user:
   81: #
   82: 
   83: sub ssi_print_error {
   84:     my ($r) = @_;
   85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   86:     $r->print('
   87: <br />
   88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   89: <p>
   90: '.&mt('Unable to retrieve a resource from a server:').'<br />
   91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   92: '.&mt('Error:').' '.$ssi_error_message.'
   93: </p>
   94: <p>'.
   95: &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 />'.
   96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   97: '</p>');
   98:     return;
   99: }
  100: 
  101: #
  102: # --- Retrieve the parts from the metadata file.---
  103: # Returns an array of everything that the resources stores away
  104: #
  105: 
  106: sub getpartlist {
  107:     my ($symb,$errorref) = @_;
  108: 
  109:     my $navmap   = Apache::lonnavmaps::navmap->new();
  110:     unless (ref($navmap)) {
  111:         if (ref($errorref)) { 
  112:             $$errorref = 'navmap';
  113:             return;
  114:         }
  115:     }
  116:     my $res      = $navmap->getBySymb($symb);
  117:     my $partlist = $res->parts();
  118:     my $url      = $res->src();
  119:     my $toolsymb;
  120:     if ($url =~ /ext\.tool$/) {
  121:         $toolsymb = $symb;
  122:     }
  123:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
  124: 
  125:     my @stores;
  126:     foreach my $part (@{ $partlist }) {
  127: 	foreach my $key (@metakeys) {
  128: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  129: 	}
  130:     }
  131:     return @stores;
  132: }
  133: 
  134: #--- Format fullname, username:domain if different for display
  135: #--- Use anywhere where the student names are listed
  136: sub nameUserString {
  137:     my ($type,$fullname,$uname,$udom) = @_;
  138:     if ($type eq 'header') {
  139: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  140:     } else {
  141: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  142: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  143:     }
  144: }
  145: 
  146: #--- Get the partlist and the response type for a given problem. ---
  147: #--- Indicate if a response type is coded handgraded or not. ---
  148: #--- Sets response_error pointer to "1" if navmaps object broken ---
  149: sub response_type {
  150:     my ($symb,$response_error) = @_;
  151: 
  152:     my $navmap = Apache::lonnavmaps::navmap->new();
  153:     unless (ref($navmap)) {
  154:         if (ref($response_error)) {
  155:             $$response_error = 1;
  156:         }
  157:         return;
  158:     }
  159:     my $res = $navmap->getBySymb($symb);
  160:     unless (ref($res)) {
  161:         $$response_error = 1;
  162:         return;
  163:     }
  164:     my $partlist = $res->parts();
  165:     my %vPart = 
  166: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  167:     my (%response_types,%handgrade);
  168:     foreach my $part (@{ $partlist }) {
  169: 	next if (%vPart && !exists($vPart{$part}));
  170: 
  171: 	my @types = $res->responseType($part);
  172: 	my @ids = $res->responseIds($part);
  173: 	for (my $i=0; $i < scalar(@ids); $i++) {
  174: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  175: 	    $handgrade{$part.'_'.$ids[$i]} = 
  176: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  177: 				     '.handgrade',$symb);
  178: 	}
  179:     }
  180:     return ($partlist,\%handgrade,\%response_types);
  181: }
  182: 
  183: sub flatten_responseType {
  184:     my ($responseType) = @_;
  185:     my @part_response_id =
  186: 	map { 
  187: 	    my $part = $_;
  188: 	    map {
  189: 		[$part,$_]
  190: 		} sort(keys(%{ $responseType->{$part} }));
  191: 	} sort(keys(%$responseType));
  192:     return @part_response_id;
  193: }
  194: 
  195: sub get_display_part {
  196:     my ($partID,$symb)=@_;
  197:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  198:     if (defined($display) and $display ne '') {
  199:         $display.= ' (<span class="LC_internal_info">'
  200:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  201:     } else {
  202: 	$display=$partID;
  203:     }
  204:     return $display;
  205: }
  206: 
  207: sub reset_caches {
  208:     &reset_analyze_cache();
  209:     &reset_perm();
  210:     &reset_old_essays();
  211: }
  212: 
  213: {
  214:     my %analyze_cache;
  215:     my %analyze_cache_formkeys;
  216: 
  217:     sub reset_analyze_cache {
  218: 	undef(%analyze_cache);
  219:         undef(%analyze_cache_formkeys);
  220:     }
  221: 
  222:     sub get_analyze {
  223: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
  224: 	my $key = "$symb\0$uname\0$udom";
  225:         if ($type eq 'randomizetry') {
  226:             if ($trial ne '') {
  227:                 $key .= "\0".$trial;
  228:             }
  229:         }
  230: 	if (exists($analyze_cache{$key})) {
  231:             my $getupdate = 0;
  232:             if (ref($add_to_hash) eq 'HASH') {
  233:                 foreach my $item (keys(%{$add_to_hash})) {
  234:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  235:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  236:                             $getupdate = 1;
  237:                             last;
  238:                         }
  239:                     } else {
  240:                         $getupdate = 1;
  241:                     }
  242:                 }
  243:             }
  244:             if (!$getupdate) {
  245:                 return $analyze_cache{$key};
  246:             }
  247:         }
  248: 
  249: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  250: 	$url=&Apache::lonnet::clutter($url);
  251:         my %form = ('grade_target'      => 'analyze',
  252:                     'grade_domain'      => $udom,
  253:                     'grade_symb'        => $symb,
  254:                     'grade_courseid'    =>  $env{'request.course.id'},
  255:                     'grade_username'    => $uname,
  256:                     'grade_noincrement' => $no_increment);
  257:         if ($bubbles_per_row ne '') {
  258:             $form{'bubbles_per_row'} = $bubbles_per_row;
  259:         }
  260:         if ($type eq 'randomizetry') {
  261:             $form{'grade_questiontype'} = $type;
  262:             if ($rndseed ne '') {
  263:                 $form{'grade_rndseed'} = $rndseed;
  264:             }
  265:         }
  266:         if (ref($add_to_hash)) {
  267:             %form = (%form,%{$add_to_hash});
  268:         }
  269: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  270: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  271: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  272:         if (ref($add_to_hash) eq 'HASH') {
  273:             $analyze_cache_formkeys{$key} = $add_to_hash;
  274:         } else {
  275:             $analyze_cache_formkeys{$key} = {};
  276:         }
  277: 	return $analyze_cache{$key} = \%analyze;
  278:     }
  279: 
  280:     sub get_order {
  281: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  282: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  283: 	return $analyze->{"$partid.$respid.shown"};
  284:     }
  285: 
  286:     sub get_radiobutton_correct_foil {
  287: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  288: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  289:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  290:         if (ref($foils) eq 'ARRAY') {
  291: 	    foreach my $foil (@{$foils}) {
  292: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  293: 		    return $foil;
  294: 	        }
  295: 	    }
  296: 	}
  297:     }
  298: 
  299:     sub scantron_partids_tograde {
  300:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
  301:         my (%analysis,@parts);
  302:         if (ref($resource)) {
  303:             my $symb = $resource->symb();
  304:             my $add_to_form;
  305:             if ($check_for_randomlist) {
  306:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  307:             }
  308:             if ($scancode) {
  309:                 if (ref($add_to_form) eq 'HASH') {
  310:                     $add_to_form->{'code_for_randomlist'} = $scancode;
  311:                 } else {
  312:                     $add_to_form = { 'code_for_randomlist' => $scancode,};
  313:                 }
  314:             }
  315:             my $analyze = 
  316:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
  317:                              undef,undef,undef,$bubbles_per_row);
  318:             if (ref($analyze) eq 'HASH') {
  319:                 %analysis = %{$analyze};
  320:             }
  321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  322:                 foreach my $part (@{$analysis{'parts'}}) {
  323:                     my ($id,$respid) = split(/\./,$part);
  324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  325:                         push(@parts,$part);
  326:                     }
  327:                 }
  328:             }
  329:         }
  330:         return (\%analysis,\@parts);
  331:     }
  332: 
  333: }
  334: 
  335: #--- Clean response type for display
  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
  337: #        response types only.
  338: sub cleanRecord {
  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  340: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  341:     my $grayFont = '<span class="LC_internal_info">';
  342:     if ($response =~ /^(option|rank)$/) {
  343: 	my %answer=&Apache::lonnet::str2hash($answer);
  344:         my @answer = %answer;
  345:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  346: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  347: 	my ($toprow,$bottomrow);
  348: 	foreach my $foil (@$order) {
  349: 	    if ($grading{$foil} == 1) {
  350: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  351: 	    } else {
  352: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  353: 	    }
  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  355: 	}
  356: 	return '<blockquote><table border="1">'.
  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  359: 	    $bottomrow.'</tr></table></blockquote>';
  360:     } elsif ($response eq 'match') {
  361: 	my %answer=&Apache::lonnet::str2hash($answer);
  362:         my @answer = %answer;
  363:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  364: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  365: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  366: 	my ($toprow,$middlerow,$bottomrow);
  367: 	foreach my $foil (@$order) {
  368: 	    my $item=shift(@items);
  369: 	    if ($grading{$foil} == 1) {
  370: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  371: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  372: 	    } else {
  373: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  374: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  375: 	    }
  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  377: 	}
  378: 	return '<blockquote><table border="1">'.
  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  381: 	    $middlerow.'</tr>'.
  382: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  383: 	    $bottomrow.'</tr></table></blockquote>';
  384:     } elsif ($response eq 'radiobutton') {
  385: 	my %answer=&Apache::lonnet::str2hash($answer);
  386:         my @answer = %answer;
  387:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
  388: 	my ($toprow,$bottomrow);
  389: 	my $correct = 
  390: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  391: 	foreach my $foil (@$order) {
  392: 	    if (exists($answer{$foil})) {
  393: 		if ($foil eq $correct) {
  394: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  395: 		} else {
  396: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  397: 		}
  398: 	    } else {
  399: 		$toprow.='<td>'.&mt('false').'</td>';
  400: 	    }
  401: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  402: 	}
  403: 	return '<blockquote><table border="1">'.
  404: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  405: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  406: 	    $bottomrow.'</tr></table></blockquote>';
  407:     } elsif ($response eq 'essay') {
  408: 	if (! exists ($env{'form.'.$symb})) {
  409: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  410: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  411: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  412: 
  413: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  414: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  415: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  416: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  417: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  418: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  419: 	}
  420: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  421: 
  422:     } elsif ( $response eq 'organic') {
  423:         my $result=&mt('Smile representation: [_1]',
  424:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
  425: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  426: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  427: 	return $result;
  428:     } elsif ( $response eq 'Task') {
  429: 	if ( $answer eq 'SUBMITTED') {
  430: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  431: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  432: 	    return $result;
  433: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  434: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  435: 			       keys(%{$record}));
  436: 	    return join('<br />',($version,@matches));
  437: 			       
  438: 			       
  439: 	} else {
  440: 	    my $result =
  441: 		'<p>'
  442: 		.&mt('Overall result: [_1]',
  443: 		     $record->{$version."resource.$respid.$partid.status"})
  444: 		.'</p>';
  445: 	    
  446: 	    $result .= '<ul>';
  447: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  448: 			     keys(%{$record}));
  449: 	    foreach my $grade (sort(@grade)) {
  450: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  451: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  452: 				     $dim, $record->{$grade}).
  453: 			  '</li>';
  454: 	    }
  455: 	    $result.='</ul>';
  456: 	    return $result;
  457: 	}
  458:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
  459:         # Respect multiple input fields, see Bug #5409
  460: 	$answer = 
  461: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  462: 							      $answer);
  463: 	return $answer;
  464:     }
  465:     return &HTML::Entities::encode($answer, '"<>&');
  466: }
  467: 
  468: #-- A couple of common js functions
  469: sub commonJSfunctions {
  470:     my $request = shift;
  471:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
  472:     function radioSelection(radioButton) {
  473: 	var selection=null;
  474: 	if (radioButton.length > 1) {
  475: 	    for (var i=0; i<radioButton.length; i++) {
  476: 		if (radioButton[i].checked) {
  477: 		    return radioButton[i].value;
  478: 		}
  479: 	    }
  480: 	} else {
  481: 	    if (radioButton.checked) return radioButton.value;
  482: 	}
  483: 	return selection;
  484:     }
  485: 
  486:     function pullDownSelection(selectOne) {
  487: 	var selection="";
  488: 	if (selectOne.length > 1) {
  489: 	    for (var i=0; i<selectOne.length; i++) {
  490: 		if (selectOne[i].selected) {
  491: 		    return selectOne[i].value;
  492: 		}
  493: 	    }
  494: 	} else {
  495:             // only one value it must be the selected one
  496: 	    return selectOne.value;
  497: 	}
  498:     }
  499: COMMONJSFUNCTIONS
  500: }
  501: 
  502: #--- Dumps the class list with usernames,list of sections,
  503: #--- section, ids and fullnames for each user.
  504: sub getclasslist {
  505:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
  506:     my @getsec;
  507:     my @getgroup;
  508:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  509:     if (!ref($getsec)) {
  510: 	if ($getsec ne '' && $getsec ne 'all') {
  511: 	    @getsec=($getsec);
  512: 	}
  513:     } else {
  514: 	@getsec=@{$getsec};
  515:     }
  516:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  517:     if (!ref($getgroup)) {
  518: 	if ($getgroup ne '' && $getgroup ne 'all') {
  519: 	    @getgroup=($getgroup);
  520: 	}
  521:     } else {
  522: 	@getgroup=@{$getgroup};
  523:     }
  524:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  525: 
  526:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  527:     # Bail out if we were unable to get the classlist
  528:     return if (! defined($classlist));
  529:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  530:     #
  531:     my %sections;
  532:     my %fullnames;
  533:     my ($cdom,$cnum,$partlist);
  534:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  535:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
  536:         $cnum = $env{"course.$env{'request.course.id'}.num"};
  537:         my $res_error;
  538:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
  539:     }
  540:     foreach my $student (keys(%$classlist)) {
  541:         my $end      = 
  542:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  543:         my $start    = 
  544:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  545:         my $id       = 
  546:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  547:         my $section  = 
  548:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  549:         my $fullname = 
  550:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  551:         my $status   = 
  552:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  553:         my $group   = 
  554:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  555: 	# filter students according to status selected
  556: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
  557: 	    if (!($stu_status =~ $status)) {
  558: 		delete($classlist->{$student});
  559: 		next;
  560: 	    }
  561: 	}
  562: 	# filter students according to groups selected
  563: 	my @stu_groups = split(/,/,$group);
  564: 	if (@getgroup) {
  565: 	    my $exclude = 1;
  566: 	    foreach my $grp (@getgroup) {
  567: 	        foreach my $stu_group (@stu_groups) {
  568: 	            if ($stu_group eq $grp) {
  569: 	                $exclude = 0;
  570:     	            } 
  571: 	        }
  572:     	        if (($grp eq 'none') && !$group) {
  573:         	    $exclude = 0;
  574:         	}
  575: 	    }
  576: 	    if ($exclude) {
  577: 	        delete($classlist->{$student});
  578: 		next;
  579: 	    }
  580: 	}
  581:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
  582:             my $udom =
  583:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
  584:             my $uname =
  585:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
  586:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
  587:                 if ($submitonly eq 'queued') {
  588:                     my %queue_status =
  589:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  590:                                                                 $udom,$uname);
  591:                     if (!defined($queue_status{'gradingqueue'})) {
  592:                         delete($classlist->{$student});
  593:                         next;
  594:                     }
  595:                 } else {
  596:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  597:                     my $submitted = 0;
  598:                     my $graded = 0;
  599:                     my $incorrect = 0;
  600:                     foreach (keys(%status)) {
  601:                         $submitted = 1 if ($status{$_} ne 'nothing');
  602:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
  603:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
  604: 
  605:                         my ($foo,$partid,$foo1) = split(/\./,$_);
  606:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  607:                             $submitted = 0;
  608:                         }
  609:                     }
  610:                     if (!$submitted && ($submitonly eq 'yes' ||
  611:                                         $submitonly eq 'incorrect' ||
  612:                                         $submitonly eq 'graded')) {
  613:                         delete($classlist->{$student});
  614:                         next;
  615:                     } elsif (!$graded && ($submitonly eq 'graded')) {
  616:                         delete($classlist->{$student});
  617:                         next;
  618:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
  619:                         delete($classlist->{$student});
  620:                         next;
  621:                     }
  622:                 }
  623:             }
  624:         }
  625: 	$section = ($section ne '' ? $section : 'none');
  626: 	if (&canview($section)) {
  627: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  628: 		$sections{$section}++;
  629: 		if ($classlist->{$student}) {
  630: 		    $fullnames{$student}=$fullname;
  631: 		}
  632: 	    } else {
  633: 		delete($classlist->{$student});
  634: 	    }
  635: 	} else {
  636: 	    delete($classlist->{$student});
  637: 	}
  638:     }
  639:     my @sections = sort(keys(%sections));
  640:     return ($classlist,\@sections,\%fullnames);
  641: }
  642: 
  643: sub canmodify {
  644:     my ($sec)=@_;
  645:     if ($perm{'mgr'}) {
  646: 	if (!defined($perm{'mgr_section'})) {
  647: 	    # can modify whole class
  648: 	    return 1;
  649: 	} else {
  650: 	    if ($sec eq $perm{'mgr_section'}) {
  651: 		#can modify the requested section
  652: 		return 1;
  653: 	    } else {
  654: 		# can't modify the request section
  655: 		return 0;
  656: 	    }
  657: 	}
  658:     }
  659:     #can't modify
  660:     return 0;
  661: }
  662: 
  663: sub canview {
  664:     my ($sec)=@_;
  665:     if ($perm{'vgr'}) {
  666: 	if (!defined($perm{'vgr_section'})) {
  667: 	    # can modify whole class
  668: 	    return 1;
  669: 	} else {
  670: 	    if ($sec eq $perm{'vgr_section'}) {
  671: 		#can modify the requested section
  672: 		return 1;
  673: 	    } else {
  674: 		# can't modify the request section
  675: 		return 0;
  676: 	    }
  677: 	}
  678:     }
  679:     #can't modify
  680:     return 0;
  681: }
  682: 
  683: #--- Retrieve the grade status of a student for all the parts
  684: sub student_gradeStatus {
  685:     my ($symb,$udom,$uname,$partlist) = @_;
  686:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  687:     my %partstatus = ();
  688:     foreach (@$partlist) {
  689: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  690: 	$status              = 'nothing' if ($status eq '');
  691: 	$partstatus{$_}      = $status;
  692: 	my $subkey           = "resource.$_.submitted_by";
  693: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  694:     }
  695:     return %partstatus;
  696: }
  697: 
  698: # hidden form and javascript that calls the form
  699: # Use by verifyscript and viewgrades
  700: # Shows a student's view of problem and submission
  701: sub jscriptNform {
  702:     my ($symb) = @_;
  703:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  704:     my $jscript= &Apache::lonhtmlcommon::scripttag(
  705: 	'    function viewOneStudent(user,domain) {'."\n".
  706: 	'	document.onestudent.student.value = user;'."\n".
  707: 	'	document.onestudent.userdom.value = domain;'."\n".
  708: 	'	document.onestudent.submit();'."\n".
  709: 	'    }'."\n".
  710: 	"\n");
  711:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  712: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  713: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  714: 	'<input type="hidden" name="command" value="submission" />'."\n".
  715: 	'<input type="hidden" name="student" value="" />'."\n".
  716: 	'<input type="hidden" name="userdom" value="" />'."\n".
  717: 	'</form>'."\n";
  718:     return $jscript;
  719: }
  720: 
  721: 
  722: 
  723: # Given the score (as a number [0-1] and the weight) what is the final
  724: # point value? This function will round to the nearest tenth, third,
  725: # or quarter if one of those is within the tolerance of .00001.
  726: sub compute_points {
  727:     my ($score, $weight) = @_;
  728:     
  729:     my $tolerance = .00001;
  730:     my $points = $score * $weight;
  731: 
  732:     # Check for nearness to 1/x.
  733:     my $check_for_nearness = sub {
  734:         my ($factor) = @_;
  735:         my $num = ($points * $factor) + $tolerance;
  736:         my $floored_num = floor($num);
  737:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  738:             return $floored_num / $factor;
  739:         }
  740:         return $points;
  741:     };
  742: 
  743:     $points = $check_for_nearness->(10);
  744:     $points = $check_for_nearness->(3);
  745:     $points = $check_for_nearness->(4);
  746:     
  747:     return $points;
  748: }
  749: 
  750: #------------------ End of general use routines --------------------
  751: 
  752: #
  753: # Find most similar essay
  754: #
  755: 
  756: sub most_similar {
  757:     my ($uname,$udom,$symb,$uessay)=@_;
  758: 
  759:     unless ($symb) { return ''; }
  760: 
  761:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
  762: 
  763: # ignore spaces and punctuation
  764: 
  765:     $uessay=~s/\W+/ /gs;
  766: 
  767: # ignore empty submissions (occuring when only files are sent)
  768: 
  769:     unless ($uessay=~/\w+/s) { return ''; }
  770: 
  771: # these will be returned. Do not care if not at least 50 percent similar
  772:     my $limit=0.6;
  773:     my $sname='';
  774:     my $sdom='';
  775:     my $scrsid='';
  776:     my $sessay='';
  777: # go through all essays ...
  778:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
  779: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  780: # ... except the same student
  781:         next if (($tname eq $uname) && ($tdom eq $udom));
  782: 	my $tessay=$old_essays{$symb}{$tkey};
  783: 	$tessay=~s/\W+/ /gs;
  784: # String similarity gives up if not even limit
  785: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  786: # Found one
  787: 	if ($tsimilar>$limit) {
  788: 	    $limit=$tsimilar;
  789: 	    $sname=$tname;
  790: 	    $sdom=$tdom;
  791: 	    $scrsid=$tcrsid;
  792: 	    $sessay=$old_essays{$symb}{$tkey};
  793: 	}
  794:     }
  795:     if ($limit>0.6) {
  796:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  797:     } else {
  798:        return ('','','','',0);
  799:     }
  800: }
  801: 
  802: #-------------------------------------------------------------------
  803: 
  804: #------------------------------------ Receipt Verification Routines
  805: #
  806: 
  807: sub initialverifyreceipt {
  808:    my ($request,$symb) = @_;
  809:    &commonJSfunctions($request);
  810:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
  811:         &Apache::lonnet::recprefix($env{'request.course.id'}).
  812:         '-<input type="text" name="receipt" size="4" />'.
  813:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  814:         '<input type="hidden" name="command" value="verify" />'.
  815:         "</form>\n";
  816: }
  817: 
  818: #--- Check whether a receipt number is valid.---
  819: sub verifyreceipt {
  820:     my ($request,$symb)  = @_;
  821: 
  822:     my $courseid = $env{'request.course.id'};
  823:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  824: 	$env{'form.receipt'};
  825:     $receipt     =~ s/[^\-\d]//g;
  826: 
  827:     my $title.=
  828: 	'<h3><span class="LC_info">'.
  829: 	&mt('Verifying Receipt Number [_1]',$receipt).
  830: 	'</span></h3>'."\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;
  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,$symb,$submitonly) = @_;
  909: 
  910:     my $is_tool   = ($symb =~ /ext\.tool$/);
  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:     unless ($submitonly) {
  916:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  917:     }
  918: 
  919:     my $result='';
  920:     my $res_error;
  921:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
  922: 
  923:     my %js_lt = &Apache::lonlocal::texthash (
  924: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  925: 		'single'   => 'Please select the student before clicking on the Next button.',
  926: 	     );
  927:     &js_escape(\%js_lt);
  928:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
  929:     function checkSelect(checkBox) {
  930: 	var ctr=0;
  931: 	var sense="";
  932: 	if (checkBox.length > 1) {
  933: 	    for (var i=0; i<checkBox.length; i++) {
  934: 		if (checkBox[i].checked) {
  935: 		    ctr++;
  936: 		}
  937: 	    }
  938: 	    sense = '$js_lt{'multiple'}';
  939: 	} else {
  940: 	    if (checkBox.checked) {
  941: 		ctr = 1;
  942: 	    }
  943: 	    sense = '$js_lt{'single'}';
  944: 	}
  945: 	if (ctr == 0) {
  946: 	    alert(sense);
  947: 	    return false;
  948: 	}
  949: 	document.gradesub.submit();
  950:     }
  951: 
  952:     function reLoadList(formname) {
  953: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  954: 	formname.command.value = 'submission';
  955: 	formname.submit();
  956:     }
  957: LISTJAVASCRIPT
  958: 
  959:     &commonJSfunctions($request);
  960:     $request->print($result);
  961: 
  962:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  963: 	"\n";
  964: 	
  965:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  966:     unless ($is_tool) {
  967:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  968:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  969:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  970:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  971:                       .&Apache::lonhtmlcommon::row_closure();
  972:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  973:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  974:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  975:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  976:                       .&Apache::lonhtmlcommon::row_closure();
  977:     }
  978: 
  979:     my $submission_options;
  980:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  981:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  982:     $env{'form.Status'} = $saveStatus;
  983:     my %optiontext;
  984:     if ($is_tool) {
  985:         %optiontext = &Apache::lonlocal::texthash (
  986:                           lastonly => 'last transaction',
  987:                           last     => 'last transaction with details',
  988:                           datesub  => 'all transactions',
  989:                           all      => 'all transactions with details',
  990:                       );
  991:     } else {
  992:         %optiontext = &Apache::lonlocal::texthash (
  993:                           lastonly => 'last submission',
  994:                           last     => 'last submission with details',
  995:                           datesub  => 'all submissions',
  996:                           all      => 'all submissions with details',
  997:                       );
  998:     }
  999:     $submission_options.=
 1000:         '<span class="LC_nobreak">'.
 1001:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
 1002:         $optiontext{'lastonly'}.' </label></span>'."\n".
 1003:         '<span class="LC_nobreak">'.
 1004:         '<label><input type="radio" name="lastSub" value="last" /> '.
 1005:         $optiontext{'last'}.' </label></span>'."\n".
 1006:         '<span class="LC_nobreak">'.
 1007:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
 1008:         $optiontext{'datesub'}.'</label></span>'."\n".
 1009:         '<span class="LC_nobreak">'.
 1010:         '<label><input type="radio" name="lastSub" value="all" /> '.
 1011:         $optiontext{'all'}.'</label></span>';
 1012:     my $viewtitle;
 1013:     if ($is_tool) {
 1014:         $viewtitle = &mt('View Transactions');
 1015:     } else {
 1016:         $viewtitle = &mt('View Submissions');
 1017:     }
 1018:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
 1019:                   .$submission_options
 1020:                   .&Apache::lonhtmlcommon::row_closure();
 1021: 
 1022:     my $closure;
 1023:     if (($is_tool) && (exists($env{'form.Status'}))) {
 1024:         $closure = 1;
 1025:     }
 1026:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
 1027:                   .'<select name="increment">'
 1028:                   .'<option value="1">'.&mt('Whole Points').'</option>'
 1029:                   .'<option value=".5">'.&mt('Half Points').'</option>'
 1030:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
 1031:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
 1032:                   .'</select>'
 1033:                   .&Apache::lonhtmlcommon::row_closure($closure);
 1034: 
 1035:     $gradeTable .= 
 1036:         &build_section_inputs().
 1037: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1038: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1039: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1040: 
 1041:     if (exists($env{'form.Status'})) {
 1042: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
 1043:     } else {
 1044:         if ($is_tool) {
 1045:             $closure = 1;
 1046:         }
 1047:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1048:                       .&Apache::lonhtmlcommon::StatusOptions(
 1049:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1050:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1051:     }
 1052: 
 1053:     unless ($is_tool) {
 1054:         $closure = 1;
 1055:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1056:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1057:                       .&Apache::lonhtmlcommon::row_closure($closure);
 1058:     }
 1059:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
 1060:     my $regrademsg;
 1061:     if ($is_tool) {
 1062:         $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
 1063:     } else {
 1064:         $regrademsg = &mt("To view/grade/regrade 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.");
 1065:     }
 1066:     $gradeTable .= '<p>'
 1067:                   .$regrademsg."\n"
 1068:                   .'<input type="hidden" name="command" value="processGroup" />'
 1069:                   .'</p>';
 1070: 
 1071: # checkall buttons
 1072:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1073:     $gradeTable.='<input type="button" '."\n".
 1074:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1075:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1076:     $gradeTable.=&check_buttons();
 1077:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1078:     $gradeTable.= &Apache::loncommon::start_data_table().
 1079: 	&Apache::loncommon::start_data_table_header_row();
 1080:     my $loop = 0;
 1081:     while ($loop < 2) {
 1082: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1083: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1084: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1085: 	    foreach my $part (sort(@$partlist)) {
 1086: 		my $display_part=
 1087: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1088: 		$gradeTable.=
 1089: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1090: 	    }
 1091: 	} elsif ($submitonly eq 'queued') {
 1092: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1093: 	}
 1094: 	$loop++;
 1095: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1096:     }
 1097:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1098: 
 1099:     my $ctr = 0;
 1100:     foreach my $student (sort 
 1101: 			 {
 1102: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1103: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1104: 			     }
 1105: 			     return $a cmp $b;
 1106: 			 }
 1107: 			 (keys(%$fullname))) {
 1108: 	my ($uname,$udom) = split(/:/,$student);
 1109: 
 1110: 	my %status = ();
 1111: 
 1112: 	if ($submitonly eq 'queued') {
 1113: 	    my %queue_status = 
 1114: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1115: 							$udom,$uname);
 1116: 	    next if (!defined($queue_status{'gradingqueue'}));
 1117: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1118: 	}
 1119: 
 1120: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1121: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1122: 	    my $submitted = 0;
 1123: 	    my $graded = 0;
 1124: 	    my $incorrect = 0;
 1125: 	    foreach (keys(%status)) {
 1126: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1127: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1128: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1129: 		
 1130: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1131: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1132: 		    $submitted = 0;
 1133: 		    my ($part)=split(/\./,$partid);
 1134: 		    $gradeTable.='<input type="hidden" name="'.
 1135: 			$student.':'.$part.':submitted_by" value="'.
 1136: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1137: 		}
 1138: 	    }
 1139: 	    
 1140: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1141: 				     $submitonly eq 'incorrect' ||
 1142: 				     $submitonly eq 'graded'));
 1143: 	    next if (!$graded && ($submitonly eq 'graded'));
 1144: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1145: 	}
 1146: 
 1147: 	$ctr++;
 1148: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1149:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1150: 	if ( $perm{'vgr'} eq 'F' ) {
 1151: 	    if ($ctr%2 ==1) {
 1152: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1153: 	    }
 1154: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1155:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1156:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1157: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1158: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1159: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1160: 
 1161: 	    if ($submitonly ne 'all') {
 1162: 		foreach (sort(keys(%status))) {
 1163: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1164: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1165: 		}
 1166: 	    }
 1167: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1168: 	    if ($ctr%2 ==0) {
 1169: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1170: 	    }
 1171: 	}
 1172:     }
 1173:     if ($ctr%2 ==1) {
 1174: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1175: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
 1176: 		foreach (@$partlist) {
 1177: 		    $gradeTable.='<td>&nbsp;</td>';
 1178: 		}
 1179: 	    } elsif ($submitonly eq 'queued') {
 1180: 		$gradeTable.='<td>&nbsp;</td>';
 1181: 	    }
 1182: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1183:     }
 1184: 
 1185:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1186:         '<input type="button" '.
 1187:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1188:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1189:     if ($ctr == 0) {
 1190: 	my $num_students=(scalar(keys(%$fullname)));
 1191: 	if ($num_students eq 0) {
 1192: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1193: 	} else {
 1194: 	    my $submissions='submissions';
 1195: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1196: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1197: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1198: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1199: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
 1200: 		    $num_students).
 1201: 		'</span><br />';
 1202: 	}
 1203:     } elsif ($ctr == 1) {
 1204: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1205:     }
 1206:     $request->print($gradeTable);
 1207:     return '';
 1208: }
 1209: 
 1210: #---- Called from the listStudents routine
 1211: 
 1212: sub check_script {
 1213:     my ($form, $type)=@_;
 1214:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
 1215:     function checkall() {
 1216:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1217:             ele = document.forms.'.$form.'.elements[i];
 1218:             if (ele.name == "'.$type.'") {
 1219:             document.forms.'.$form.'.elements[i].checked=true;
 1220:                                        }
 1221:         }
 1222:     }
 1223: 
 1224:     function checksec() {
 1225:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1226:             ele = document.forms.'.$form.'.elements[i];
 1227:            string = document.forms.'.$form.'.chksec.value;
 1228:            if
 1229:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1230:               document.forms.'.$form.'.elements[i].checked=true;
 1231:             }
 1232:         }
 1233:     }
 1234: 
 1235: 
 1236:     function uncheckall() {
 1237:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1238:             ele = document.forms.'.$form.'.elements[i];
 1239:             if (ele.name == "'.$type.'") {
 1240:             document.forms.'.$form.'.elements[i].checked=false;
 1241:                                        }
 1242:         }
 1243:     }
 1244: 
 1245: '."\n");
 1246:     return $chkallscript;
 1247: }
 1248: 
 1249: sub check_buttons {
 1250:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1251:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1252:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1253:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1254:     return $buttons;
 1255: }
 1256: 
 1257: #     Displays the submissions for one student or a group of students
 1258: sub processGroup {
 1259:     my ($request,$symb)  = @_;
 1260:     my $ctr        = 0;
 1261:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1262:     my $total      = scalar(@stuchecked)-1;
 1263: 
 1264:     foreach my $student (@stuchecked) {
 1265: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1266: 	$env{'form.student'}        = $uname;
 1267: 	$env{'form.userdom'}        = $udom;
 1268: 	$env{'form.fullname'}       = $fullname;
 1269: 	&submission($request,$ctr,$total,$symb);
 1270: 	$ctr++;
 1271:     }
 1272:     return '';
 1273: }
 1274: 
 1275: #------------------------------------------------------------------------------------
 1276: #
 1277: #-------------------------- Next few routines handles grading by student, essentially
 1278: #                           handles essay response type problem/part
 1279: #
 1280: #--- Javascript to handle the submission page functionality ---
 1281: sub sub_page_js {
 1282:     my $request = shift;
 1283:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1284:     &js_escape(\$alertmsg);
 1285:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1286:     function updateRadio(formname,id,weight) {
 1287: 	var gradeBox = formname["GD_BOX"+id];
 1288: 	var radioButton = formname["RADVAL"+id];
 1289: 	var oldpts = formname["oldpts"+id].value;
 1290: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1291: 	gradeBox.value = pts;
 1292: 	var resetbox = false;
 1293: 	if (isNaN(pts) || pts < 0) {
 1294: 	    alert("$alertmsg"+pts);
 1295: 	    for (var i=0; i<radioButton.length; i++) {
 1296: 		if (radioButton[i].checked) {
 1297: 		    gradeBox.value = i;
 1298: 		    resetbox = true;
 1299: 		}
 1300: 	    }
 1301: 	    if (!resetbox) {
 1302: 		formtextbox.value = "";
 1303: 	    }
 1304: 	    return;
 1305: 	}
 1306: 
 1307: 	if (pts > weight) {
 1308: 	    var resp = confirm("You entered a value ("+pts+
 1309: 			       ") greater than the weight for the part. Accept?");
 1310: 	    if (resp == false) {
 1311: 		gradeBox.value = oldpts;
 1312: 		return;
 1313: 	    }
 1314: 	}
 1315: 
 1316: 	for (var i=0; i<radioButton.length; i++) {
 1317: 	    radioButton[i].checked=false;
 1318: 	    if (pts == i && pts != "") {
 1319: 		radioButton[i].checked=true;
 1320: 	    }
 1321: 	}
 1322: 	updateSelect(formname,id);
 1323: 	formname["stores"+id].value = "0";
 1324:     }
 1325: 
 1326:     function writeBox(formname,id,pts) {
 1327: 	var gradeBox = formname["GD_BOX"+id];
 1328: 	if (checkSolved(formname,id) == 'update') {
 1329: 	    gradeBox.value = pts;
 1330: 	} else {
 1331: 	    var oldpts = formname["oldpts"+id].value;
 1332: 	    gradeBox.value = oldpts;
 1333: 	    var radioButton = formname["RADVAL"+id];
 1334: 	    for (var i=0; i<radioButton.length; i++) {
 1335: 		radioButton[i].checked=false;
 1336: 		if (i == oldpts) {
 1337: 		    radioButton[i].checked=true;
 1338: 		}
 1339: 	    }
 1340: 	}
 1341: 	formname["stores"+id].value = "0";
 1342: 	updateSelect(formname,id);
 1343: 	return;
 1344:     }
 1345: 
 1346:     function clearRadBox(formname,id) {
 1347: 	if (checkSolved(formname,id) == 'noupdate') {
 1348: 	    updateSelect(formname,id);
 1349: 	    return;
 1350: 	}
 1351: 	gradeSelect = formname["GD_SEL"+id];
 1352: 	for (var i=0; i<gradeSelect.length; i++) {
 1353: 	    if (gradeSelect[i].selected) {
 1354: 		var selectx=i;
 1355: 	    }
 1356: 	}
 1357: 	var stores = formname["stores"+id];
 1358: 	if (selectx == stores.value) { return };
 1359: 	var gradeBox = formname["GD_BOX"+id];
 1360: 	gradeBox.value = "";
 1361: 	var radioButton = formname["RADVAL"+id];
 1362: 	for (var i=0; i<radioButton.length; i++) {
 1363: 	    radioButton[i].checked=false;
 1364: 	}
 1365: 	stores.value = selectx;
 1366:     }
 1367: 
 1368:     function checkSolved(formname,id) {
 1369: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1370: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1371: 	    if (!reply) {return "noupdate";}
 1372: 	    formname.overRideScore.value = 'yes';
 1373: 	}
 1374: 	return "update";
 1375:     }
 1376: 
 1377:     function updateSelect(formname,id) {
 1378: 	formname["GD_SEL"+id][0].selected = true;
 1379: 	return;
 1380:     }
 1381: 
 1382: //=========== Check that a point is assigned for all the parts  ============
 1383:     function checksubmit(formname,val,total,parttot) {
 1384: 	formname.gradeOpt.value = val;
 1385: 	if (val == "Save & Next") {
 1386: 	    for (i=0;i<=total;i++) {
 1387: 		for (j=0;j<parttot;j++) {
 1388: 		    var partid = formname["partid"+i+"_"+j].value;
 1389: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1390: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1391: 			if (points == "") {
 1392: 			    var name = formname["name"+i].value;
 1393: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1394: 			    var resp = confirm("You did not assign a score for "+studentID+
 1395: 					       ", part "+partid+". Continue?");
 1396: 			    if (resp == false) {
 1397: 				formname["GD_BOX"+i+"_"+partid].focus();
 1398: 				return false;
 1399: 			    }
 1400: 			}
 1401: 		    }
 1402: 		}
 1403: 	    }
 1404: 	}
 1405: 	formname.submit();
 1406:     }
 1407: 
 1408: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1409:     function checkSubmitPage(formname,total) {
 1410: 	noscore = new Array(100);
 1411: 	var ptr = 0;
 1412: 	for (i=1;i<total;i++) {
 1413: 	    var partid = formname["q_"+i].value;
 1414: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1415: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1416: 		var status = formname["solved"+i+"_"+partid].value;
 1417: 		if (points == "" && status != "correct_by_student") {
 1418: 		    noscore[ptr] = i;
 1419: 		    ptr++;
 1420: 		}
 1421: 	    }
 1422: 	}
 1423: 	if (ptr != 0) {
 1424: 	    var sense = ptr == 1 ? ": " : "s: ";
 1425: 	    var prolist = "";
 1426: 	    if (ptr == 1) {
 1427: 		prolist = noscore[0];
 1428: 	    } else {
 1429: 		var i = 0;
 1430: 		while (i < ptr-1) {
 1431: 		    prolist += noscore[i]+", ";
 1432: 		    i++;
 1433: 		}
 1434: 		prolist += "and "+noscore[i];
 1435: 	    }
 1436: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1437: 	    if (resp == false) {
 1438: 		return false;
 1439: 	    }
 1440: 	}
 1441: 
 1442: 	formname.submit();
 1443:     }
 1444: SUBJAVASCRIPT
 1445: }
 1446: 
 1447: #--- javascript for essay type problem --
 1448: sub sub_page_kw_js {
 1449:     my $request = shift;
 1450:     my $iconpath = $request->dir_config('lonIconsURL');
 1451:     &commonJSfunctions($request);
 1452: 
 1453:     my $inner_js_msg_central= (<<INNERJS);
 1454: <script type="text/javascript">
 1455:     function checkInput() {
 1456:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1457:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1458:       var usrctr = document.msgcenter.usrctr.value;
 1459:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1460:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1461: 
 1462:       var msgchk = "";
 1463:       if (document.msgcenter.subchk.checked) {
 1464:          msgchk = "msgsub,";
 1465:       }
 1466:       var includemsg = 0;
 1467:       for (var i=1; i<=nmsg; i++) {
 1468:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1469:           var frmmsg = document.msgcenter["msg"+i];
 1470:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1471:           var showflg = opener.document.SCORE["shownOnce"+i];
 1472:           showflg.value = "1";
 1473:           var chkbox = document.msgcenter["msgn"+i];
 1474:           if (chkbox.checked) {
 1475:              msgchk += "savemsg"+i+",";
 1476:              includemsg = 1;
 1477:           }
 1478:       }
 1479:       if (document.msgcenter.newmsgchk.checked) {
 1480:          msgchk += "newmsg"+usrctr;
 1481:          includemsg = 1;
 1482:       }
 1483:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1484:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1485:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1486:       includemsg.value = msgchk;
 1487: 
 1488:       self.close()
 1489: 
 1490:     }
 1491: </script>
 1492: INNERJS
 1493: 
 1494:     my $inner_js_highlight_central= (<<INNERJS);
 1495: <script type="text/javascript">
 1496:     function updateChoice(flag) {
 1497:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1498:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1499:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1500:       opener.document.SCORE.refresh.value = "on";
 1501:       if (opener.document.SCORE.keywords.value!=""){
 1502:          opener.document.SCORE.submit();
 1503:       }
 1504:       self.close()
 1505:     }
 1506: </script>
 1507: INNERJS
 1508: 
 1509:     my $start_page_msg_central = 
 1510:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1511: 				       {'js_ready'  => 1,
 1512: 					'only_body' => 1,
 1513: 					'bgcolor'   =>'#FFFFFF',});
 1514:     my $end_page_msg_central = 
 1515: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1516: 
 1517: 
 1518:     my $start_page_highlight_central = 
 1519:         &Apache::loncommon::start_page('Highlight Central',
 1520: 				       $inner_js_highlight_central,
 1521: 				       {'js_ready'  => 1,
 1522: 					'only_body' => 1,
 1523: 					'bgcolor'   =>'#FFFFFF',});
 1524:     my $end_page_highlight_central = 
 1525: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1526: 
 1527:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1528:     $docopen=~s/^document\.//;
 1529:     my %js_lt = &Apache::lonlocal::texthash(
 1530:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
 1531:                 plse => 'Please select a word or group of words from document and then click this link.',
 1532:                 adds => 'Add selection to keyword list? Edit if desired.',
 1533:                 col1 => 'red',
 1534:                 col2 => 'green',
 1535:                 col3 => 'blue',
 1536:                 siz1 => 'normal',
 1537:                 siz2 => '+1',
 1538:                 siz3 => '+2',
 1539:                 sty1 => 'normal',
 1540:                 sty2 => 'italic',
 1541:                 sty3 => 'bold',
 1542:              );
 1543:     my %html_js_lt = &Apache::lonlocal::texthash(
 1544:                 comp => 'Compose Message for: ',
 1545:                 incl => 'Include',
 1546:                 type => 'Type',
 1547:                 subj => 'Subject',
 1548:                 mesa => 'Message',
 1549:                 new  => 'New',
 1550:                 save => 'Save',
 1551:                 canc => 'Cancel',
 1552:                 kehi => 'Keyword Highlight Options',
 1553:                 txtc => 'Text Color',
 1554:                 font => 'Font Size',
 1555:                 fnst => 'Font Style',
 1556:              );
 1557:     &js_escape(\%js_lt);
 1558:     &html_escape(\%html_js_lt);
 1559:     &js_escape(\%html_js_lt);
 1560:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
 1561: 
 1562: //===================== Show list of keywords ====================
 1563:   function keywords(formname) {
 1564:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
 1565:     if (nret==null) return;
 1566:     formname.keywords.value = nret;
 1567: 
 1568:     if (formname.keywords.value != "") {
 1569: 	formname.refresh.value = "on";
 1570: 	formname.submit();
 1571:     }
 1572:     return;
 1573:   }
 1574: 
 1575: //===================== Script to view submitted by ==================
 1576:   function viewSubmitter(submitter) {
 1577:     document.SCORE.refresh.value = "on";
 1578:     document.SCORE.NCT.value = "1";
 1579:     document.SCORE.unamedom0.value = submitter;
 1580:     document.SCORE.submit();
 1581:     return;
 1582:   }
 1583: 
 1584: //===================== Script to add keyword(s) ==================
 1585:   function getSel() {
 1586:     if (document.getSelection) txt = document.getSelection();
 1587:     else if (document.selection) txt = document.selection.createRange().text;
 1588:     else return;
 1589:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1590:     if (cleantxt=="") {
 1591: 	alert("$js_lt{'plse'}");
 1592: 	return;
 1593:     }
 1594:     var nret = prompt("$js_lt{'adds'}",cleantxt);
 1595:     if (nret==null) return;
 1596:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1597:     if (document.SCORE.keywords.value != "") {
 1598: 	document.SCORE.refresh.value = "on";
 1599: 	document.SCORE.submit();
 1600:     }
 1601:     return;
 1602:   }
 1603: 
 1604: //====================== Script for composing message ==============
 1605:    // preload images
 1606:    img1 = new Image();
 1607:    img1.src = "$iconpath/mailbkgrd.gif";
 1608:    img2 = new Image();
 1609:    img2.src = "$iconpath/mailto.gif";
 1610: 
 1611:   function msgCenter(msgform,usrctr,fullname) {
 1612:     var Nmsg  = msgform.savemsgN.value;
 1613:     savedMsgHeader(Nmsg,usrctr,fullname);
 1614:     var subject = msgform.msgsub.value;
 1615:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1616:     re = /msgsub/;
 1617:     var shwsel = "";
 1618:     if (re.test(msgchk)) { shwsel = "checked" }
 1619:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1620:     displaySubject(checkEntities(subject),shwsel);
 1621:     for (var i=1; i<=Nmsg; i++) {
 1622: 	var testmsg = "savemsg"+i+",";
 1623: 	re = new RegExp(testmsg,"g");
 1624: 	shwsel = "";
 1625: 	if (re.test(msgchk)) { shwsel = "checked" }
 1626: 	var message = document.SCORE["savemsg"+i].value;
 1627: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1628: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1629: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1630:     }
 1631:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1632:     shwsel = "";
 1633:     re = /newmsg/;
 1634:     if (re.test(msgchk)) { shwsel = "checked" }
 1635:     newMsg(newmsg,shwsel);
 1636:     msgTail(); 
 1637:     return;
 1638:   }
 1639: 
 1640:   function checkEntities(strx) {
 1641:     if (strx.length == 0) return strx;
 1642:     var orgStr = ["&", "<", ">", '"']; 
 1643:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1644:     var counter = 0;
 1645:     while (counter < 4) {
 1646: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1647: 	counter++;
 1648:     }
 1649:     return strx;
 1650:   }
 1651: 
 1652:   function strReplace(strx, orgStr, newStr) {
 1653:     return strx.split(orgStr).join(newStr);
 1654:   }
 1655: 
 1656:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1657:     var height = 70*Nmsg+250;
 1658:     if (height > 600) {
 1659: 	height = 600;
 1660:     }
 1661:     var xpos = (screen.width-600)/2;
 1662:     xpos = (xpos < 0) ? '0' : xpos;
 1663:     var ypos = (screen.height-height)/2-30;
 1664:     ypos = (ypos < 0) ? '0' : ypos;
 1665: 
 1666:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
 1667:     pWin.focus();
 1668:     pDoc = pWin.document;
 1669:     pDoc.$docopen;
 1670:     pDoc.write('$start_page_msg_central');
 1671: 
 1672:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1673:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1674:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
 1675: 
 1676:     pDoc.write('<table style="border:1px solid black;"><tr>');
 1677:     pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
 1678: }
 1679:     function displaySubject(msg,shwsel) {
 1680:     pDoc = pWin.document;
 1681:     pDoc.write("<tr>");
 1682:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1683:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
 1684:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1685: }
 1686: 
 1687:   function displaySavedMsg(ctr,msg,shwsel) {
 1688:     pDoc = pWin.document;
 1689:     pDoc.write("<tr>");
 1690:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1691:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1692:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1693: }
 1694: 
 1695:   function newMsg(newmsg,shwsel) {
 1696:     pDoc = pWin.document;
 1697:     pDoc.write("<tr>");
 1698:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1699:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
 1700:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1701: }
 1702: 
 1703:   function msgTail() {
 1704:     pDoc = pWin.document;
 1705:     //pDoc.write("<\\/table>");
 1706:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1707:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1708:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
 1709:     pDoc.write("<\\/form>");
 1710:     pDoc.write('$end_page_msg_central');
 1711:     pDoc.close();
 1712: }
 1713: 
 1714: //====================== Script for keyword highlight options ==============
 1715:   function kwhighlight() {
 1716:     var kwclr    = document.SCORE.kwclr.value;
 1717:     var kwsize   = document.SCORE.kwsize.value;
 1718:     var kwstyle  = document.SCORE.kwstyle.value;
 1719:     var redsel = "";
 1720:     var grnsel = "";
 1721:     var blusel = "";
 1722:     var txtcol1 = "$js_lt{'col1'}";
 1723:     var txtcol2 = "$js_lt{'col2'}";
 1724:     var txtcol3 = "$js_lt{'col3'}";
 1725:     var txtsiz1 = "$js_lt{'siz1'}";
 1726:     var txtsiz2 = "$js_lt{'siz2'}";
 1727:     var txtsiz3 = "$js_lt{'siz3'}";
 1728:     var txtsty1 = "$js_lt{'sty1'}";
 1729:     var txtsty2 = "$js_lt{'sty2'}";
 1730:     var txtsty3 = "$js_lt{'sty3'}";
 1731:     if (kwclr=="red")   {var redsel="checked='checked'"};
 1732:     if (kwclr=="green") {var grnsel="checked='checked'"};
 1733:     if (kwclr=="blue")  {var blusel="checked='checked'"};
 1734:     var sznsel = "";
 1735:     var sz1sel = "";
 1736:     var sz2sel = "";
 1737:     if (kwsize=="0")  {var sznsel="checked='checked'"};
 1738:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
 1739:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
 1740:     var synsel = "";
 1741:     var syisel = "";
 1742:     var sybsel = "";
 1743:     if (kwstyle=="")    {var synsel="checked='checked'"};
 1744:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
 1745:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
 1746:     highlightCentral();
 1747:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
 1748:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
 1749:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
 1750:     highlightend();
 1751:     return;
 1752:   }
 1753: 
 1754:   function highlightCentral() {
 1755: //    if (window.hwdWin) window.hwdWin.close();
 1756:     var xpos = (screen.width-400)/2;
 1757:     xpos = (xpos < 0) ? '0' : xpos;
 1758:     var ypos = (screen.height-330)/2-30;
 1759:     ypos = (ypos < 0) ? '0' : ypos;
 1760: 
 1761:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1762:     hwdWin.focus();
 1763:     var hDoc = hwdWin.document;
 1764:     hDoc.$docopen;
 1765:     hDoc.write('$start_page_highlight_central');
 1766:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1767:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
 1768: 
 1769:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
 1770:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
 1771:   }
 1772: 
 1773:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1774:     var hDoc = hwdWin.document;
 1775:     hDoc.write("<tr>");
 1776:     hDoc.write("<td align=\\"left\\">");
 1777:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
 1778:     hDoc.write("<td align=\\"left\\">");
 1779:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
 1780:     hDoc.write("<td align=\\"left\\">");
 1781:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
 1782:     hDoc.write("<\\/tr>");
 1783:   }
 1784: 
 1785:   function highlightend() { 
 1786:     var hDoc = hwdWin.document;
 1787:     hDoc.write("<\\/table><br \\/>");
 1788:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
 1789:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
 1790:     hDoc.write("<\\/form>");
 1791:     hDoc.write('$end_page_highlight_central');
 1792:     hDoc.close();
 1793:   }
 1794: 
 1795: SUBJAVASCRIPT
 1796: }
 1797: 
 1798: sub get_increment {
 1799:     my $increment = $env{'form.increment'};
 1800:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1801:         $increment != .1) {
 1802:         $increment = 1;
 1803:     }
 1804:     return $increment;
 1805: }
 1806: 
 1807: sub gradeBox_start {
 1808:     return (
 1809:         &Apache::loncommon::start_data_table()
 1810:        .&Apache::loncommon::start_data_table_header_row()
 1811:        .'<th>'.&mt('Part').'</th>'
 1812:        .'<th>'.&mt('Points').'</th>'
 1813:        .'<th>&nbsp;</th>'
 1814:        .'<th>'.&mt('Assign Grade').'</th>'
 1815:        .'<th>'.&mt('Weight').'</th>'
 1816:        .'<th>'.&mt('Grade Status').'</th>'
 1817:        .&Apache::loncommon::end_data_table_header_row()
 1818:     );
 1819: }
 1820: 
 1821: sub gradeBox_end {
 1822:     return (
 1823:         &Apache::loncommon::end_data_table()
 1824:     );
 1825: }
 1826: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1827: sub gradeBox {
 1828:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1829:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1830: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1831:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1832:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1833:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1834:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1835:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1836: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1837:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1838:     my $display_part= &get_display_part($partid,$symb);
 1839:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1840: 				       [$partid]);
 1841:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1842:     if ($last_resets{$partid}) {
 1843:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1844:     }
 1845:     my $result=&Apache::loncommon::start_data_table_row();
 1846:     my $ctr = 0;
 1847:     my $thisweight = 0;
 1848:     my $increment = &get_increment();
 1849: 
 1850:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1851:     while ($thisweight<=$wgt) {
 1852: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1853:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1854: 	    $thisweight.')" value="'.$thisweight.'" '.
 1855: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1856: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1857:         $thisweight += $increment;
 1858: 	$ctr++;
 1859:     }
 1860:     $radio.='</tr></table>';
 1861: 
 1862:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1863: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1864: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1865: 	$wgt.')" /></td>'."\n";
 1866:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1867: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1868: 	' </td>'."\n";
 1869:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1870: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1871:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1872: 	$line.='<option></option>'.
 1873: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1874:     } else {
 1875: 	$line.='<option selected="selected"></option>'.
 1876: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1877:     }
 1878:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1879: 
 1880: 
 1881:     $result .= 
 1882: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1883:     $result.=&Apache::loncommon::end_data_table_row();
 1884:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
 1885:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1886: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1887: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1888: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1889:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1890:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1891:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1892:         $aggtries.'" />'."\n";
 1893:     my $res_error;
 1894:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1895:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
 1896:     if ($res_error) {
 1897:         return &navmap_errormsg();
 1898:     }
 1899:     return $result;
 1900: }
 1901: 
 1902: sub handback_box {
 1903:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
 1904:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
 1905:     my (@respids);
 1906:     my @part_response_id = &flatten_responseType($responseType);
 1907:     foreach my $part_response_id (@part_response_id) {
 1908:     	my ($part,$resp) = @{ $part_response_id };
 1909:         if ($part eq $partid) {
 1910:             push(@respids,$resp);
 1911:         }
 1912:     }
 1913:     my $result;
 1914:     foreach my $respid (@respids) {
 1915: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1916: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1917: 	next if (!@$files);
 1918: 	my $file_counter = 0;
 1919: 	foreach my $file (@$files) {
 1920: 	    if ($file =~ /\/portfolio\//) {
 1921:                 $file_counter++;
 1922:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1923:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
 1924:     	        $file_disp = "$name.$ext";
 1925:     	        $file = $file_path.$file_disp;
 1926:     	        $result.=&mt('Return commented version of [_1] to student.',
 1927:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1928:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1929:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
 1930: 	    }
 1931: 	}
 1932:         if ($file_counter) {
 1933:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
 1934:                        '<span class="LC_info">'.
 1935:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
 1936:         }
 1937:     }
 1938:     return $result;    
 1939: }
 1940: 
 1941: sub show_problem {
 1942:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1943:     my $rendered;
 1944:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1945:     &Apache::lonxml::remember_problem_counter();
 1946:     if ($mode eq 'both' or $mode eq 'text') {
 1947: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1948: 						       $env{'request.course.id'},
 1949: 						       undef,\%form);
 1950:     }
 1951:     if ($removeform) {
 1952: 	$rendered=~s|<form(.*?)>||g;
 1953: 	$rendered=~s|</form>||g;
 1954: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1955:     }
 1956:     my $companswer;
 1957:     if ($mode eq 'both' or $mode eq 'answer') {
 1958: 	&Apache::lonxml::restore_problem_counter();
 1959: 	$companswer=
 1960: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1961: 						    $env{'request.course.id'},
 1962: 						    %form);
 1963:     }
 1964:     if ($removeform) {
 1965: 	$companswer=~s|<form(.*?)>||g;
 1966: 	$companswer=~s|</form>||g;
 1967: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1968:     }
 1969:     my $renderheading = &mt('View of the problem');
 1970:     my $answerheading = &mt('Correct answer');
 1971:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 1972:         my $stu_fullname = $env{'form.fullname'};
 1973:         if ($stu_fullname eq '') {
 1974:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 1975:         }
 1976:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
 1977:         if ($forwhom ne '') {
 1978:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
 1979:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
 1980:         }
 1981:     }
 1982:     $rendered=
 1983:         '<div class="LC_Box">'
 1984:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
 1985:        .$rendered
 1986:        .'</div>';
 1987:     $companswer=
 1988:         '<div class="LC_Box">'
 1989:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
 1990:        .$companswer
 1991:        .'</div>';
 1992:     my $result;
 1993:     if ($mode eq 'both') {
 1994:         $result=$rendered.$companswer;
 1995:     } elsif ($mode eq 'text') {
 1996:         $result=$rendered;
 1997:     } elsif ($mode eq 'answer') {
 1998:         $result=$companswer;
 1999:     }
 2000:     return $result;
 2001: }
 2002: 
 2003: sub files_exist {
 2004:     my ($r, $symb) = @_;
 2005:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 2006:     foreach my $student (@students) {
 2007:         my ($uname,$udom,$fullname) = split(/:/,$student);
 2008:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2009: 					      $udom,$uname);
 2010:         my ($string,$timestamp)= &get_last_submission(\%record);
 2011:         foreach my $submission (@$string) {
 2012:             my ($partid,$respid) =
 2013: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2014:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 2015: 					   \%record);
 2016:             return 1 if (@$files);
 2017:         }
 2018:     }
 2019:     return 0;
 2020: }
 2021: 
 2022: sub download_all_link {
 2023:     my ($r,$symb) = @_;
 2024:     unless (&files_exist($r, $symb)) {
 2025:        $r->print(&mt('There are currently no submitted documents.'));
 2026:        return;
 2027:     }
 2028:     my $all_students = 
 2029: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 2030: 
 2031:     my $parts =
 2032: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 2033: 
 2034:     my $identifier = &Apache::loncommon::get_cgi_id();
 2035:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 2036:                              'cgi.'.$identifier.'.symb' => $symb,
 2037:                              'cgi.'.$identifier.'.parts' => $parts,});
 2038:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 2039: 	      &mt('Download All Submitted Documents').'</a>');
 2040:     return;
 2041: }
 2042: 
 2043: sub submit_download_link {
 2044:     my ($request,$symb) = @_;
 2045:     if (!$symb) { return ''; }
 2046: #FIXME: Figure out which type of problem this is and provide appropriate download
 2047:     my $res_error;
 2048:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 2049:     if (ref($res_error)) {
 2050:         if ($$res_error) {
 2051:             $request->print(&mt('An error occurred retrieving response types'));
 2052:             return;
 2053:         }
 2054:     }
 2055:     my ($numupload,$numessay) = (0,0);
 2056:     if (ref($responseType) eq 'HASH') {
 2057:         foreach my $part (sort(keys(%$responseType))) {
 2058:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
 2059:                 my $responsetype = $responseType->{$part}->{$id};
 2060:                 if ($responsetype eq 'essay') {
 2061:                     my $uploadedfiletypes =
 2062:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
 2063:                     if ($uploadedfiletypes) {
 2064:                         $numupload++;
 2065:                     } else {
 2066:                         $numessay++;
 2067:                     }
 2068:                 }
 2069:             }
 2070:         }
 2071:     }
 2072:     if (($numupload) || ($numessay)) {
 2073:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
 2074:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 2075:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
 2076:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
 2077:         if (ref($fullname) eq 'HASH') {
 2078:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
 2079:             if (@students) {
 2080:                 @{$env{'form.stuinfo'}} = @students;
 2081:                 if ($numupload) {
 2082:                     &download_all_link($request,$symb);
 2083:                 }
 2084: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
 2085: # Needs to omit user's identity if resource instance is for an anonymous survey.
 2086:             } else {
 2087:                 $request->print(&mt('No students match the criteria you selected'));
 2088:             }
 2089:         } else {
 2090:             $request->print(&mt('Could not retrieve student information'));
 2091:         }
 2092:     } else {
 2093:         $request->print(&mt('No essayresponse items found'));
 2094:     }
 2095:     return;
 2096: }
 2097: 
 2098: sub build_section_inputs {
 2099:     my $section_inputs;
 2100:     if ($env{'form.section'} eq '') {
 2101:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 2102:     } else {
 2103:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 2104:         foreach my $section (@sections) {
 2105:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 2106:         }
 2107:     }
 2108:     return $section_inputs;
 2109: }
 2110: 
 2111: # --------------------------- show submissions of a student, option to grade 
 2112: sub submission {
 2113:     my ($request,$counter,$total,$symb) = @_;
 2114:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2115:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2116:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2117:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2118: 
 2119:     my $probtitle=&Apache::lonnet::gettitle($symb); 
 2120:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2121:     my $is_tool = ($symb =~ /ext\.tool$/);
 2122: 
 2123:     if (!&canview($usec)) {
 2124:         $request->print(
 2125:             '<span class="LC_warning">'.
 2126:             &mt('Unable to view requested student.').
 2127:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2128:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2129:             '</span>');
 2130: 	return;
 2131:     }
 2132: 
 2133:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2134:     unless ($is_tool) { 
 2135:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2136:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2137:     }
 2138:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2139:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2140: 	'" src="'.$request->dir_config('lonIconsURL').
 2141: 	'/check.gif" height="16" border="0" />';
 2142: 
 2143:     # header info
 2144:     if ($counter == 0) {
 2145: 	&sub_page_js($request);
 2146: 	&sub_page_kw_js($request);
 2147: 
 2148: 	# option to display problem, only once else it cause problems 
 2149:         # with the form later since the problem has a form.
 2150: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2151: 	    my $mode;
 2152: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2153: 		$mode='both';
 2154: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2155: 		$mode='text';
 2156: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2157: 		$mode='answer';
 2158: 	    }
 2159: 	    &Apache::lonxml::clear_problem_counter();
 2160: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2161: 	}
 2162: 
 2163: 	# kwclr is the only variable that is guaranteed not to be blank 
 2164:         # if this subroutine has been called once.
 2165: 	my %keyhash = ();
 2166: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2167:         if (1) {
 2168: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2169: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2170: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2171: 
 2172: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2173: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2174: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2175: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2176: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2177: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2178: 		$keyhash{$symb.'_subject'} : $probtitle;
 2179: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2180: 	}
 2181: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2182: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2183: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2184: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2185: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2186: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2187: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2188: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2189: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2190: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2191: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2192: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2193: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2194: 			&build_section_inputs().
 2195: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2196: 			'<input type="hidden" name="NCT"'.
 2197: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2198: #	if ($env{'form.handgrade'} eq 'yes') {
 2199:         if (1) {
 2200: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2201: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2202: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2203: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2204: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2205: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2206: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2207: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2208: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2209: 	    }
 2210: 	}
 2211: 	
 2212: 	my ($cts,$prnmsg) = (1,'');
 2213: 	while ($cts <= $env{'form.savemsgN'}) {
 2214: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2215: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2216: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2217: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2218: 		'" />'."\n".
 2219: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2220: 	    $cts++;
 2221: 	}
 2222: 	$request->print($prnmsg);
 2223: 
 2224: #	if ($env{'form.handgrade'} eq 'yes') {
 2225:         unless ($is_tool) {
 2226: 
 2227:             my %lt = &Apache::lonlocal::texthash(
 2228:                           keyh => 'Keyword Highlighting for Essays',
 2229:                           keyw => 'Keyword Options',
 2230:                           list => 'List',
 2231:                           past => 'Paste Selection to List',
 2232:                           high => 'Highlight Attribute',
 2233:                      );    
 2234: #
 2235: # Print out the keyword options line
 2236: #
 2237: 	    $request->print(
 2238:                 '<div class="LC_columnSection">'
 2239:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
 2240:                .&Apache::lonhtmlcommon::funclist_from_array(
 2241:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
 2242:                      '<a href="#" onmousedown="javascript:getSel(); return false"
 2243:  class="page">'.$lt{'past'}.'</a>',
 2244:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
 2245:                     {legend => $lt{'keyw'}})
 2246:                .'</fieldset></div>'
 2247:             );
 2248: 
 2249: #
 2250: # Load the other essays for similarity check
 2251: #
 2252:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2253: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2254: 	    $apath=&escape($apath);
 2255: 	    $apath=~s/\W/\_/gs;
 2256:             &init_old_essays($symb,$apath,$adom,$aname);
 2257:         }
 2258:     }
 2259: 
 2260: # This is where output for one specific student would start
 2261:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2262:     $request->print(
 2263:         "\n\n"
 2264:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2265:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2266:        ."\n"
 2267:     );
 2268: 
 2269:     # Show additional functions if allowed
 2270:     if ($perm{'vgr'}) {
 2271:         $request->print(
 2272:             &Apache::loncommon::track_student_link(
 2273:                 'View recent activity',
 2274:                 $uname,$udom,'check')
 2275:            .' '
 2276:         );
 2277:     }
 2278:     if ($perm{'opa'}) {
 2279:         $request->print(
 2280:             &Apache::loncommon::pprmlink(
 2281:                 &mt('Set/Change parameters'),
 2282:                 $uname,$udom,$symb,'check'));
 2283:     }
 2284: 
 2285:     # Show Problem
 2286:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2287: 	my $mode;
 2288: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2289: 	    $mode='both';
 2290: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2291: 	    $mode='text';
 2292: 	} elsif ($env{'form.vAns'} eq 'all') {
 2293: 	    $mode='answer';
 2294: 	}
 2295: 	&Apache::lonxml::clear_problem_counter();
 2296: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2297:     }
 2298: 
 2299:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2300:     my $res_error;
 2301:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2302:     if ($res_error) {
 2303:         $request->print(&navmap_errormsg());
 2304:         return;
 2305:     }
 2306: 
 2307:     # Display student info
 2308:     $request->print(($counter == 0 ? '' : '<br />'));
 2309: 
 2310:     my $boxtitle = &mt('Submissions');
 2311:     if ($is_tool) {
 2312:         $boxtitle = &mt('Transactions')
 2313:     }
 2314:     my $result='<div class="LC_Box">'
 2315:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
 2316:     $result.='<input type="hidden" name="name'.$counter.
 2317:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2318: #    if ($env{'form.handgrade'} eq 'no') {
 2319:     unless ($is_tool) {
 2320:         $result.='<p class="LC_info">'
 2321:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2322:                 ."</p>\n";
 2323:     }
 2324: 
 2325:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2326:     my $fullname;
 2327:     my $col_fullnames = [];
 2328: #    if ($env{'form.handgrade'} eq 'yes') {
 2329:     unless ($is_tool) {
 2330: 	(my $sub_result,$fullname,$col_fullnames)=
 2331: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2332: 				 $counter);
 2333: 	$result.=$sub_result;
 2334:     }
 2335:     $request->print($result."\n");
 2336:     
 2337:     # print student answer/submission
 2338:     # Options are (1) Handgraded submission only
 2339:     #             (2) Last submission, includes submission that is not handgraded 
 2340:     #                  (for multi-response type part)
 2341:     #             (3) Last submission plus the parts info
 2342:     #             (4) The whole record for this student
 2343:     
 2344:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
 2345: 	
 2346:     my $lastsubonly;
 2347: 
 2348:     if ($$timestamp eq '') {
 2349:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2350:     } elsif ($is_tool) {
 2351:         $lastsubonly =
 2352:             '<div class="LC_grade_submissions_body">'
 2353:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
 2354:     } else {
 2355:         $lastsubonly =
 2356:             '<div class="LC_grade_submissions_body">'
 2357:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2358: 
 2359: 	my %seenparts;
 2360: 	my @part_response_id = &flatten_responseType($responseType);
 2361: 	foreach my $part (@part_response_id) {
 2362: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
 2363: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2364: 
 2365: 	    my ($partid,$respid) = @{ $part };
 2366: 	    my $display_part=&get_display_part($partid,$symb);
 2367: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2368: 		if (exists($seenparts{$partid})) { next; }
 2369: 		$seenparts{$partid}=1;
 2370:                 $request->print(
 2371:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2372:                     ' <b>'.&mt('Collaborative submission by: [_1]',
 2373:                                '<a href="javascript:viewSubmitter(\''.
 2374:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
 2375:                                '\');" target="_self">'.
 2376:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
 2377:                     '<br />');
 2378: 		next;
 2379: 		}
 2380: 	    my $responsetype = $responseType->{$partid}->{$respid};
 2381: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
 2382:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2383:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2384:                     ' <span class="LC_internal_info">'.
 2385:                     '('.&mt('Response ID: [_1]',$respid).')'.
 2386:                     '</span>&nbsp; &nbsp;'.
 2387: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2388: 		next;
 2389: 	    }
 2390: 	    foreach my $submission (@$string) {
 2391: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2392: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2393: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
 2394: 		# Similarity check
 2395:                 my $similar='';
 2396:                 my ($type,$trial,$rndseed);
 2397:                 if ($hide eq 'rand') {
 2398:                     $type = 'randomizetry';
 2399:                     $trial = $record{"resource.$partid.tries"};
 2400:                     $rndseed = $record{"resource.$partid.rndseed"};
 2401:                 }
 2402: 	        if ($env{'form.checkPlag'}) {
 2403:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2404: 		        &most_similar($uname,$udom,$symb,$subval);
 2405: 		    if ($osim) {
 2406: 			$osim=int($osim*100.0);
 2407: 			my %old_course_desc = 
 2408: 			    &Apache::lonnet::coursedescription($ocrsid,
 2409: 							{'one_time' => 1});
 2410: 
 2411:                         if ($hide eq 'anon') {
 2412:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2413:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2414:                         } else {
 2415: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2416: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2417: 				    $osim,
 2418: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2419: 				        $old_course_desc{'description'},
 2420: 				        $old_course_desc{'num'},
 2421: 				        $old_course_desc{'domain'}).
 2422: 				    '</span></h3><blockquote><i>'.
 2423: 				    &keywords_highlight($oessay).
 2424: 				    '</i></blockquote><hr />';
 2425:                         }
 2426: 	            }
 2427: 		}
 2428: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2429:                                      undef,$type,$trial,$rndseed);
 2430:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
 2431: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2432: 		    my $display_part=&get_display_part($partid,$symb);
 2433:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
 2434:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2435:                         ' <span class="LC_internal_info">'.
 2436:                         '('.&mt('Response ID: [_1]',$respid).')'.
 2437:                         '</span>&nbsp; &nbsp;';
 2438: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2439:                         
 2440: 		    if (@$files) {
 2441:                         if ($hide eq 'anon') {
 2442:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2443:                         } else {
 2444:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
 2445:                                         .'<br /><span class="LC_warning">';
 2446:                             if(@$files == 1) {
 2447:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
 2448:                             } else {
 2449:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
 2450:                             }
 2451:                             $lastsubonly .= '</span>';                         
 2452:                             foreach my $file (@$files) {
 2453:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2454:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
 2455:                             }
 2456:                         }
 2457: 			$lastsubonly.='<br />';
 2458:                     }
 2459:                     if ($hide eq 'anon') {
 2460:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
 2461:                     } else {
 2462:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
 2463:                         if ($draft) {
 2464:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
 2465:                         }
 2466:                         $subval =
 2467: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2468: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2469:                         if ($responsetype eq 'essay') {
 2470:                             $subval =~ s{\n}{<br />}g;
 2471:                         }
 2472:                         $lastsubonly.=$subval."\n";
 2473:                     }
 2474: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2475: 		    $lastsubonly.='</div>';
 2476: 		}
 2477:             }
 2478: 	}
 2479: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2480:     }
 2481:     $request->print($lastsubonly);
 2482:     if ($env{'form.lastSub'} eq 'datesub') {
 2483:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2484: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2485:   
 2486:     } 
 2487:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2488:         my $identifier = (&canmodify($usec)? $counter : '');
 2489:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2490: 								 $env{'request.course.id'},
 2491: 								 $last,'.submission',
 2492: 								 'Apache::grades::keywords_highlight',
 2493:                                                                  $usec,$identifier));
 2494:     }
 2495:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2496: 	.$udom.'" />'."\n");
 2497:     # return if view submission with no grading option
 2498:     if (!&canmodify($usec)) {
 2499: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
 2500: 	return;
 2501:     } else {
 2502: 	$request->print('</div>'."\n");
 2503:     }
 2504: 
 2505:     # essay grading message center
 2506: #    if ($env{'form.handgrade'} eq 'yes') {
 2507:     if (1) {
 2508: 	my $result='<div class="LC_grade_message_center">';
 2509:     
 2510: 	$result.='<div class="LC_grade_message_center_header">'.
 2511: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2512: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2513: 	my $msgfor = $givenn.' '.$lastname;
 2514: 	if (scalar(@$col_fullnames) > 0) {
 2515: 	    my $lastone = pop(@$col_fullnames);
 2516: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2517: 	}
 2518: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2519: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2520: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2521: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2522: 	    ',\''.$msgfor.'\');" target="_self">'.
 2523: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
 2524: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2525: 	    ' <img src="'.$request->dir_config('lonIconsURL').
 2526: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
 2527: 	    '<br />&nbsp;('.
 2528: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2529: 	$result.='</div></div>';
 2530: 	$request->print($result);
 2531:     }
 2532: 
 2533:     my %seen = ();
 2534:     my @partlist;
 2535:     my @gradePartRespid;
 2536:     my @part_response_id;
 2537:     if ($is_tool) {
 2538:         @part_response_id = ([0,'']);
 2539:     } else {
 2540:         @part_response_id = &flatten_responseType($responseType);
 2541:     }
 2542:     $request->print(
 2543:         '<div class="LC_Box">'
 2544:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2545:     );
 2546:     $request->print(&gradeBox_start());
 2547:     foreach my $part_response_id (@part_response_id) {
 2548:     	my ($partid,$respid) = @{ $part_response_id };
 2549: 	my $part_resp = join('_',@{ $part_response_id });
 2550: 	next if ($seen{$partid} > 0);
 2551: 	$seen{$partid}++;
 2552: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2553: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2554: 	push(@partlist,$partid);
 2555: 	push(@gradePartRespid,$partid.'.'.$respid);
 2556: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2557:     }
 2558:     $request->print(&gradeBox_end()); # </div>
 2559:     $request->print('</div>');
 2560: 
 2561:     $request->print('<div class="LC_grade_info_links">');
 2562:     $request->print('</div>');
 2563: 
 2564:     $result='<input type="hidden" name="partlist'.$counter.
 2565: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2566:     $result.='<input type="hidden" name="gradePartRespid'.
 2567: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2568:     my $ctr = 0;
 2569:     while ($ctr < scalar(@partlist)) {
 2570: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2571: 	    $partlist[$ctr].'" />'."\n";
 2572: 	$ctr++;
 2573:     }
 2574:     $request->print($result.''."\n");
 2575: 
 2576: # Done with printing info for one student
 2577: 
 2578:     $request->print('</div>');#LC_grade_show_user
 2579: 
 2580: 
 2581:     # print end of form
 2582:     if ($counter == $total) {
 2583:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2584: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2585: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2586: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2587: 	my $ntstu ='<select name="NTSTU">'.
 2588: 	    '<option>1</option><option>2</option>'.
 2589: 	    '<option>3</option><option>5</option>'.
 2590: 	    '<option>7</option><option>10</option></select>'."\n";
 2591: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2592: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2593:         $endform.=&mt('[_1]student(s)',$ntstu);
 2594: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2595: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2596: 	    '<input type="button" value="'.&mt('Next').'" '.
 2597: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2598:         $endform.='<span class="LC_warning">'.
 2599:                   &mt('(Next and Previous (student) do not save the scores.)').
 2600:                   '</span>'."\n" ;
 2601:         $endform.="<input type='hidden' value='".&get_increment().
 2602:             "' name='increment' />";
 2603: 	$endform.='</td></tr></table></form>';
 2604: 	$request->print($endform);
 2605:     }
 2606:     return '';
 2607: }
 2608: 
 2609: sub check_collaborators {
 2610:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2611:     my ($result,@col_fullnames);
 2612:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2613:     foreach my $part (keys(%$handgrade)) {
 2614: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2615: 					'.maxcollaborators',
 2616: 					$symb,$udom,$uname);
 2617: 	next if ($ncol <= 0);
 2618: 	$part =~ s/\_/\./g;
 2619: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2620: 	my (@good_collaborators, @bad_collaborators);
 2621: 	foreach my $possible_collaborator
 2622: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2623: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2624: 	    next if ($possible_collaborator eq '');
 2625: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
 2626: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2627: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2628: 	    # Doing this grep allows 'fuzzy' specification
 2629: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2630: 			       keys(%$classlist));
 2631: 	    if (! scalar(@matches)) {
 2632: 		push(@bad_collaborators, $possible_collaborator);
 2633: 	    } else {
 2634: 		push(@good_collaborators, @matches);
 2635: 	    }
 2636: 	}
 2637: 	if (scalar(@good_collaborators) != 0) {
 2638: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
 2639: 	    foreach my $name (@good_collaborators) {
 2640: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2641: 		push(@col_fullnames, $givenn.' '.$lastname);
 2642: 		$result.='<li>'.$fullname->{$name}.'</li>';
 2643: 	    }
 2644: 	    $result.='</ol><br />'."\n";
 2645: 	    my ($part)=split(/\./,$part);
 2646: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2647: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2648: 		"\n";
 2649: 	}
 2650: 	if (scalar(@bad_collaborators) > 0) {
 2651: 	    $result.='<div class="LC_warning">';
 2652: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2653: 	    $result .= '</div>';
 2654: 	}         
 2655: 	if (scalar(@bad_collaborators > $ncol)) {
 2656: 	    $result .= '<div class="LC_warning">';
 2657: 	    $result .= &mt('This student has submitted too many '.
 2658: 		'collaborators.  Maximum is [_1].',$ncol);
 2659: 	    $result .= '</div>';
 2660: 	}
 2661:     }
 2662:     return ($result,$fullname,\@col_fullnames);
 2663: }
 2664: 
 2665: #--- Retrieve the last submission for all the parts
 2666: sub get_last_submission {
 2667:     my ($returnhash,$is_tool)=@_;
 2668:     my (@string,$timestamp,%lasthidden);
 2669:     if ($$returnhash{'version'}) {
 2670: 	my %lasthash=();
 2671: 	my ($version);
 2672: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2673: 	    foreach my $key (sort(split(/\:/,
 2674: 					$$returnhash{$version.':keys'}))) {
 2675: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2676: 		$timestamp = 
 2677: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2678: 	    }
 2679: 	}
 2680:         my (%typeparts,%randombytry);
 2681:         my $showsurv = 
 2682:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2683:         foreach my $key (sort(keys(%lasthash))) {
 2684:             if ($key =~ /\.type$/) {
 2685:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2686:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2687:                     ($lasthash{$key} eq 'randomizetry')) {
 2688:                     my ($ign,@parts) = split(/\./,$key);
 2689:                     pop(@parts);
 2690:                     my $id = join('.',@parts);
 2691:                     if ($lasthash{$key} eq 'randomizetry') {
 2692:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2693:                     } else {
 2694:                         unless ($showsurv) {
 2695:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2696:                         }
 2697:                     }
 2698:                     delete($lasthash{$key});
 2699:                 }
 2700:             }
 2701:         }
 2702:         my @hidden = keys(%typeparts);
 2703:         my @randomize = keys(%randombytry);
 2704: 	foreach my $key (keys(%lasthash)) {
 2705: 	    next if ($key !~ /\.submission$/);
 2706:             my $hide;
 2707:             if (@hidden) {
 2708:                 foreach my $id (@hidden) {
 2709:                     if ($key =~ /^\Q$id\E/) {
 2710:                         $hide = 'anon';
 2711:                         last;
 2712:                     }
 2713:                 }
 2714:             }
 2715:             unless ($hide) {
 2716:                 if (@randomize) {
 2717:                     foreach my $id (@randomize) {
 2718:                         if ($key =~ /^\Q$id\E/) {
 2719:                             $hide = 'rand';
 2720:                             last;
 2721:                         }
 2722:                     }
 2723:                 }
 2724:             }
 2725: 	    my ($partid,$foo) = split(/submission$/,$key);
 2726: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
 2727:             push(@string, join(':', $key, $hide, $draft, (
 2728:                 ref($lasthash{$key}) eq 'ARRAY' ?
 2729:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
 2730: 	}
 2731:     }
 2732:     if (!@string) {
 2733:         my $msg;
 2734:         if ($is_tool) {
 2735:             $msg = &mt('No grade passed back.');
 2736:         } else {
 2737:             $msg = &mt('Nothing submitted - no attempts.');
 2738:         }
 2739: 	$string[0] =
 2740: 	    '<span class="LC_warning">'.$msg.'</span>';
 2741:     }
 2742:     return (\@string,\$timestamp);
 2743: }
 2744: 
 2745: #--- High light keywords, with style choosen by user.
 2746: sub keywords_highlight {
 2747:     my $string    = shift;
 2748:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2749:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2750:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2751:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2752:     foreach my $keyword (@keylist) {
 2753: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2754:     }
 2755:     return $string;
 2756: }
 2757: 
 2758: # For Tasks provide a mechanism to display previous version for one specific student
 2759: 
 2760: sub show_previous_task_version {
 2761:     my ($request,$symb) = @_;
 2762:     if ($symb eq '') {
 2763:         $request->print(
 2764:             '<span class="LC_error">'.
 2765:             &mt('Unable to handle ambiguous references.').
 2766:             '</span>');
 2767:         return '';
 2768:     }
 2769:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
 2770:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2771:     if (!&canview($usec)) {
 2772:         $request->print(
 2773:             '<span class="LC_warning">'.
 2774:             &mt('Unable to view previous version for requested student.').
 2775:             ' '.&mt('([_1] in section [_2] in course id [_3])',
 2776:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
 2777:             '</span>');
 2778:         return;
 2779:     }
 2780:     my $mode = 'both';
 2781:     my $isTask = ($symb =~/\.task$/);
 2782:     if ($isTask) {
 2783:         if ($env{'form.previousversion'} =~ /^\d+$/) {
 2784:             if ($env{'form.fullname'} eq '') {
 2785:                 $env{'form.fullname'} =
 2786:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
 2787:             }
 2788:             my $probtitle=&Apache::lonnet::gettitle($symb);
 2789:             $request->print("\n\n".
 2790:                             '<div class="LC_grade_show_user">'.
 2791:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 2792:                             '</h2>'."\n");
 2793:             &Apache::lonxml::clear_problem_counter();
 2794:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
 2795:                             {'previousversion' => $env{'form.previousversion'} }));
 2796:             $request->print("\n</div>");
 2797:         }
 2798:     }
 2799:     return;
 2800: }
 2801: 
 2802: sub choose_task_version_form {
 2803:     my ($symb,$uname,$udom,$nomenu) = @_;
 2804:     my $isTask = ($symb =~/\.task$/);
 2805:     my ($current,$version,$result,$js,$displayed,$rowtitle);
 2806:     if ($isTask) {
 2807:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 2808:                                               $udom,$uname);
 2809:         if (($record{'resource.0.version'} eq '') ||
 2810:             ($record{'resource.0.version'} < 2)) {
 2811:             return ($record{'resource.0.version'},
 2812:                     $record{'resource.0.version'},$result,$js);
 2813:         } else {
 2814:             $current = $record{'resource.0.version'};
 2815:         }
 2816:         if ($env{'form.previousversion'}) {
 2817:             $displayed = $env{'form.previousversion'};
 2818:             $rowtitle = &mt('Choose another version:')
 2819:         } else {
 2820:             $displayed = $current;
 2821:             $rowtitle = &mt('Show earlier version:');
 2822:         }
 2823:         $result = '<div class="LC_left_float">';
 2824:         my $list;
 2825:         my $numversions = 0;
 2826:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
 2827:             if ($i == $current) {
 2828:                 if (!$env{'form.previousversion'} || $nomenu) {
 2829:                     next;
 2830:                 } else {
 2831:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
 2832:                     $numversions ++;
 2833:                 }
 2834:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
 2835:                 unless ($i == $env{'form.previousversion'}) {
 2836:                     $numversions ++;
 2837:                 }
 2838:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 2839:             }
 2840:         }
 2841:         if ($numversions) {
 2842:             $symb = &HTML::Entities::encode($symb,'<>"&');
 2843:             $result .=
 2844:                 '<form name="getprev" method="post" action=""'.
 2845:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
 2846:                 &Apache::loncommon::start_data_table().
 2847:                 &Apache::loncommon::start_data_table_row().
 2848:                 '<th align="left">'.$rowtitle.'</th>'.
 2849:                 '<td><select name="version">'.
 2850:                 '<option>'.&mt('Select').'</option>'.
 2851:                 $list.
 2852:                 '</select></td>'.
 2853:                 &Apache::loncommon::end_data_table_row();
 2854:             unless ($nomenu) {
 2855:                 $result .= &Apache::loncommon::start_data_table_row().
 2856:                 '<th align="left">'.&mt('Open in new window').'</th>'.
 2857:                 '<td><span class="LC_nobreak">'.
 2858:                 '<label><input type="radio" name="prevwin" value="1" />'.
 2859:                 &mt('Yes').'</label>'.
 2860:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
 2861:                 '</span></td>'.
 2862:                 &Apache::loncommon::end_data_table_row();
 2863:             }
 2864:             $result .=
 2865:                 &Apache::loncommon::start_data_table_row().
 2866:                 '<th align="left">&nbsp;</th>'.
 2867:                 '<td>'.
 2868:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
 2869:                 '</td>'.
 2870:                 &Apache::loncommon::end_data_table_row().
 2871:                 &Apache::loncommon::end_data_table().
 2872:                 '</form>';
 2873:             $js = &previous_display_javascript($nomenu,$current);
 2874:         } elsif ($displayed && $nomenu) {
 2875:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
 2876:         } else {
 2877:             $result .= &mt('No previous versions to show for this student');
 2878:         }
 2879:         $result .= '</div>';
 2880:     }
 2881:     return ($current,$displayed,$result,$js);
 2882: }
 2883: 
 2884: sub previous_display_javascript {
 2885:     my ($nomenu,$current) = @_;
 2886:     my $js = <<"JSONE";
 2887: <script type="text/javascript">
 2888: // <![CDATA[
 2889: function previousVersion(uname,udom,symb) {
 2890:     var current = '$current';
 2891:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
 2892:     var prevstr = new RegExp("^\\\\d+\$");
 2893:     if (!prevstr.test(version)) {
 2894:         return false;
 2895:     }
 2896:     var url = '';
 2897:     if (version == current) {
 2898:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
 2899:     } else {
 2900:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
 2901:     }
 2902: JSONE
 2903:     if ($nomenu) {
 2904:         $js .= <<"JSTWO";
 2905:     document.location.href = url;
 2906: JSTWO
 2907:     } else {
 2908:         $js .= <<"JSTHREE";
 2909:     var newwin = 0;
 2910:     for (var i=0; i<document.getprev.prevwin.length; i++) {
 2911:         if (document.getprev.prevwin[i].checked == true) {
 2912:             newwin = document.getprev.prevwin[i].value;
 2913:         }
 2914:     }
 2915:     if (newwin == 1) {
 2916:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2917:         url = url+'&inhibitmenu=yes';
 2918:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
 2919:             previousWin = window.open(url,'',options,1);
 2920:         } else {
 2921:             previousWin.location.href = url;
 2922:         }
 2923:         previousWin.focus();
 2924:         return false;
 2925:     } else {
 2926:         document.location.href = url;
 2927:         return false;
 2928:     }
 2929: JSTHREE
 2930:     }
 2931:     $js .= <<"ENDJS";
 2932:     return false;
 2933: }
 2934: // ]]>
 2935: </script>
 2936: ENDJS
 2937: 
 2938: }
 2939: 
 2940: #--- Called from submission routine
 2941: sub processHandGrade {
 2942:     my ($request,$symb) = @_;
 2943:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2944:     my $button = $env{'form.gradeOpt'};
 2945:     my $ngrade = $env{'form.NCT'};
 2946:     my $ntstu  = $env{'form.NTSTU'};
 2947:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2948:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2949: 
 2950:     if ($button eq 'Save & Next') {
 2951: 	my $ctr = 0;
 2952: 	while ($ctr < $ngrade) {
 2953: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2954: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
 2955:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2956: 	    if ($errorflag eq 'no_score') {
 2957: 		$ctr++;
 2958: 		next;
 2959: 	    }
 2960: 	    if ($errorflag eq 'not_allowed') {
 2961: 		$request->print(
 2962:                     '<span class="LC_error">'
 2963:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
 2964:                    .'</span>');
 2965: 		$ctr++;
 2966: 		next;
 2967: 	    }
 2968:             if ($numhidden) {
 2969:                 $request->print(
 2970:                     '<span class="LC_info">'
 2971:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
 2972:                    .'</span><br />');
 2973:             }
 2974: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2975: 	    my ($subject,$message,$msgstatus) = ('','','');
 2976: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2977:             my ($feedurl,$showsymb) =
 2978: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2979: 	    my $messagetail;
 2980: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2981: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2982: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2983: 		$subject.=' ['.$restitle.']';
 2984: 		my (@msgnum) = split(/,/,$includemsg);
 2985: 		foreach (@msgnum) {
 2986: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2987: 		}
 2988: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2989: 		if ($env{'form.withgrades'.$ctr}) {
 2990: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2991: 		    $messagetail = " for <a href=\"".
 2992: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
 2993: 		}
 2994: 		$msgstatus = 
 2995:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2996: 						     $message.$messagetail,
 2997:                                                      undef,$feedurl,undef,
 2998:                                                      undef,undef,$showsymb,
 2999:                                                      $restitle);
 3000: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 3001: 				$msgstatus.'<br />');
 3002: 	    }
 3003: 	    if ($env{'form.collaborator'.$ctr}) {
 3004: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 3005: 		foreach my $collabstr (@collabstrs) {
 3006: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 3007: 		    foreach my $collaborator (@collaborators) {
 3008: 			my ($errorflag,$pts,$wgt) = 
 3009: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 3010: 					   $env{'form.unamedom'.$ctr},$part);
 3011: 			if ($errorflag eq 'not_allowed') {
 3012: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 3013: 			    next;
 3014: 			} elsif ($message ne '') {
 3015: 			    my ($baseurl,$showsymb) = 
 3016: 				&get_feedurl_and_symb($symb,$collaborator,
 3017: 						      $udom);
 3018: 			    if ($env{'form.withgrades'.$ctr}) {
 3019: 				$messagetail = " for <a href=\"".
 3020:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
 3021: 			    }
 3022: 			    $msgstatus = 
 3023: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 3024: 			}
 3025: 		    }
 3026: 		}
 3027: 	    }
 3028: 	    $ctr++;
 3029: 	}
 3030:     }
 3031: 
 3032: #    if ($env{'form.handgrade'} eq 'yes') {
 3033:     if (1) {
 3034: 	# Keywords sorted in alphabatical order
 3035: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 3036: 	my %keyhash = ();
 3037: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 3038: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 3039: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 3040: 	$env{'form.keywords'} = join(' ',@keywords);
 3041: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 3042: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 3043: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 3044: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 3045: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 3046: 
 3047: 	# message center - Order of message gets changed. Blank line is eliminated.
 3048: 	# New messages are saved in env for the next student.
 3049: 	# All messages are saved in nohist_handgrade.db
 3050: 	my ($ctr,$idx) = (1,1);
 3051: 	while ($ctr <= $env{'form.savemsgN'}) {
 3052: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 3053: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 3054: 		$idx++;
 3055: 	    }
 3056: 	    $ctr++;
 3057: 	}
 3058: 	$ctr = 0;
 3059: 	while ($ctr < $ngrade) {
 3060: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 3061: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3062: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 3063: 		$idx++;
 3064: 	    }
 3065: 	    $ctr++;
 3066: 	}
 3067: 	$env{'form.savemsgN'} = --$idx;
 3068: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 3069: 	my $putresult = &Apache::lonnet::put
 3070: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 3071:     }
 3072:     # Called by Save & Refresh from Highlight Attribute Window
 3073:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3074:     if ($env{'form.refresh'} eq 'on') {
 3075: 	my ($ctr,$total) = (0,0);
 3076: 	while ($ctr < $ngrade) {
 3077: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 3078: 	    $ctr++;
 3079: 	}
 3080: 	$env{'form.NTSTU'}=$ngrade;
 3081: 	$ctr = 0;
 3082: 	while ($ctr < $total) {
 3083: 	    my $processUser = $env{'form.unamedom'.$ctr};
 3084: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 3085: 	    $env{'form.fullname'} = $$fullname{$processUser};
 3086: 	    &submission($request,$ctr,$total-1,$symb);
 3087: 	    $ctr++;
 3088: 	}
 3089: 	return '';
 3090:     }
 3091: 
 3092:     # Get the next/previous one or group of students
 3093:     my $firststu = $env{'form.unamedom0'};
 3094:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 3095:     my $ctr = 2;
 3096:     while ($laststu eq '') {
 3097: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 3098: 	$ctr++;
 3099: 	$laststu = $firststu if ($ctr > $ngrade);
 3100:     }
 3101: 
 3102:     my (@parsedlist,@nextlist);
 3103:     my ($nextflg) = 0;
 3104:     foreach my $item (sort 
 3105: 	     {
 3106: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3107: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3108: 		 }
 3109: 		 return $a cmp $b;
 3110: 	     } (keys(%$fullname))) {
 3111: # FIXME: this is fishy, looks like the button label
 3112: 	if ($nextflg == 1 && $button =~ /Next$/) {
 3113: 	    push(@parsedlist,$item);
 3114: 	}
 3115: 	$nextflg = 1 if ($item eq $laststu);
 3116: 	if ($button eq 'Previous') {
 3117: 	    last if ($item eq $firststu);
 3118: 	    push(@parsedlist,$item);
 3119: 	}
 3120:     }
 3121:     $ctr = 0;
 3122: # FIXME: this is fishy, looks like the button label
 3123:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 3124:     my $res_error;
 3125:     my ($partlist) = &response_type($symb,\$res_error);
 3126:     if ($res_error) {
 3127:         $request->print(&navmap_errormsg());
 3128:         return;
 3129:     }
 3130:     foreach my $student (@parsedlist) {
 3131: 	my $submitonly=$env{'form.submitonly'};
 3132: 	my ($uname,$udom) = split(/:/,$student);
 3133: 	
 3134: 	if ($submitonly eq 'queued') {
 3135: 	    my %queue_status = 
 3136: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 3137: 							$udom,$uname);
 3138: 	    next if (!defined($queue_status{'gradingqueue'}));
 3139: 	}
 3140: 
 3141: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 3142: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 3143: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 3144: 	    my $submitted = 0;
 3145: 	    my $ungraded = 0;
 3146: 	    my $incorrect = 0;
 3147: 	    foreach my $item (keys(%status)) {
 3148: 		$submitted = 1 if ($status{$item} ne 'nothing');
 3149: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 3150: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 3151: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 3152: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 3153: 		    $submitted = 0;
 3154: 		}
 3155: 	    }
 3156: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 3157: 				     $submitonly eq 'incorrect' ||
 3158: 				     $submitonly eq 'graded'));
 3159: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 3160: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 3161: 	}
 3162: 	push(@nextlist,$student) if ($ctr < $ntstu);
 3163: 	last if ($ctr == $ntstu);
 3164: 	$ctr++;
 3165:     }
 3166: 
 3167:     $ctr = 0;
 3168:     my $total = scalar(@nextlist)-1;
 3169: 
 3170:     foreach (sort(@nextlist)) {
 3171: 	my ($uname,$udom,$submitter) = split(/:/);
 3172: 	$env{'form.student'}  = $uname;
 3173: 	$env{'form.userdom'}  = $udom;
 3174: 	$env{'form.fullname'} = $$fullname{$_};
 3175: 	&submission($request,$ctr,$total,$symb);
 3176: 	$ctr++;
 3177:     }
 3178:     if ($total < 0) {
 3179: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
 3180: 	$request->print($the_end);
 3181:     }
 3182:     return '';
 3183: }
 3184: 
 3185: #---- Save the score and award for each student, if changed
 3186: sub saveHandGrade {
 3187:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 3188:     my @version_parts;
 3189:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 3190: 					   $env{'request.course.id'});
 3191:     if (!&canmodify($usec)) { return('not_allowed'); }
 3192:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 3193:     my @parts_graded;
 3194:     my %newrecord  = ();
 3195:     my ($pts,$wgt,$totchg) = ('','',0);
 3196:     my %aggregate = ();
 3197:     my $aggregateflag = 0;
 3198:     if ($env{'form.HIDE'.$newflg}) {
 3199:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
 3200:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
 3201:         $totchg += $numchgs;
 3202:     }
 3203:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 3204:     foreach my $new_part (@parts) {
 3205: 	#collaborator ($submi may vary for different parts
 3206: 	if ($submitter && $new_part ne $part) { next; }
 3207: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 3208: 	if ($dropMenu eq 'excused') {
 3209: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 3210: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 3211: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 3212: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 3213: 		}
 3214: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3215: 	    }
 3216: 	} elsif ($dropMenu eq 'reset status'
 3217: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 3218: 	    foreach my $key (keys(%record)) {
 3219: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 3220: 	    }
 3221: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3222: 		"$env{'user.name'}:$env{'user.domain'}";
 3223:             my $totaltries = $record{'resource.'.$part.'.tries'};
 3224: 
 3225:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 3226: 					       [$new_part]);
 3227:             my $aggtries =$totaltries;
 3228:             if ($last_resets{$new_part}) {
 3229:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 3230: 					   $new_part);
 3231:             }
 3232: 
 3233:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 3234:             if ($aggtries > 0) {
 3235:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3236:                 $aggregateflag = 1;
 3237:             }
 3238: 	} elsif ($dropMenu eq '') {
 3239: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 3240: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 3241: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 3242: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 3243: 		next;
 3244: 	    }
 3245: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 3246: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 3247: 	    my $partial= $pts/$wgt;
 3248: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 3249: 		#do not update score for part if not changed.
 3250:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 3251: 		next;
 3252: 	    } else {
 3253: 	        push(@parts_graded,$new_part);
 3254: 	    }
 3255: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 3256: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 3257: 	    }
 3258: 	    my $reckey = 'resource.'.$new_part.'.solved';
 3259: 	    if ($partial == 0) {
 3260: 		if ($record{$reckey} ne 'incorrect_by_override') {
 3261: 		    $newrecord{$reckey} = 'incorrect_by_override';
 3262: 		}
 3263: 	    } else {
 3264: 		if ($record{$reckey} ne 'correct_by_override') {
 3265: 		    $newrecord{$reckey} = 'correct_by_override';
 3266: 		}
 3267: 	    }	    
 3268: 	    if ($submitter && 
 3269: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 3270: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 3271: 	    }
 3272: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 3273: 		"$env{'user.name'}:$env{'user.domain'}";
 3274: 	}
 3275: 	# unless problem has been graded, set flag to version the submitted files
 3276: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 3277: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 3278: 	        $dropMenu eq 'reset status')
 3279: 	   {
 3280: 	    push(@version_parts,$new_part);
 3281: 	}
 3282:     }
 3283:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3284:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3285: 
 3286:     if (%newrecord) {
 3287:         if (@version_parts) {
 3288:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 3289:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 3290: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 3291: 	    foreach my $new_part (@version_parts) {
 3292: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 3293: 				$new_part,\%newrecord);
 3294: 	    }
 3295:         }
 3296: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 3297: 				$env{'request.course.id'},$domain,$stuname);
 3298: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 3299: 				     $cdom,$cnum,$domain,$stuname);
 3300:     }
 3301:     if ($aggregateflag) {
 3302:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3303: 			      $cdom,$cnum);
 3304:     }
 3305:     return ('',$pts,$wgt,$totchg);
 3306: }
 3307: 
 3308: sub makehidden {
 3309:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
 3310:     return unless (ref($record) eq 'HASH');
 3311:     my %modified;
 3312:     my $numchanged = 0;
 3313:     if (exists($record->{$version.':keys'})) {
 3314:         my $partsregexp = $parts;
 3315:         $partsregexp =~ s/,/|/g;
 3316:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
 3317:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
 3318:                  my $item = $1;
 3319:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
 3320:                      $modified{$key} = $record->{$version.':'.$key};
 3321:                  }
 3322:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
 3323:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
 3324:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
 3325:                 $modified{$key} = $record->{$version.':'.$key};
 3326:             }
 3327:         }
 3328:         if (keys(%modified)) {
 3329:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
 3330:                                           $domain,$stuname,$tolog) eq 'ok') {
 3331:                 $numchanged ++;
 3332:             }
 3333:         }
 3334:     }
 3335:     return $numchanged;
 3336: }
 3337: 
 3338: sub check_and_remove_from_queue {
 3339:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 3340:     my @ungraded_parts;
 3341:     foreach my $part (@{$parts}) {
 3342: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 3343: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 3344: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 3345: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 3346: 		) {
 3347: 	    push(@ungraded_parts, $part);
 3348: 	}
 3349:     }
 3350:     if ( !@ungraded_parts ) {
 3351: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 3352: 					       $cnum,$domain,$stuname);
 3353:     }
 3354: }
 3355: 
 3356: sub handback_files {
 3357:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 3358:     my $portfolio_root = '/userfiles/portfolio';
 3359:     my $res_error;
 3360:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3361:     if ($res_error) {
 3362:         $request->print('<br />'.&navmap_errormsg().'<br />');
 3363:         return;
 3364:     }
 3365:     my @handedback;
 3366:     my $file_msg;
 3367:     my @part_response_id = &flatten_responseType($responseType);
 3368:     foreach my $part_response_id (@part_response_id) {
 3369:     	my ($part_id,$resp_id) = @{ $part_response_id };
 3370: 	my $part_resp = join('_',@{ $part_response_id });
 3371:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
 3372:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
 3373:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
 3374:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
 3375:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
 3376:                     my ($directory,$answer_file) = 
 3377:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
 3378:                     my ($answer_name,$answer_ver,$answer_ext) =
 3379: 		        &Apache::lonnet::file_name_version_ext($answer_file);
 3380: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 3381:                     my $getpropath = 1;
 3382:                     my ($dir_list,$listerror) = 
 3383:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
 3384:                                                  $domain,$stuname,$getpropath);
 3385: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
 3386:                     # fix filename
 3387:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 3388:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 3389:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
 3390:             	                                $save_file_name);
 3391:                     if ($result !~ m|^/uploaded/|) {
 3392:                         $request->print('<br /><span class="LC_error">'.
 3393:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 3394:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
 3395:                                         '</span>');
 3396:                     } else {
 3397:                         # mark the file as read only
 3398:                         push(@handedback,$save_file_name);
 3399: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 3400: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 3401: 			}
 3402:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 3403: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
 3404:                     }
 3405:                     $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>'));
 3406:                 }
 3407:             }
 3408:         }
 3409:     }
 3410:     if (@handedback > 0) {
 3411:         $request->print('<br />');
 3412:         my @what = ($symb,$env{'request.course.id'},'handback');
 3413:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
 3414:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
 3415:         my ($subject,$message);
 3416:         if (scalar(@handedback) == 1) {
 3417:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
 3418:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
 3419:         } else {
 3420:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
 3421:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
 3422:         }
 3423:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
 3424:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
 3425:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
 3426:         my ($feedurl,$showsymb) =
 3427:             &get_feedurl_and_symb($symb,$domain,$stuname);
 3428:         my $restitle = &Apache::lonnet::gettitle($symb);
 3429:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
 3430:         my $msgstatus =
 3431:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
 3432:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
 3433:                  $restitle);
 3434:         if ($msgstatus) {
 3435:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
 3436:         }
 3437:     }
 3438:     return;
 3439: }
 3440: 
 3441: sub get_feedurl_and_symb {
 3442:     my ($symb,$uname,$udom) = @_;
 3443:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3444:     $url = &Apache::lonnet::clutter($url);
 3445:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3446: 					$symb,$udom,$uname);
 3447:     if ($encrypturl =~ /^yes$/i) {
 3448: 	&Apache::lonenc::encrypted(\$url,1);
 3449: 	&Apache::lonenc::encrypted(\$symb,1);
 3450:     }
 3451:     return ($url,$symb);
 3452: }
 3453: 
 3454: sub get_submitted_files {
 3455:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3456:     my @files;
 3457:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3458:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3459:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3460:     	    push(@files,$file_url.$file);
 3461:         }
 3462:     }
 3463:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3464:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3465:     }
 3466:     return (\@files);
 3467: }
 3468: 
 3469: # ----------- Provides number of tries since last reset.
 3470: sub get_num_tries {
 3471:     my ($record,$last_reset,$part) = @_;
 3472:     my $timestamp = '';
 3473:     my $num_tries = 0;
 3474:     if ($$record{'version'}) {
 3475:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3476:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3477:                 $timestamp = $$record{$version.':timestamp'};
 3478:                 if ($timestamp > $last_reset) {
 3479:                     $num_tries ++;
 3480:                 } else {
 3481:                     last;
 3482:                 }
 3483:             }
 3484:         }
 3485:     }
 3486:     return $num_tries;
 3487: }
 3488: 
 3489: # ----------- Determine decrements required in aggregate totals 
 3490: sub decrement_aggs {
 3491:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3492:     my %decrement = (
 3493:                         attempts => 0,
 3494:                         users => 0,
 3495:                         correct => 0
 3496:                     );
 3497:     $decrement{'attempts'} = $aggtries;
 3498:     if ($solvedstatus =~ /^correct/) {
 3499:         $decrement{'correct'} = 1;
 3500:     }
 3501:     if ($aggtries == $totaltries) {
 3502:         $decrement{'users'} = 1;
 3503:     }
 3504:     foreach my $type (keys(%decrement)) {
 3505:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3506:     }
 3507:     return;
 3508: }
 3509: 
 3510: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3511: sub get_last_resets {
 3512:     my ($symb,$courseid,$partids) =@_;
 3513:     my %last_resets;
 3514:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3515:     my $cname = $env{'course.'.$courseid.'.num'};
 3516:     my @keys;
 3517:     foreach my $part (@{$partids}) {
 3518: 	push(@keys,"$symb\0$part\0resettime");
 3519:     }
 3520:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3521: 				     $cdom,$cname);
 3522:     foreach my $part (@{$partids}) {
 3523: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3524:     }
 3525:     return %last_resets;
 3526: }
 3527: 
 3528: # ----------- Handles creating versions for portfolio files as answers
 3529: sub version_portfiles {
 3530:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3531:     my $version_parts = join('|',@$v_flag);
 3532:     my @returned_keys;
 3533:     my $parts = join('|', @$parts_graded);
 3534:     foreach my $key (keys(%$record)) {
 3535:         my $new_portfiles;
 3536:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3537:             my @versioned_portfiles;
 3538:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3539:             if (@portfiles) {
 3540:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
 3541:                                                       \@versioned_portfiles);
 3542:             }
 3543:             $$record{$key} = join(',',@versioned_portfiles);
 3544:             push(@returned_keys,$key);
 3545:         }
 3546:     } 
 3547:     return (@returned_keys);   
 3548: }
 3549: 
 3550: #--------------------------------------------------------------------------------------
 3551: #
 3552: #-------------------------- Next few routines handles grading by section or whole class
 3553: #
 3554: #--- Javascript to handle grading by section or whole class
 3555: sub viewgrades_js {
 3556:     my ($request) = shift;
 3557: 
 3558:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3559:     &js_escape(\$alertmsg);
 3560:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
 3561:    function writePoint(partid,weight,point) {
 3562: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3563: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3564: 	if (point == "textval") {
 3565: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3566: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3567: 		alert("$alertmsg"+parseFloat(point));
 3568: 		var resetbox = false;
 3569: 		for (var i=0; i<radioButton.length; i++) {
 3570: 		    if (radioButton[i].checked) {
 3571: 			textbox.value = i;
 3572: 			resetbox = true;
 3573: 		    }
 3574: 		}
 3575: 		if (!resetbox) {
 3576: 		    textbox.value = "";
 3577: 		}
 3578: 		return;
 3579: 	    }
 3580: 	    if (parseFloat(point) > parseFloat(weight)) {
 3581: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3582: 				   ") greater than the weight for the part. Accept?");
 3583: 		if (resp == false) {
 3584: 		    textbox.value = "";
 3585: 		    return;
 3586: 		}
 3587: 	    }
 3588: 	    for (var i=0; i<radioButton.length; i++) {
 3589: 		radioButton[i].checked=false;
 3590: 		if (parseFloat(point) == i) {
 3591: 		    radioButton[i].checked=true;
 3592: 		}
 3593: 	    }
 3594: 
 3595: 	} else {
 3596: 	    textbox.value = parseFloat(point);
 3597: 	}
 3598: 	for (i=0;i<document.classgrade.total.value;i++) {
 3599: 	    var user = document.classgrade["ctr"+i].value;
 3600: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3601: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3602: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3603: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3604: 	    if (saveval != "correct") {
 3605: 		scorename.value = point;
 3606: 		if (selname[0].selected != true) {
 3607: 		    selname[0].selected = true;
 3608: 		}
 3609: 	    }
 3610: 	}
 3611: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3612:     }
 3613: 
 3614:     function writeRadText(partid,weight) {
 3615: 	var selval   = document.classgrade["SELVAL_"+partid];
 3616: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3617:         var override = document.classgrade["FORCE_"+partid].checked;
 3618: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3619: 	if (selval[1].selected || selval[2].selected) {
 3620: 	    for (var i=0; i<radioButton.length; i++) {
 3621: 		radioButton[i].checked=false;
 3622: 
 3623: 	    }
 3624: 	    textbox.value = "";
 3625: 
 3626: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3627: 		var user = document.classgrade["ctr"+i].value;
 3628: 		user = user.replace(new RegExp(':', 'g'),"_");
 3629: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3630: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3631: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3632: 		if ((saveval != "correct") || override) {
 3633: 		    scorename.value = "";
 3634: 		    if (selval[1].selected) {
 3635: 			selname[1].selected = true;
 3636: 		    } else {
 3637: 			selname[2].selected = true;
 3638: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3639: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3640: 		    }
 3641: 		}
 3642: 	    }
 3643: 	} else {
 3644: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3645: 		var user = document.classgrade["ctr"+i].value;
 3646: 		user = user.replace(new RegExp(':', 'g'),"_");
 3647: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3648: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3649: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3650: 		if ((saveval != "correct") || override) {
 3651: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3652: 		    selname[0].selected = true;
 3653: 		}
 3654: 	    }
 3655: 	}	    
 3656:     }
 3657: 
 3658:     function changeSelect(partid,user) {
 3659: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3660: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3661: 	var point  = textbox.value;
 3662: 	var weight = document.classgrade["weight_"+partid].value;
 3663: 
 3664: 	if (isNaN(point) || parseFloat(point) < 0) {
 3665: 	    alert("$alertmsg"+parseFloat(point));
 3666: 	    textbox.value = "";
 3667: 	    return;
 3668: 	}
 3669: 	if (parseFloat(point) > parseFloat(weight)) {
 3670: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3671: 			       ") greater than the weight of the part. Accept?");
 3672: 	    if (resp == false) {
 3673: 		textbox.value = "";
 3674: 		return;
 3675: 	    }
 3676: 	}
 3677: 	selval[0].selected = true;
 3678:     }
 3679: 
 3680:     function changeOneScore(partid,user) {
 3681: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3682: 	if (selval[1].selected || selval[2].selected) {
 3683: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3684: 	    if (selval[2].selected) {
 3685: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3686: 	    }
 3687:         }
 3688:     }
 3689: 
 3690:     function resetEntry(numpart) {
 3691: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3692: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3693: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3694: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3695: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3696: 	    for (var i=0; i<radioButton.length; i++) {
 3697: 		radioButton[i].checked=false;
 3698: 
 3699: 	    }
 3700: 	    textbox.value = "";
 3701: 	    selval[0].selected = true;
 3702: 
 3703: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3704: 		var user = document.classgrade["ctr"+i].value;
 3705: 		user = user.replace(new RegExp(':', 'g'),"_");
 3706: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3707: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3708: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3709: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3710: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3711: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3712: 		if (saveselval == "excused") {
 3713: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3714: 		} else {
 3715: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3716: 		}
 3717: 	    }
 3718: 	}
 3719:     }
 3720: 
 3721: VIEWJAVASCRIPT
 3722: }
 3723: 
 3724: #--- show scores for a section or whole class w/ option to change/update a score
 3725: sub viewgrades {
 3726:     my ($request,$symb) = @_;
 3727:     my ($is_tool,$toolsymb);
 3728:     if ($symb =~ /ext\.tool$/) {
 3729:         $is_tool = 1;
 3730:         $toolsymb = $symb;
 3731:     }
 3732:     &viewgrades_js($request);
 3733: 
 3734:     #need to make sure we have the correct data for later EXT calls, 
 3735:     #thus invalidate the cache
 3736:     &Apache::lonnet::devalidatecourseresdata(
 3737:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3738:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3739:     &Apache::lonnet::clear_EXT_cache_status();
 3740: 
 3741:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3742: 
 3743:     #view individual student submission form - called using Javascript viewOneStudent
 3744:     $result.=&jscriptNform($symb);
 3745: 
 3746:     #beginning of class grading form
 3747:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3748:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3749: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3750: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3751: 	&build_section_inputs().
 3752: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3753: 
 3754:     #retrieve selected groups
 3755:     my (@groups,$group_display);
 3756:     @groups = &Apache::loncommon::get_env_multiple('form.group');
 3757:     if (grep(/^all$/,@groups)) {
 3758:         @groups = ('all');
 3759:     } elsif (grep(/^none$/,@groups)) {
 3760:         @groups = ('none');
 3761:     } elsif (@groups > 0) {
 3762:         $group_display = join(', ',@groups);
 3763:     }
 3764: 
 3765:     my ($common_header,$specific_header,@sections,$section_display);
 3766:     @sections = &Apache::loncommon::get_env_multiple('form.section');
 3767:     if (grep(/^all$/,@sections)) {
 3768:         @sections = ('all');
 3769:         if ($group_display) {
 3770:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
 3771:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
 3772:         } elsif (grep(/^none$/,@groups)) {
 3773:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
 3774:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
 3775:         } else {
 3776: 	    $common_header = &mt('Assign Common Grade to Class');
 3777:             $specific_header = &mt('Assign Grade to Specific Students in Class');
 3778:         }
 3779:     } elsif (grep(/^none$/,@sections)) {
 3780:         @sections = ('none');
 3781:         if ($group_display) {
 3782:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
 3783:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
 3784:         } elsif (grep(/^none$/,@groups)) {
 3785:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
 3786:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
 3787:         } else {
 3788:             $common_header = &mt('Assign Common Grade to Students in no Section');
 3789: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3790:         }
 3791:     } else {
 3792:         $section_display = join (", ",@sections);
 3793:         if ($group_display) {
 3794:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
 3795:                                  $section_display,$group_display);
 3796:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
 3797:                                    $section_display,$group_display);
 3798:         } elsif (grep(/^none$/,@groups)) {
 3799:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
 3800:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
 3801:         } else {
 3802:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3803: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3804:         }
 3805:     }
 3806:     my %submit_types = &substatus_options();
 3807:     my $submission_status = $submit_types{$env{'form.submitonly'}};
 3808: 
 3809:     if ($env{'form.submitonly'} eq 'all') {
 3810:         $result.= '<h3>'.$common_header.'</h3>';
 3811:     } else {
 3812:         my $text;
 3813:         if ($is_tool) {
 3814:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3815:         } else {
 3816:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3817:         }
 3818:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
 3819:     }
 3820:     $result .= &Apache::loncommon::start_data_table();
 3821:     #radio buttons/text box for assigning points for a section or class.
 3822:     #handles different parts of a problem
 3823:     my $res_error;
 3824:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3825:     if ($res_error) {
 3826:         return &navmap_errormsg();
 3827:     }
 3828:     my %weight = ();
 3829:     my $ctsparts = 0;
 3830:     my %seen = ();
 3831:     my @part_response_id;
 3832:     if ($is_tool) {
 3833:         @part_response_id = ([0,'']);
 3834:     } else {
 3835:         @part_response_id = &flatten_responseType($responseType);
 3836:     }
 3837:     foreach my $part_response_id (@part_response_id) {
 3838:     	my ($partid,$respid) = @{ $part_response_id };
 3839: 	my $part_resp = join('_',@{ $part_response_id });
 3840: 	next if $seen{$partid};
 3841: 	$seen{$partid}++;
 3842: #	my $handgrade=$$handgrade{$part_resp};
 3843: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3844: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3845: 
 3846: 	my $display_part=&get_display_part($partid,$symb);
 3847: 	my $radio.='<table border="0"><tr>';  
 3848: 	my $ctr = 0;
 3849: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3850: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3851: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3852: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3853: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3854: 	    $ctr++;
 3855: 	}
 3856: 	$radio.='</tr></table>';
 3857: 	my $line = '<input type="text" name="TEXTVAL_'.
 3858: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3859: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3860: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3861:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
 3862:             '<select name="SELVAL_'.$partid.'" '.
 3863:             'onchange="javascript:writeRadText(\''.$partid.'\','.
 3864:                 $weight{$partid}.')"> '.
 3865: 	    '<option selected="selected"> </option>'.
 3866: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3867: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3868: 	    '</select></td>'.
 3869:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3870: 	$line.='<input type="hidden" name="partid_'.
 3871: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3872: 	$line.='<input type="hidden" name="weight_'.
 3873: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3874: 
 3875: 	$result.=
 3876: 	    &Apache::loncommon::start_data_table_row()."\n".
 3877: 	    '<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>'.
 3878: 	    &Apache::loncommon::end_data_table_row()."\n";
 3879: 	$ctsparts++;
 3880:     }
 3881:     $result.=&Apache::loncommon::end_data_table()."\n".
 3882: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3883:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3884: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3885: 
 3886:     #table listing all the students in a section/class
 3887:     #header of table
 3888:     if ($env{'form.submitonly'} eq 'all') {
 3889:         $result.= '<h3>'.$specific_header.'</h3>';
 3890:     } else {
 3891:         my $text;
 3892:         if ($is_tool) {
 3893:             $text = &mt('(transaction status: "[_1]")',$submission_status);
 3894:         } else {
 3895:             $text = &mt('(submission status: "[_1]")',$submission_status);
 3896:         }
 3897:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
 3898:     }
 3899:     $result.= &Apache::loncommon::start_data_table().
 3900: 	      &Apache::loncommon::start_data_table_header_row().
 3901: 	      '<th>'.&mt('No.').'</th>'.
 3902: 	      '<th>'.&nameUserString('header')."</th>\n";
 3903:     my $partserror;
 3904:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3905:     if ($partserror) {
 3906:         return &navmap_errormsg();
 3907:     }
 3908:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3909:     my @partids = ();
 3910:     foreach my $part (@parts) {
 3911: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 3912:         my $narrowtext = &mt('Tries');
 3913: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3914: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
 3915: 	my ($partid) = &split_part_type($part);
 3916:         push(@partids,$partid);
 3917: #
 3918: # FIXME: Looks like $display looks at English text
 3919: #
 3920: 	my $display_part=&get_display_part($partid,$symb);
 3921: 	if ($display =~ /^Partial Credit Factor/) {
 3922: 	    $result.='<th>'.
 3923: 		&mt('Score Part: [_1][_2](weight = [_3])',
 3924: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
 3925: 	    next;
 3926: 	    
 3927: 	} else {
 3928: 	    if ($display =~ /Problem Status/) {
 3929: 		my $grade_status_mt = &mt('Grade Status');
 3930: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3931: 	    }
 3932: 	    my $part_mt = &mt('Part:');
 3933: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3934: 	}
 3935: 
 3936: 	$result.='<th>'.$display.'</th>'."\n";
 3937:     }
 3938:     $result.=&Apache::loncommon::end_data_table_header_row();
 3939: 
 3940:     my %last_resets = 
 3941: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3942: 
 3943:     #get info for each student
 3944:     #list all the students - with points and grade status
 3945:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
 3946:     my $ctr = 0;
 3947:     foreach (sort 
 3948: 	     {
 3949: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3950: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3951: 		 }
 3952: 		 return $a cmp $b;
 3953: 	     } (keys(%$fullname))) {
 3954: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3955: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
 3956:     }
 3957:     $result.=&Apache::loncommon::end_data_table();
 3958:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3959:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3960: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3961:     if ($ctr == 0) {
 3962:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3963:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
 3964:                 '<span class="LC_warning">';
 3965:         if ($env{'form.submitonly'} eq 'all') {
 3966:             if (grep(/^all$/,@sections)) {
 3967:                 if (grep(/^all$/,@groups)) {
 3968:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
 3969:                                    $stu_status);
 3970:                 } elsif (grep(/^none$/,@groups)) {
 3971:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
 3972:                                    $stu_status); 
 3973:                 } else {
 3974:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3975:                                    $group_display,$stu_status);
 3976:                 }
 3977:             } elsif (grep(/^none$/,@sections)) {
 3978:                 if (grep(/^all$/,@groups)) {
 3979:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
 3980:                                    $stu_status);
 3981:                 } elsif (grep(/^none$/,@groups)) {
 3982:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
 3983:                                    $stu_status);
 3984:                 } else {
 3985:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
 3986:                                    $group_display,$stu_status);
 3987:                 }
 3988:             } else {
 3989:                 if (grep(/^all$/,@groups)) {
 3990:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3991:                                    $section_display,$stu_status);
 3992:                 } elsif (grep(/^none$/,@groups)) {
 3993:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
 3994:                                    $section_display,$stu_status);
 3995:                 } else {
 3996:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
 3997:                                    $section_display,$group_display,$stu_status);
 3998:                 }
 3999:             }
 4000:         } else {
 4001:             if (grep(/^all$/,@sections)) {
 4002:                 if (grep(/^all$/,@groups)) {
 4003:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4004:                                    $stu_status,$submission_status);
 4005:                 } elsif (grep(/^none$/,@groups)) {
 4006:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4007:                                    $stu_status,$submission_status);
 4008:                 } else {
 4009:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4010:                                    $group_display,$stu_status,$submission_status);
 4011:                 }
 4012:             } elsif (grep(/^none$/,@sections)) {
 4013:                 if (grep(/^all$/,@groups)) {
 4014:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4015:                                    $stu_status,$submission_status);
 4016:                 } elsif (grep(/^none$/,@groups)) {
 4017:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
 4018:                                    $stu_status,$submission_status);
 4019:                 } else {
 4020:                     $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.',
 4021:                                    $group_display,$stu_status,$submission_status);
 4022:                 }
 4023:             } else {
 4024:                 if (grep(/^all$/,@groups)) {
 4025: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
 4026: 	                           $section_display,$stu_status,$submission_status);
 4027:                 } elsif (grep(/^none$/,@groups)) {
 4028:                     $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.',
 4029:                                    $section_display,$stu_status,$submission_status);
 4030:                 } else {
 4031:                     $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.',
 4032:                                    $section_display,$group_display,$stu_status,$submission_status);
 4033:                 }
 4034:             }
 4035:         }
 4036: 	$result .= '</span><br />';
 4037:     }
 4038:     return $result;
 4039: }
 4040: 
 4041: #--- call by previous routine to display each student who satisfies submission filter. 
 4042: sub viewstudentgrade {
 4043:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
 4044:     my ($uname,$udom) = split(/:/,$student);
 4045:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 4046:     my $submitonly = $env{'form.submitonly'};
 4047:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
 4048:         my %partstatus = ();
 4049:         if (ref($parts) eq 'ARRAY') {
 4050:             foreach my $apart (@{$parts}) {
 4051:                 my ($part,$type) = &split_part_type($apart);
 4052:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
 4053:                 $status = 'nothing' if ($status eq '');
 4054:                 $partstatus{$part}      = $status;
 4055:                 my $subkey = "resource.$part.submitted_by";
 4056:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
 4057:             }
 4058:             my $submitted = 0;
 4059:             my $graded = 0;
 4060:             my $incorrect = 0;
 4061:             foreach my $key (keys(%partstatus)) {
 4062:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
 4063:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
 4064:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
 4065: 
 4066:                 my $partid = (split(/\./,$key))[1];
 4067:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
 4068:                     $submitted = 0;
 4069:                 }
 4070:             }
 4071:             return if (!$submitted && ($submitonly eq 'yes' ||
 4072:                                        $submitonly eq 'incorrect' ||
 4073:                                        $submitonly eq 'graded'));
 4074:             return if (!$graded && ($submitonly eq 'graded'));
 4075:             return if (!$incorrect && $submitonly eq 'incorrect');
 4076:         }
 4077:     }
 4078:     if ($submitonly eq 'queued') {
 4079:         my ($cdom,$cnum) = split(/_/,$courseid);
 4080:         my %queue_status =
 4081:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 4082:                                                     $udom,$uname);
 4083:         return if (!defined($queue_status{'gradingqueue'}));
 4084:     }
 4085:     $$ctr++;
 4086:     my %aggregates = ();
 4087:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 4088: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
 4089: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
 4090: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 4091: 	'\');" target="_self">'.$fullname.'</a> '.
 4092: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 4093:     $student=~s/:/_/; # colon doen't work in javascript for names
 4094:     foreach my $apart (@$parts) {
 4095: 	my ($part,$type) = &split_part_type($apart);
 4096: 	my $score=$record{"resource.$part.$type"};
 4097:         $result.='<td align="center">';
 4098:         my ($aggtries,$totaltries);
 4099:         unless (exists($aggregates{$part})) {
 4100: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 4101: 	    $aggtries = $totaltries;
 4102:             if ($$last_resets{$part}) {  
 4103:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 4104: 					   $part);
 4105:             }
 4106:             $result.='<input type="hidden" name="'.
 4107:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 4108:             $result.='<input type="hidden" name="'.
 4109:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 4110:             $aggregates{$part} = 1;
 4111:         }
 4112: 	if ($type eq 'awarded') {
 4113: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 4114: 	    $result.='<input type="hidden" name="'.
 4115: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 4116: 	    $result.='<input type="text" name="'.
 4117: 		'GD_'.$student.'_'.$part.'_awarded" '.
 4118:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 4119: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 4120: 	} elsif ($type eq 'solved') {
 4121: 	    my ($status,$foo)=split(/_/,$score,2);
 4122: 	    $status = 'nothing' if ($status eq '');
 4123: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 4124: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 4125: 	    $result.='&nbsp;<select name="'.
 4126: 		'GD_'.$student.'_'.$part.'_solved" '.
 4127:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 4128: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 4129: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 4130: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 4131: 	    $result.="</select>&nbsp;</td>\n";
 4132: 	} else {
 4133: 	    $result.='<input type="hidden" name="'.
 4134: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 4135: 		    "\n";
 4136: 	    $result.='<input type="text" name="'.
 4137: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 4138: 		'value="'.$score.'" size="4" /></td>'."\n";
 4139: 	}
 4140:     }
 4141:     $result.=&Apache::loncommon::end_data_table_row();
 4142:     return $result;
 4143: }
 4144: 
 4145: #--- change scores for all the students in a section/class
 4146: #    record does not get update if unchanged
 4147: sub editgrades {
 4148:     my ($request,$symb) = @_;
 4149:     my $toolsymb;
 4150:     if ($symb =~ /ext\.tool$/) {
 4151:         $toolsymb = $symb;
 4152:     }
 4153: 
 4154:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 4155:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 4156:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 4157: 
 4158:     my $result= &Apache::loncommon::start_data_table().
 4159: 	&Apache::loncommon::start_data_table_header_row().
 4160: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 4161: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 4162:     my %scoreptr = (
 4163: 		    'correct'  =>'correct_by_override',
 4164: 		    'incorrect'=>'incorrect_by_override',
 4165: 		    'excused'  =>'excused',
 4166: 		    'ungraded' =>'ungraded_attempted',
 4167:                     'credited' =>'credit_attempted',
 4168: 		    'nothing'  => '',
 4169: 		    );
 4170:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 4171: 
 4172:     my (@partid);
 4173:     my %weight = ();
 4174:     my %columns = ();
 4175:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 4176: 
 4177:     my $partserror;
 4178:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 4179:     if ($partserror) {
 4180:         return &navmap_errormsg();
 4181:     }
 4182:     my $header;
 4183:     while ($ctr < $env{'form.totalparts'}) {
 4184: 	my $partid = $env{'form.partid_'.$ctr};
 4185: 	push(@partid,$partid);
 4186: 	$weight{$partid} = $env{'form.weight_'.$partid};
 4187: 	$ctr++;
 4188:     }
 4189:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4190:     my $totcolspan = 0;
 4191:     foreach my $partid (@partid) {
 4192: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 4193: 	    '<th align="center">'.&mt('New Score').'</th>';
 4194: 	$columns{$partid}=2;
 4195: 	foreach my $stores (@parts) {
 4196: 	    my ($part,$type) = &split_part_type($stores);
 4197: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 4198: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 4199: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
 4200: 	    $display =~ s/\[Part: \Q$part\E\]//;
 4201:             my $narrowtext = &mt('Tries');
 4202: 	    $display =~ s/Number of Attempts/$narrowtext/;
 4203: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 4204: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 4205: 	    $columns{$partid}+=2;
 4206: 	}
 4207:         $totcolspan += $columns{$partid};
 4208:     }
 4209:     foreach my $partid (@partid) {
 4210: 	my $display_part=&get_display_part($partid,$symb);
 4211: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 4212: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 4213: 	    '</th>';
 4214: 
 4215:     }
 4216:     $result .= &Apache::loncommon::end_data_table_header_row().
 4217: 	&Apache::loncommon::start_data_table_header_row().
 4218: 	$header.
 4219: 	&Apache::loncommon::end_data_table_header_row();
 4220:     my @noupdate;
 4221:     my ($updateCtr,$noupdateCtr) = (1,1);
 4222:     for ($i=0; $i<$env{'form.total'}; $i++) {
 4223: 	my $user = $env{'form.ctr'.$i};
 4224: 	my ($uname,$udom)=split(/:/,$user);
 4225: 	my %newrecord;
 4226: 	my $updateflag = 0;
 4227: 	my $usec=$classlist->{"$uname:$udom"}[5];
 4228: 	my $canmodify = &canmodify($usec);
 4229: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
 4230: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 4231: 	if (!$canmodify) {
 4232: 	    push(@noupdate,
 4233: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
 4234: 		 &mt('Not allowed to modify student')."</span></td>");
 4235: 	    next;
 4236: 	}
 4237:         my %aggregate = ();
 4238:         my $aggregateflag = 0;
 4239: 	$user=~s/:/_/; # colon doen't work in javascript for names
 4240: 	foreach (@partid) {
 4241: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 4242: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 4243: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 4244: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4245: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 4246: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 4247: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 4248: 	    my $score;
 4249: 	    if ($partial eq '') {
 4250: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 4251: 	    } elsif ($partial > 0) {
 4252: 		$score = 'correct_by_override';
 4253: 	    } elsif ($partial == 0) {
 4254: 		$score = 'incorrect_by_override';
 4255: 	    }
 4256: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 4257: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 4258: 
 4259: 	    $newrecord{'resource.'.$_.'.regrader'}=
 4260: 		"$env{'user.name'}:$env{'user.domain'}";
 4261: 	    if ($dropMenu eq 'reset status' &&
 4262: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 4263: 		$newrecord{'resource.'.$_.'.tries'} = '';
 4264: 		$newrecord{'resource.'.$_.'.solved'} = '';
 4265: 		$newrecord{'resource.'.$_.'.award'} = '';
 4266: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 4267: 		$updateflag = 1;
 4268:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 4269:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 4270:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 4271:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 4272:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4273:                     $aggregateflag = 1;
 4274:                 }
 4275: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 4276: 		$updateflag = 1;
 4277: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 4278: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 4279: 		$rec_update++;
 4280: 	    }
 4281: 
 4282: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4283: 		'<td align="center">'.$awarded.
 4284: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 4285: 
 4286: 
 4287: 	    my $partid=$_;
 4288: 	    foreach my $stores (@parts) {
 4289: 		my ($part,$type) = &split_part_type($stores);
 4290: 		if ($part !~ m/^\Q$partid\E/) { next;}
 4291: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 4292: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 4293: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 4294: 		if ($awarded ne '' && $awarded ne $old_aw) {
 4295: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 4296: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 4297: 		    $updateflag=1;
 4298: 		}
 4299: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 4300: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 4301: 	    }
 4302: 	}
 4303: 	$line.="\n";
 4304: 
 4305: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4306: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4307: 
 4308: 	if ($updateflag) {
 4309: 	    $count++;
 4310: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 4311: 				    $udom,$uname);
 4312: 
 4313: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 4314: 					      $cnum,$udom,$uname)) {
 4315: 		# need to figure out if should be in queue.
 4316: 		my %record =  
 4317: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 4318: 					     $udom,$uname);
 4319: 		my $all_graded = 1;
 4320: 		my $none_graded = 1;
 4321: 		foreach my $part (@parts) {
 4322: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 4323: 			$all_graded = 0;
 4324: 		    } else {
 4325: 			$none_graded = 0;
 4326: 		    }
 4327: 		}
 4328: 
 4329: 		if ($all_graded || $none_graded) {
 4330: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 4331: 							   $symb,$cdom,$cnum,
 4332: 							   $udom,$uname);
 4333: 		}
 4334: 	    }
 4335: 
 4336: 	    $result.=&Apache::loncommon::start_data_table_row().
 4337: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 4338: 		&Apache::loncommon::end_data_table_row();
 4339: 	    $updateCtr++;
 4340: 	} else {
 4341: 	    push(@noupdate,
 4342: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 4343: 	    $noupdateCtr++;
 4344: 	}
 4345:         if ($aggregateflag) {
 4346:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4347: 				  $cdom,$cnum);
 4348:         }
 4349:     }
 4350:     if (@noupdate) {
 4351:         my $numcols=$totcolspan+2;
 4352: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 4353: 	    '<td align="center" colspan="'.$numcols.'">'.
 4354: 	    &mt('No Changes Occurred For the Students Below').
 4355: 	    '</td>'.
 4356: 	    &Apache::loncommon::end_data_table_row();
 4357: 	foreach my $line (@noupdate) {
 4358: 	    $result.=
 4359: 		&Apache::loncommon::start_data_table_row().
 4360: 		$line.
 4361: 		&Apache::loncommon::end_data_table_row();
 4362: 	}
 4363:     }
 4364:     $result .= &Apache::loncommon::end_data_table();
 4365:     my $msg = '<p><b>'.
 4366: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 4367: 	    $rec_update,$count).'</b><br />'.
 4368: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 4369: 	'</b></p>';
 4370:     return $title.$msg.$result;
 4371: }
 4372: 
 4373: sub split_part_type {
 4374:     my ($partstr) = @_;
 4375:     my ($temp,@allparts)=split(/_/,$partstr);
 4376:     my $type=pop(@allparts);
 4377:     my $part=join('_',@allparts);
 4378:     return ($part,$type);
 4379: }
 4380: 
 4381: #------------- end of section for handling grading by section/class ---------
 4382: #
 4383: #----------------------------------------------------------------------------
 4384: 
 4385: 
 4386: #----------------------------------------------------------------------------
 4387: #
 4388: #-------------------------- Next few routines handles grading by csv upload
 4389: #
 4390: #--- Javascript to handle csv upload
 4391: sub csvupload_javascript_reverse_associate {
 4392:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4393:     my $error2=&mt('You need to specify at least one grading field');
 4394:   &js_escape(\$error1);
 4395:   &js_escape(\$error2);
 4396:   return(<<ENDPICK);
 4397:   function verify(vf) {
 4398:     var foundsomething=0;
 4399:     var founduname=0;
 4400:     var foundID=0;
 4401:     var foundclicker=0;
 4402:     for (i=0;i<=vf.nfields.value;i++) {
 4403:       tw=eval('vf.f'+i+'.selectedIndex');
 4404:       if (i==0 && tw!=0) { foundID=1; }
 4405:       if (i==1 && tw!=0) { founduname=1; }
 4406:       if (i==2 && tw!=0) { foundclicker=1; }
 4407:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
 4408:     }
 4409:     if (founduname==0 && foundID==0 && foundclicker==0) {
 4410: 	alert('$error1');
 4411: 	return;
 4412:     }
 4413:     if (foundsomething==0) {
 4414: 	alert('$error2');
 4415: 	return;
 4416:     }
 4417:     vf.submit();
 4418:   }
 4419:   function flip(vf,tf) {
 4420:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4421:     var i;
 4422:     for (i=0;i<=vf.nfields.value;i++) {
 4423:       //can not pick the same destination field for both name and domain
 4424:       if (((i ==0)||(i ==1)) && 
 4425:           ((tf==0)||(tf==1)) && 
 4426:           (i!=tf) &&
 4427:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4428:         eval('vf.f'+i+'.selectedIndex=0;')
 4429:       }
 4430:     }
 4431:   }
 4432: ENDPICK
 4433: }
 4434: 
 4435: sub csvupload_javascript_forward_associate {
 4436:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
 4437:     my $error2=&mt('You need to specify at least one grading field');
 4438:   &js_escape(\$error1);
 4439:   &js_escape(\$error2);
 4440:   return(<<ENDPICK);
 4441:   function verify(vf) {
 4442:     var foundsomething=0;
 4443:     var founduname=0;
 4444:     var foundID=0;
 4445:     var foundclicker=0;
 4446:     for (i=0;i<=vf.nfields.value;i++) {
 4447:       tw=eval('vf.f'+i+'.selectedIndex');
 4448:       if (tw==1) { foundID=1; }
 4449:       if (tw==2) { founduname=1; }
 4450:       if (tw==3) { foundclicker=1; }
 4451:       if (tw>4) { foundsomething=1; }
 4452:     }
 4453:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
 4454: 	alert('$error1');
 4455: 	return;
 4456:     }
 4457:     if (foundsomething==0) {
 4458: 	alert('$error2');
 4459: 	return;
 4460:     }
 4461:     vf.submit();
 4462:   }
 4463:   function flip(vf,tf) {
 4464:     var nw=eval('vf.f'+tf+'.selectedIndex');
 4465:     var i;
 4466:     //can not pick the same destination field twice
 4467:     for (i=0;i<=vf.nfields.value;i++) {
 4468:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 4469:         eval('vf.f'+i+'.selectedIndex=0;')
 4470:       }
 4471:     }
 4472:   }
 4473: ENDPICK
 4474: }
 4475: 
 4476: sub csvuploadmap_header {
 4477:     my ($request,$symb,$datatoken,$distotal)= @_;
 4478:     my $javascript;
 4479:     if ($env{'form.upfile_associate'} eq 'reverse') {
 4480: 	$javascript=&csvupload_javascript_reverse_associate();
 4481:     } else {
 4482: 	$javascript=&csvupload_javascript_forward_associate();
 4483:     }
 4484: 
 4485:     $symb = &Apache::lonenc::check_encrypt($symb);
 4486:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
 4487:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
 4488:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
 4489:     my $reverse=&mt("Reverse Association");
 4490:     $request->print(<<ENDPICK);
 4491: <br />
 4492: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 4493: <input type="hidden" name="associate"  value="" />
 4494: <input type="hidden" name="phase"      value="three" />
 4495: <input type="hidden" name="datatoken"  value="$datatoken" />
 4496: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 4497: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 4498: <input type="hidden" name="upfile_associate" 
 4499:                                        value="$env{'form.upfile_associate'}" />
 4500: <input type="hidden" name="symb"       value="$symb" />
 4501: <input type="hidden" name="command"    value="csvuploadoptions" />
 4502: <hr />
 4503: ENDPICK
 4504:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
 4505:     return '';
 4506: 
 4507: }
 4508: 
 4509: sub csvupload_fields {
 4510:     my ($symb,$errorref) = @_;
 4511:     my $toolsymb;
 4512:     if ($symb =~ /ext\.tool$/) {
 4513:         $toolsymb = $symb;
 4514:     }
 4515:     my (@parts) = &getpartlist($symb,$errorref);
 4516:     if (ref($errorref)) {
 4517:         if ($$errorref) {
 4518:             return;
 4519:         }
 4520:     }
 4521: 
 4522:     my @fields=(['ID','Student/Employee ID'],
 4523: 		['username','Student Username'],
 4524: 		['clicker','Clicker ID'],
 4525: 		['domain','Student Domain']);
 4526:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 4527:     foreach my $part (sort(@parts)) {
 4528: 	my @datum;
 4529: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
 4530: 	my $name=$part;
 4531: 	if (!$display) { $display = $name; }
 4532: 	@datum=($name,$display);
 4533: 	if ($name=~/^stores_(.*)_awarded/) {
 4534: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4535: 	}
 4536: 	push(@fields,\@datum);
 4537:     }
 4538:     return (@fields);
 4539: }
 4540: 
 4541: sub csvuploadmap_footer {
 4542:     my ($request,$i,$keyfields) =@_;
 4543:     my $buttontext = &mt('Assign Grades');
 4544:     $request->print(<<ENDPICK);
 4545: </table>
 4546: <input type="hidden" name="nfields" value="$i" />
 4547: <input type="hidden" name="keyfields" value="$keyfields" />
 4548: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 4549: </form>
 4550: ENDPICK
 4551: }
 4552: 
 4553: sub checkforfile_js {
 4554:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4555:     &js_escape(\$alertmsg);
 4556:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
 4557:     function checkUpload(formname) {
 4558: 	if (formname.upfile.value == "") {
 4559: 	    alert("$alertmsg");
 4560: 	    return false;
 4561: 	}
 4562: 	formname.submit();
 4563:     }
 4564: CSVFORMJS
 4565:     return $result;
 4566: }
 4567: 
 4568: sub upcsvScores_form {
 4569:     my ($request,$symb) = @_;
 4570:     if (!$symb) {return '';}
 4571:     my $result=&checkforfile_js();
 4572:     $result.=&Apache::loncommon::start_data_table().
 4573:              &Apache::loncommon::start_data_table_header_row().
 4574:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
 4575:              &Apache::loncommon::end_data_table_header_row().
 4576:              &Apache::loncommon::start_data_table_row().'<td>';
 4577:     my $upload=&mt("Upload Scores");
 4578:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4579:     my $ignore=&mt('Ignore First Line');
 4580:     $symb = &Apache::lonenc::check_encrypt($symb);
 4581:     $result.=<<ENDUPFORM;
 4582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4583: <input type="hidden" name="symb" value="$symb" />
 4584: <input type="hidden" name="command" value="csvuploadmap" />
 4585: $upfile_select
 4586: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4587: </form>
 4588: ENDUPFORM
 4589:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4590:                            &mt("How do I create a CSV file from a spreadsheet")).
 4591:              '</td>'.
 4592:             &Apache::loncommon::end_data_table_row().
 4593:             &Apache::loncommon::end_data_table();
 4594:     return $result;
 4595: }
 4596: 
 4597: 
 4598: sub csvuploadmap {
 4599:     my ($request,$symb)= @_;
 4600:     if (!$symb) {return '';}
 4601: 
 4602:     my $datatoken;
 4603:     if (!$env{'form.datatoken'}) {
 4604: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4605:     } else {
 4606: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4607:         if ($datatoken ne '') {
 4608: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
 4609:         }
 4610:     }
 4611:     my @records=&Apache::loncommon::upfile_record_sep();
 4612:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4613:     my ($i,$keyfields);
 4614:     if (@records) {
 4615:         my $fieldserror;
 4616: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4617:         if ($fieldserror) {
 4618:             $request->print(&navmap_errormsg());
 4619:             return;
 4620:         }
 4621: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4622: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4623: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4624: 							  \@fields);
 4625: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4626: 	    chop($keyfields);
 4627: 	} else {
 4628: 	    unshift(@fields,['none','']);
 4629: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4630: 							    \@fields);
 4631:             foreach my $rec (@records) {
 4632:                 my %temp = &Apache::loncommon::record_sep($rec);
 4633:                 if (%temp) {
 4634:                     $keyfields=join(',',sort(keys(%temp)));
 4635:                     last;
 4636:                 }
 4637:             }
 4638: 	}
 4639:     }
 4640:     &csvuploadmap_footer($request,$i,$keyfields);
 4641: 
 4642:     return '';
 4643: }
 4644: 
 4645: sub csvuploadoptions {
 4646:     my ($request,$symb)= @_;
 4647:     my $overwrite=&mt('Overwrite any existing score');
 4648:     $request->print(<<ENDPICK);
 4649: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4650: <input type="hidden" name="command"    value="csvuploadassign" />
 4651: <p>
 4652: <label>
 4653:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4654:    $overwrite
 4655: </label>
 4656: </p>
 4657: ENDPICK
 4658:     my %fields=&get_fields();
 4659:     if (!defined($fields{'domain'})) {
 4660: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4661: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
 4662:     }
 4663:     foreach my $key (sort(keys(%env))) {
 4664: 	if ($key !~ /^form\.(.*)$/) { next; }
 4665: 	my $cleankey=$1;
 4666: 	if ($cleankey eq 'command') { next; }
 4667: 	$request->print('<input type="hidden" name="'.$cleankey.
 4668: 			'"  value="'.$env{$key}.'" />'."\n");
 4669:     }
 4670:     # FIXME do a check for any duplicated user ids...
 4671:     # FIXME do a check for any invalid user ids?...
 4672:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
 4673: <hr /></form>'."\n");
 4674:     return '';
 4675: }
 4676: 
 4677: sub get_fields {
 4678:     my %fields;
 4679:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4680:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4681: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4682: 	    if ($env{'form.f'.$i} ne 'none') {
 4683: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4684: 	    }
 4685: 	} else {
 4686: 	    if ($env{'form.f'.$i} ne 'none') {
 4687: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4688: 	    }
 4689: 	}
 4690:     }
 4691:     return %fields;
 4692: }
 4693: 
 4694: sub csvuploadassign {
 4695:     my ($request,$symb)= @_;
 4696:     if (!$symb) {return '';}
 4697:     my $error_msg = '';
 4698:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4699:     if ($datatoken ne '') { 
 4700:         &Apache::loncommon::load_tmp_file($request,$datatoken);
 4701:     }
 4702:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4703:     my %fields=&get_fields();
 4704:     my $courseid=$env{'request.course.id'};
 4705:     my ($classlist) = &getclasslist('all',0);
 4706:     my @notallowed;
 4707:     my @skipped;
 4708:     my @warnings;
 4709:     my $countdone=0;
 4710:     foreach my $grade (@gradedata) {
 4711: 	my %entries=&Apache::loncommon::record_sep($grade);
 4712: 	my $domain;
 4713: 	if ($entries{$fields{'domain'}}) {
 4714: 	    $domain=$entries{$fields{'domain'}};
 4715: 	} else {
 4716: 	    $domain=$env{'form.default_domain'};
 4717: 	}
 4718: 	$domain=~s/\s//g;
 4719: 	my $username=$entries{$fields{'username'}};
 4720: 	$username=~s/\s//g;
 4721: 	if (!$username) {
 4722: 	    my $id=$entries{$fields{'ID'}};
 4723: 	    $id=~s/\s//g;
 4724:             if ($id ne '') {
 4725: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
 4726: 	        $username=$ids{$id};
 4727:             } else {
 4728:                 if ($entries{$fields{'clicker'}}) {
 4729:                     my $clicker = $entries{$fields{'clicker'}};
 4730:                     $clicker=~s/\s//g;
 4731:                     if ($clicker ne '') {
 4732:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
 4733:                         if ($clickers{$clicker} ne '') {  
 4734:                             my $match = 0;
 4735:                             my @inclass;
 4736:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
 4737:                                 if (exists($$classlist{"$poss:$domain"})) {
 4738:                                     $username = $poss;
 4739:                                     push(@inclass,$poss);
 4740:                                     $match ++;
 4741:                                     
 4742:                                 }
 4743:                             }
 4744:                             if ($match > 1) {
 4745:                                 undef($username); 
 4746:                                 $request->print('<p class="LC_warning">'.
 4747:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
 4748:                                                 $clicker,join(', ',@inclass)).'</p>');
 4749:                             }
 4750:                         }
 4751:                     }
 4752:                 }
 4753:             }
 4754: 	}
 4755: 	if (!exists($$classlist{"$username:$domain"})) {
 4756: 	    my $id=$entries{$fields{'ID'}};
 4757: 	    $id=~s/\s//g;
 4758:             my $clicker = $entries{$fields{'clicker'}};
 4759:             $clicker=~s/\s//g;
 4760:             if ($clicker) {
 4761:                 push(@skipped,"$clicker:$domain");
 4762: 	    } elsif ($id) {
 4763: 		push(@skipped,"$id:$domain");
 4764: 	    } else {
 4765: 		push(@skipped,"$username:$domain");
 4766: 	    }
 4767: 	    next;
 4768: 	}
 4769: 	my $usec=$classlist->{"$username:$domain"}[5];
 4770: 	if (!&canmodify($usec)) {
 4771: 	    push(@notallowed,"$username:$domain");
 4772: 	    next;
 4773: 	}
 4774: 	my %points;
 4775: 	my %grades;
 4776: 	foreach my $dest (keys(%fields)) {
 4777: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4778: 		$dest eq 'domain') { next; }
 4779: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4780: 	    if ($dest=~/stores_(.*)_points/) {
 4781: 		my $part=$1;
 4782: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4783: 					      $symb,$domain,$username);
 4784:                 if ($wgt) {
 4785:                     $entries{$fields{$dest}}=~s/\s//g;
 4786:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4787:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4788:                                           : 'correct_by_override';
 4789:                     if ($pcr>1) {
 4790:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
 4791:                     }
 4792:                     $grades{"resource.$part.awarded"}=$pcr;
 4793:                     $grades{"resource.$part.solved"}=$award;
 4794:                     $points{$part}=1;
 4795:                 } else {
 4796:                     $error_msg = "<br />" .
 4797:                         &mt("Some point values were assigned"
 4798:                             ." for problems with a weight "
 4799:                             ."of zero. These values were "
 4800:                             ."ignored.");
 4801:                 }
 4802: 	    } else {
 4803: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4804: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4805: 		my $store_key=$dest;
 4806: 		$store_key=~s/^stores/resource/;
 4807: 		$store_key=~s/_/\./g;
 4808: 		$grades{$store_key}=$entries{$fields{$dest}};
 4809: 	    }
 4810: 	}
 4811: 	if (! %grades) { 
 4812:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4813:         } else {
 4814: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4815: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4816: 					   $env{'request.course.id'},
 4817: 					   $domain,$username);
 4818: 	   if ($result eq 'ok') {
 4819: # Successfully stored
 4820: 	      $request->print('.');
 4821: # Remove from grading queue
 4822:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
 4823:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
 4824:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
 4825:                                              $domain,$username);
 4826:               $countdone++;
 4827:            } else {
 4828: 	      $request->print("<p><span class=\"LC_error\">".
 4829:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4830:                                   "$username:$domain",$result)."</span></p>");
 4831: 	   }
 4832: 	   $request->rflush();
 4833:         }
 4834:     }
 4835:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4836:     if (@warnings) {
 4837:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
 4838:         $request->print(join(', ',@warnings));
 4839:     }
 4840:     if (@skipped) {
 4841: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4842:         $request->print(join(', ',@skipped));
 4843:     }
 4844:     if (@notallowed) {
 4845: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4846: 	$request->print(join(', ',@notallowed));
 4847:     }
 4848:     $request->print("<br />\n");
 4849:     return $error_msg;
 4850: }
 4851: #------------- end of section for handling csv file upload ---------
 4852: #
 4853: #-------------------------------------------------------------------
 4854: #
 4855: #-------------- Next few routines handle grading by page/sequence
 4856: #
 4857: #--- Select a page/sequence and a student to grade
 4858: sub pickStudentPage {
 4859:     my ($request,$symb) = @_;
 4860: 
 4861:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4862:     &js_escape(\$alertmsg);
 4863:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
 4864: 
 4865: function checkPickOne(formname) {
 4866:     if (radioSelection(formname.student) == null) {
 4867: 	alert("$alertmsg");
 4868: 	return;
 4869:     }
 4870:     ptr = pullDownSelection(formname.selectpage);
 4871:     formname.page.value = formname["page"+ptr].value;
 4872:     formname.title.value = formname["title"+ptr].value;
 4873:     formname.submit();
 4874: }
 4875: 
 4876: LISTJAVASCRIPT
 4877:     &commonJSfunctions($request);
 4878: 
 4879:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4880:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4881:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4882: 
 4883:     my $result='<h3><span class="LC_info">&nbsp;'.
 4884: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4885: 
 4886:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4887:     my $map_error;
 4888:     my ($titles,$symbx) = &getSymbMap($map_error);
 4889:     if ($map_error) {
 4890:         $request->print(&navmap_errormsg());
 4891:         return; 
 4892:     }
 4893:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4894: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4895: #    my $type=($curpage =~ /\.(page|sequence)/);
 4896: 
 4897:     # Collection of hidden fields
 4898:     my $ctr=0;
 4899:     foreach (@$titles) {
 4900:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4901:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4902:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4903:         $ctr++;
 4904:     }
 4905:     $result.='<input type="hidden" name="page" />'."\n".
 4906:         '<input type="hidden" name="title" />'."\n";
 4907: 
 4908:     $result.=&build_section_inputs();
 4909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4910:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4911: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4912: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 4913: 
 4914:     # Show grading options
 4915:     $result.=&Apache::lonhtmlcommon::start_pick_box();
 4916:     my $select = '<select name="selectpage">'."\n";
 4917:     $ctr=0;
 4918:     foreach (@$titles) {
 4919: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4920: 	$select.='<option value="'.$ctr.'"'.
 4921: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
 4922: 	    '>'.$showtitle.'</option>'."\n";
 4923: 	$ctr++;
 4924:     }
 4925:     $select.= '</select>';
 4926: 
 4927:     $result.=
 4928:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
 4929:        .$select
 4930:        .&Apache::lonhtmlcommon::row_closure();
 4931: 
 4932:     $result.=
 4933:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
 4934:        .'<label><input type="radio" name="vProb" value="no"'
 4935:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
 4936:        .'<label><input type="radio" name="vProb" value="yes" />'
 4937:            .&mt('yes').'</label>'."\n"
 4938:        .&Apache::lonhtmlcommon::row_closure();
 4939: 
 4940:     $result.=
 4941:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
 4942:        .'<label><input type="radio" name="lastSub" value="none" /> '
 4943:            .&mt('none').' </label>'."\n"
 4944:        .'<label><input type="radio" name="lastSub" value="datesub"'
 4945:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
 4946:        .'<label><input type="radio" name="lastSub" value="all" /> '
 4947:            .&mt('all submissions with details').' </label>'
 4948:        .&Apache::lonhtmlcommon::row_closure();
 4949:     
 4950:     $result.=
 4951:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
 4952:        .'<input type="text" name="CODE" value="" />'
 4953:        .&Apache::lonhtmlcommon::row_closure(1)
 4954:        .&Apache::lonhtmlcommon::end_pick_box();
 4955: 
 4956:     # Show list of students to select for grading
 4957:     $result.='<br /><input type="button" '.
 4958:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4959: 
 4960:     $request->print($result);
 4961: 
 4962:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4963: 	&Apache::loncommon::start_data_table().
 4964: 	&Apache::loncommon::start_data_table_header_row().
 4965: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4966: 	'<th>'.&nameUserString('header').'</th>'.
 4967: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4968: 	'<th>'.&nameUserString('header').'</th>'.
 4969: 	&Apache::loncommon::end_data_table_header_row();
 4970:  
 4971:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4972:     my $ptr = 1;
 4973:     foreach my $student (sort 
 4974: 			 {
 4975: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4976: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4977: 			     }
 4978: 			     return $a cmp $b;
 4979: 			 } (keys(%$fullname))) {
 4980: 	my ($uname,$udom) = split(/:/,$student);
 4981: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4982:                                   : '</td>');
 4983: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4984: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4985: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4986: 	$studentTable.=
 4987: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4988:                          : '');
 4989: 	$ptr++;
 4990:     }
 4991:     if ($ptr%2 == 0) {
 4992: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4993: 	    &Apache::loncommon::end_data_table_row();
 4994:     }
 4995:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4996:     $studentTable.='<input type="button" '.
 4997:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4998: 
 4999:     $request->print($studentTable);
 5000: 
 5001:     return '';
 5002: }
 5003: 
 5004: sub getSymbMap {
 5005:     my ($map_error) = @_;
 5006:     my $navmap = Apache::lonnavmaps::navmap->new();
 5007:     unless (ref($navmap)) {
 5008:         if (ref($map_error)) {
 5009:             $$map_error = 'navmap';
 5010:         }
 5011:         return;
 5012:     }
 5013:     my %symbx = ();
 5014:     my @titles = ();
 5015:     my $minder = 0;
 5016: 
 5017:     # Gather every sequence that has problems.
 5018:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 5019: 					       1,0,1);
 5020:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 5021: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
 5022: 	    my $title = $minder.'.'.
 5023: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 5024: 	    push(@titles, $title); # minder in case two titles are identical
 5025: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 5026: 	    $minder++;
 5027: 	}
 5028:     }
 5029:     return \@titles,\%symbx;
 5030: }
 5031: 
 5032: #
 5033: #--- Displays a page/sequence w/wo problems, w/wo submissions
 5034: sub displayPage {
 5035:     my ($request,$symb) = @_;
 5036:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5037:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5038:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5039:     my $pageTitle = $env{'form.page'};
 5040:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5041:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5042:     my $usec=$classlist->{$env{'form.student'}}[5];
 5043: 
 5044:     #need to make sure we have the correct data for later EXT calls, 
 5045:     #thus invalidate the cache
 5046:     &Apache::lonnet::devalidatecourseresdata(
 5047:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 5048:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 5049:     &Apache::lonnet::clear_EXT_cache_status();
 5050: 
 5051:     if (!&canview($usec)) {
 5052:         $request->print(
 5053:             '<span class="LC_warning">'.
 5054:             &mt('Unable to view requested student. ([_1])',
 5055:                     $env{'form.student'}).
 5056:             '</span>');
 5057:         return;
 5058:     }
 5059:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5060:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 5061: 	'</h3>'."\n";
 5062:     $env{'form.CODE'} = uc($env{'form.CODE'});
 5063:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 5064: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 5065:     } else {
 5066: 	delete($env{'form.CODE'});
 5067:     }
 5068:     &sub_page_js($request);
 5069:     $request->print($result);
 5070: 
 5071:     my $navmap = Apache::lonnavmaps::navmap->new();
 5072:     unless (ref($navmap)) {
 5073:         $request->print(&navmap_errormsg());
 5074:         return;
 5075:     }
 5076:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 5077:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5078:     if (!$map) {
 5079: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 5080: 	return; 
 5081:     }
 5082:     my $iterator = $navmap->getIterator($map->map_start(),
 5083: 					$map->map_finish());
 5084: 
 5085:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 5086: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 5087: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 5088: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 5089: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 5090: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 5091: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 5092: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
 5093: 
 5094:     if (defined($env{'form.CODE'})) {
 5095: 	$studentTable.=
 5096: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 5097:     }
 5098:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 5099: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 5100: 
 5101:     $studentTable.='&nbsp;<span class="LC_info">'.
 5102:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 5103:         '</span>'."\n".
 5104: 	&Apache::loncommon::start_data_table().
 5105: 	&Apache::loncommon::start_data_table_header_row().
 5106: 	'<th>'.&mt('Prob.').'</th>'.
 5107: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 5108: 	&Apache::loncommon::end_data_table_header_row();
 5109: 
 5110:     &Apache::lonxml::clear_problem_counter();
 5111:     my ($depth,$question,$prob) = (1,1,1);
 5112:     $iterator->next(); # skip the first BEGIN_MAP
 5113:     my $curRes = $iterator->next(); # for "current resource"
 5114:     while ($depth > 0) {
 5115:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5116:         if($curRes == $iterator->END_MAP) { $depth--; }
 5117: 
 5118:         if (ref($curRes) && $curRes->is_gradable()) {
 5119: 	    my $parts = $curRes->parts();
 5120:             my $title = $curRes->compTitle();
 5121: 	    my $symbx = $curRes->symb();
 5122:             my $is_tool = ($symbx =~ /ext\.tool$/);
 5123: 	    $studentTable.=
 5124: 		&Apache::loncommon::start_data_table_row().
 5125: 		'<td align="center" valign="top" >'.$prob.
 5126: 		(scalar(@{$parts}) == 1 ? '' 
 5127: 		                        : '<br />('.&mt('[_1]parts',
 5128: 							scalar(@{$parts}).'&nbsp;').')'
 5129: 		 ).
 5130: 		 '</td>';
 5131: 	    $studentTable.='<td valign="top">';
 5132: 	    my %form = ('CODE' => $env{'form.CODE'},);
 5133:             if ($is_tool) {
 5134:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
 5135:             } else {
 5136: 	        if ($env{'form.vProb'} eq 'yes' ) {
 5137: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 5138: 					         undef,'both',\%form);
 5139: 	        } else {
 5140: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 5141: 		    $companswer =~ s|<form(.*?)>||g;
 5142: 		    $companswer =~ s|</form>||g;
 5143: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 5144: #		        $companswer =~ s/$1/ /ms;
 5145: #		        $request->print('match='.$1."<br />\n");
 5146: #		    }
 5147: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 5148: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 5149: 		}
 5150: 	    }
 5151: 
 5152: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5153: 
 5154: 	    if ($env{'form.lastSub'} eq 'datesub') {
 5155: 		if ($record{'version'} eq '') {
 5156:                     my $msg = &mt('No recorded submission for this problem.');
 5157:                     if ($is_tool) {
 5158:                         $msg = &mt('No recorded transactions for this external tool');
 5159:                     }
 5160: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
 5161: 		} else {
 5162: 		    my %responseType = ();
 5163: 		    foreach my $partid (@{$parts}) {
 5164: 			my @responseIds =$curRes->responseIds($partid);
 5165: 			my @responseType =$curRes->responseType($partid);
 5166: 			my %responseIds;
 5167: 			for (my $i=0;$i<=$#responseIds;$i++) {
 5168: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 5169: 			}
 5170: 			$responseType{$partid} = \%responseIds;
 5171: 		    }
 5172: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 5173: 		}
 5174: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 5175: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 5176:                 my $identifier = (&canmodify($usec)? $prob : ''); 
 5177: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 5178: 									$env{'request.course.id'},
 5179: 									'','.submission',undef,
 5180:                                                                         $usec,$identifier);
 5181:  
 5182: 	    }
 5183: 	    if (&canmodify($usec)) {
 5184:             $studentTable.=&gradeBox_start();
 5185: 		foreach my $partid (@{$parts}) {
 5186: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 5187: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 5188: 		    $question++;
 5189: 		}
 5190:             $studentTable.=&gradeBox_end();
 5191: 		$prob++;
 5192: 	    }
 5193: 	    $studentTable.='</td></tr>';
 5194: 
 5195: 	}
 5196:         $curRes = $iterator->next();
 5197:     }
 5198: 
 5199:     $studentTable.=
 5200:         '</table>'."\n".
 5201:         '<input type="button" value="'.&mt('Save').'" '.
 5202:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 5203:         '</form>'."\n";
 5204:     $request->print($studentTable);
 5205: 
 5206:     return '';
 5207: }
 5208: 
 5209: sub displaySubByDates {
 5210:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 5211:     my $isCODE=0;
 5212:     my $isTask = ($symb =~/\.task$/);
 5213:     my $is_tool = ($symb =~/\.tool$/);
 5214:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 5215:     my $studentTable=&Apache::loncommon::start_data_table().
 5216: 	&Apache::loncommon::start_data_table_header_row().
 5217: 	'<th>'.&mt('Date/Time').'</th>'.
 5218: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 5219:         ($isTask?'<th>'.&mt('Version').'</th>':'').
 5220: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
 5221: 	'<th>'.&mt('Status').'</th>'.
 5222: 	&Apache::loncommon::end_data_table_header_row();
 5223:     my ($version);
 5224:     my %mark;
 5225:     my %orders;
 5226:     $mark{'correct_by_student'} = $checkIcon;
 5227:     if (!exists($$record{'1:timestamp'})) {
 5228:         if ($is_tool) {
 5229:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
 5230:         } else {
 5231:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 5232:         }
 5233:     }
 5234: 
 5235:     my $interaction;
 5236:     my $no_increment = 1;
 5237:     my (%lastrndseed,%lasttype);
 5238:     for ($version=1;$version<=$$record{'version'};$version++) {
 5239: 	my $timestamp = 
 5240: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 5241: 	if (exists($$record{$version.':resource.0.version'})) {
 5242: 	    $interaction = $$record{$version.':resource.0.version'};
 5243: 	}
 5244:         if ($isTask && $env{'form.previousversion'}) {
 5245:             next unless ($interaction == $env{'form.previousversion'});
 5246:         }
 5247: 	my $where = ($isTask ? "$version:resource.$interaction"
 5248: 		             : "$version:resource");
 5249: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 5250: 	    '<td>'.$timestamp.'</td>';
 5251: 	if ($isCODE) {
 5252: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 5253: 	}
 5254:         if ($isTask) {
 5255:             $studentTable.='<td>'.$interaction.'</td>';
 5256:         }
 5257: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 5258: 	my @displaySub = ();
 5259: 	foreach my $partid (@{$parts}) {
 5260:             my ($hidden,$type);
 5261:             $type = $$record{$version.':resource.'.$partid.'.type'};
 5262:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 5263:                 $hidden = 1;
 5264:             }
 5265:             my @matchKey;
 5266:             if ($isTask) {
 5267:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
 5268:             } elsif ($is_tool) {
 5269:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
 5270:             } else {
 5271:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
 5272:             }
 5273: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 5274: 	    my $display_part=&get_display_part($partid,$symb);
 5275: 	    foreach my $matchKey (@matchKey) {
 5276: 		if (exists($$record{$version.':'.$matchKey}) &&
 5277: 		    $$record{$version.':'.$matchKey} ne '') {
 5278:                     if ($is_tool) {
 5279:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
 5280:                     } else {
 5281: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 5282: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 5283:                         $displaySub[0].='<span class="LC_nobreak">';
 5284:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 5285:                                        .' <span class="LC_internal_info">'
 5286:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
 5287:                                        .'</span>'
 5288:                                        .' <b>';
 5289:                         if ($hidden) {
 5290:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
 5291:                         } else {
 5292:                             my ($trial,$rndseed,$newvariation);
 5293:                             if ($type eq 'randomizetry') {
 5294:                                 $trial = $$record{"$where.$partid.tries"};
 5295:                                 $rndseed = $$record{"$where.$partid.rndseed"};
 5296:                             }
 5297: 		            if ($$record{"$where.$partid.tries"} eq '') {
 5298: 			        $displaySub[0].=&mt('Trial not counted');
 5299: 		            } else {
 5300: 			        $displaySub[0].=&mt('Trial: [_1]',
 5301: 					        $$record{"$where.$partid.tries"});
 5302:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
 5303:                                     if (($rndseed ne $lastrndseed{$partid}) &&
 5304:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
 5305:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
 5306:                                     }
 5307:                                 }
 5308:                                 $lastrndseed{$partid} = $rndseed;
 5309:                                 $lasttype{$partid} = $type;
 5310: 		            }
 5311: 		            my $responseType=($isTask ? 'Task'
 5312:                                               : $responseType->{$partid}->{$responseId});
 5313: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
 5314: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 5315: 			        $orders{$partid}->{$responseId}=
 5316: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
 5317:                                                $no_increment,$type,$trial,$rndseed);
 5318: 		            }
 5319: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 5320: 		            $displaySub[0].='&nbsp; '.
 5321: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 5322:                         }
 5323:                     }
 5324: 		}
 5325: 	    }
 5326: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 5327: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 5328: 				    $$record{"$where.$partid.checkedin"},
 5329: 				    $$record{"$where.$partid.checkedin.slot"}).
 5330: 					'<br />';
 5331: 	    }
 5332: 	    if (exists $$record{"$where.$partid.award"}) {
 5333: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 5334: 		    lc($$record{"$where.$partid.award"}).' '.
 5335: 		    $mark{$$record{"$where.$partid.solved"}}.
 5336: 		    '<br />';
 5337: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
 5338: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
 5339: 		    $displaySub[1].=&mt('Grade passed back by external tool');
 5340: 		}
 5341: 	    }
 5342: 	    if (exists $$record{"$where.$partid.regrader"}) {
 5343: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
 5344: 		unless ($is_tool) {
 5345: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5346: 		}
 5347: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 5348: 		$displaySub[2].=
 5349: 		    $$record{"$version:resource.$partid.regrader"};
 5350:                 unless ($is_tool) {
 5351: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
 5352:                 }
 5353: 	    }
 5354: 	}
 5355: 	# needed because old essay regrader has not parts info
 5356: 	if (exists $$record{"$version:resource.regrader"}) {
 5357: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 5358: 	}
 5359: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 5360: 	if ($displaySub[2]) {
 5361: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 5362: 	}
 5363: 	$studentTable.='&nbsp;</td>'.
 5364: 	    &Apache::loncommon::end_data_table_row();
 5365:     }
 5366:     $studentTable.=&Apache::loncommon::end_data_table();
 5367:     return $studentTable;
 5368: }
 5369: 
 5370: sub updateGradeByPage {
 5371:     my ($request,$symb) = @_;
 5372: 
 5373:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 5374:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 5375:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 5376:     my $pageTitle = $env{'form.page'};
 5377:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 5378:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 5379:     my $usec=$classlist->{$env{'form.student'}}[5];
 5380:     if (!&canmodify($usec)) {
 5381: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 5382: 	return;
 5383:     }
 5384:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 5385:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 5386: 	'</h3>'."\n";
 5387: 
 5388:     $request->print($result);
 5389: 
 5390: 
 5391:     my $navmap = Apache::lonnavmaps::navmap->new();
 5392:     unless (ref($navmap)) {
 5393:         $request->print(&navmap_errormsg());
 5394:         return;
 5395:     }
 5396:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 5397:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 5398:     if (!$map) {
 5399: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 5400: 	return; 
 5401:     }
 5402:     my $iterator = $navmap->getIterator($map->map_start(),
 5403: 					$map->map_finish());
 5404: 
 5405:     my $studentTable=
 5406: 	&Apache::loncommon::start_data_table().
 5407: 	&Apache::loncommon::start_data_table_header_row().
 5408: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 5409: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 5410: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 5411: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 5412: 	&Apache::loncommon::end_data_table_header_row();
 5413: 
 5414:     $iterator->next(); # skip the first BEGIN_MAP
 5415:     my $curRes = $iterator->next(); # for "current resource"
 5416:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
 5417:     while ($depth > 0) {
 5418:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 5419:         if($curRes == $iterator->END_MAP) { $depth--; }
 5420: 
 5421:         if (ref($curRes) && $curRes->is_problem()) {
 5422: 	    my $parts = $curRes->parts();
 5423:             my $title = $curRes->compTitle();
 5424: 	    my $symbx = $curRes->symb();
 5425: 	    $studentTable.=
 5426: 		&Apache::loncommon::start_data_table_row().
 5427: 		'<td align="center" valign="top" >'.$prob.
 5428: 		(scalar(@{$parts}) == 1 ? '' 
 5429:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 5430: 		.')').'</td>';
 5431: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 5432: 
 5433: 	    my %newrecord=();
 5434: 	    my @displayPts=();
 5435:             my %aggregate = ();
 5436:             my $aggregateflag = 0;
 5437:             if ($env{'form.HIDE'.$prob}) {
 5438:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 5439:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
 5440:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
 5441:                 $hideflag += $numchgs;
 5442:             }
 5443: 	    foreach my $partid (@{$parts}) {
 5444: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 5445: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 5446: 
 5447: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 5448: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 5449: 		my $partial = $newpts/$wgt;
 5450: 		my $score;
 5451: 		if ($partial > 0) {
 5452: 		    $score = 'correct_by_override';
 5453: 		} elsif ($newpts ne '') { #empty is taken as 0
 5454: 		    $score = 'incorrect_by_override';
 5455: 		}
 5456: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 5457: 		if ($dropMenu eq 'excused') {
 5458: 		    $partial = '';
 5459: 		    $score = 'excused';
 5460: 		} elsif ($dropMenu eq 'reset status'
 5461: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 5462: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 5463: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 5464: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 5465: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 5466: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 5467: 		    $changeflag++;
 5468: 		    $newpts = '';
 5469:                     
 5470:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 5471:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 5472:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 5473:                     if ($aggtries > 0) {
 5474:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 5475:                         $aggregateflag = 1;
 5476:                     }
 5477: 		}
 5478: 		my $display_part=&get_display_part($partid,$curRes->symb());
 5479: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 5480: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5481: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 5482: 		    '&nbsp;<br />';
 5483: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 5484: 		     (($score eq 'excused') ? 'excused' : $newpts).
 5485: 		    '&nbsp;<br />';
 5486: 		$question++;
 5487: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 5488: 
 5489: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 5490: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 5491: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 5492: 		    if (scalar(keys(%newrecord)) > 0);
 5493: 
 5494: 		$changeflag++;
 5495: 	    }
 5496: 	    if (scalar(keys(%newrecord)) > 0) {
 5497: 		my %record = 
 5498: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 5499: 					     $udom,$uname);
 5500: 
 5501: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 5502: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 5503: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 5504: 		    $newrecord{'resource.CODE'} = '';
 5505: 		}
 5506: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 5507: 					$udom,$uname);
 5508: 		%record = &Apache::lonnet::restore($symbx,
 5509: 						   $env{'request.course.id'},
 5510: 						   $udom,$uname);
 5511: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 5512: 					     $cdom,$cnum,$udom,$uname);
 5513: 	    }
 5514: 	    
 5515:             if ($aggregateflag) {
 5516:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 5517:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 5518:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 5519:             }
 5520: 
 5521: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 5522: 		'<td valign="top">'.$displayPts[1].'</td>'.
 5523: 		&Apache::loncommon::end_data_table_row();
 5524: 
 5525: 	    $prob++;
 5526: 	}
 5527:         $curRes = $iterator->next();
 5528:     }
 5529: 
 5530:     $studentTable.=&Apache::loncommon::end_data_table();
 5531:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 5532: 		  &mt('The scores were changed for [quant,_1,problem].',
 5533: 		  $changeflag).'<br />');
 5534:     my $hidemsg=($hideflag == 0 ? '' :
 5535:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
 5536:                      $hideflag).'<br />');
 5537:     $request->print($hidemsg.$grademsg.$studentTable);
 5538: 
 5539:     return '';
 5540: }
 5541: 
 5542: #-------- end of section for handling grading by page/sequence ---------
 5543: #
 5544: #-------------------------------------------------------------------
 5545: 
 5546: #-------------------- Bubblesheet (Scantron) Grading -------------------
 5547: #
 5548: #------ start of section for handling grading by page/sequence ---------
 5549: 
 5550: =pod
 5551: 
 5552: =head1 Bubble sheet grading routines
 5553: 
 5554:   For this documentation:
 5555: 
 5556:    'scanline' refers to the full line of characters
 5557:    from the file that we are parsing that represents one entire sheet
 5558: 
 5559:    'bubble line' refers to the data
 5560:    representing the line of bubbles that are on the physical bubblesheet
 5561: 
 5562: 
 5563: The overall process is that a scanned in bubblesheet data is uploaded
 5564: into a course. When a user wants to grade, they select a
 5565: sequence/folder of resources, a file of bubblesheet info, and pick
 5566: one of the predefined configurations for what each scanline looks
 5567: like.
 5568: 
 5569: Next each scanline is checked for any errors of either 'missing
 5570: bubbles' (it's an error because it may have been mis-scanned
 5571: because too light bubbling), 'double bubble' (each bubble line should
 5572: have no more than one letter picked), invalid or duplicated CODE,
 5573: invalid student/employee ID
 5574: 
 5575: If the CODE option is used that determines the randomization of the
 5576: homework problems, either way the student/employee ID is looked up into a
 5577: username:domain.
 5578: 
 5579: During the validation phase the instructor can choose to skip scanlines. 
 5580: 
 5581: After the validation phase, there are now 3 bubblesheet files
 5582: 
 5583:   scantron_original_filename (unmodified original file)
 5584:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 5585:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 5586: 
 5587: Also there is a separate hash nohist_scantrondata that contains extra
 5588: correction information that isn't representable in the bubblesheet
 5589: file (see &scantron_getfile() for more information)
 5590: 
 5591: After all scanlines are either valid, marked as valid or skipped, then
 5592: foreach line foreach problem in the picked sequence, an ssi request is
 5593: made that simulates a user submitting their selected letter(s) against
 5594: the homework problem.
 5595: 
 5596: =over 4
 5597: 
 5598: 
 5599: 
 5600: =item defaultFormData
 5601: 
 5602:   Returns html hidden inputs used to hold context/default values.
 5603: 
 5604:  Arguments:
 5605:   $symb - $symb of the current resource 
 5606: 
 5607: =cut
 5608: 
 5609: sub defaultFormData {
 5610:     my ($symb)=@_;
 5611:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
 5612: }
 5613: 
 5614: 
 5615: =pod 
 5616: 
 5617: =item getSequenceDropDown
 5618: 
 5619:    Return html dropdown of possible sequences to grade
 5620:  
 5621:  Arguments:
 5622:    $symb - $symb of the current resource
 5623:    $map_error - ref to scalar which will container error if
 5624:                 $navmap object is unavailable in &getSymbMap().
 5625: 
 5626: =cut
 5627: 
 5628: sub getSequenceDropDown {
 5629:     my ($symb,$map_error)=@_;
 5630:     my $result='<select name="selectpage">'."\n";
 5631:     my ($titles,$symbx) = &getSymbMap($map_error);
 5632:     if (ref($map_error)) {
 5633:         return if ($$map_error);
 5634:     }
 5635:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5636:     my $ctr=0;
 5637:     foreach (@$titles) {
 5638: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5639: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5640: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5641: 	    '>'.$showtitle.'</option>'."\n";
 5642: 	$ctr++;
 5643:     }
 5644:     $result.= '</select>';
 5645:     return $result;
 5646: }
 5647: 
 5648: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5649:                                    # key is zero-based index - 0, 1, 2 ...
 5650: 
 5651: my %first_bubble_line;             # First bubble line no. for each bubble.
 5652: 
 5653: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5654:                                    # matchresponse or rankresponse, where 
 5655:                                    # an individual response can have multiple 
 5656:                                    # lines
 5657: 
 5658: my %responsetype_per_response;     # responsetype for each response
 5659: 
 5660: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
 5661:                                    # numbered response. Needed when randomorder
 5662:                                    # or randompick are in use. Key is ID, value 
 5663:                                    # is response number.
 5664: 
 5665: # Save and restore the bubble lines array to the form env.
 5666: 
 5667: 
 5668: sub save_bubble_lines {
 5669:     foreach my $line (keys(%bubble_lines_per_response)) {
 5670: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5671: 	$env{"form.scantron.first_bubble_line.$line"} =
 5672: 	    $first_bubble_line{$line};
 5673:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5674:             $subdivided_bubble_lines{$line};
 5675:         $env{"form.scantron.responsetype.$line"} =
 5676:             $responsetype_per_response{$line};
 5677:     }
 5678:     foreach my $resid (keys(%masterseq_id_responsenum)) {
 5679:         my $line = $masterseq_id_responsenum{$resid};
 5680:         $env{"form.scantron.residpart.$line"} = $resid;
 5681:     }
 5682: }
 5683: 
 5684: 
 5685: sub restore_bubble_lines {
 5686:     my $line = 0;
 5687:     %bubble_lines_per_response = ();
 5688:     %masterseq_id_responsenum = ();
 5689:     while ($env{"form.scantron.bubblelines.$line"}) {
 5690: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5691: 	$bubble_lines_per_response{$line} = $value;
 5692: 	$first_bubble_line{$line}  =
 5693: 	    $env{"form.scantron.first_bubble_line.$line"};
 5694:         $subdivided_bubble_lines{$line} =
 5695:             $env{"form.scantron.sub_bubblelines.$line"};
 5696:         $responsetype_per_response{$line} =
 5697:             $env{"form.scantron.responsetype.$line"};
 5698:         my $id = $env{"form.scantron.residpart.$line"};
 5699:         $masterseq_id_responsenum{$id} = $line;
 5700: 	$line++;
 5701:     }
 5702: }
 5703: 
 5704: =pod 
 5705: 
 5706: =item scantron_filenames
 5707: 
 5708:    Returns a list of the scantron files in the current course 
 5709: 
 5710: =cut
 5711: 
 5712: sub scantron_filenames {
 5713:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5714:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5715:     my $getpropath = 1;
 5716:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
 5717:                                                         $cname,$getpropath);
 5718:     my @possiblenames;
 5719:     if (ref($dirlist) eq 'ARRAY') {
 5720:         foreach my $filename (sort(@{$dirlist})) {
 5721: 	    ($filename)=split(/&/,$filename);
 5722: 	    if ($filename!~/^scantron_orig_/) { next ; }
 5723: 	    $filename=~s/^scantron_orig_//;
 5724: 	    push(@possiblenames,$filename);
 5725:         }
 5726:     }
 5727:     return @possiblenames;
 5728: }
 5729: 
 5730: =pod 
 5731: 
 5732: =item scantron_uploads
 5733: 
 5734:    Returns  html drop-down list of scantron files in current course.
 5735: 
 5736:  Arguments:
 5737:    $file2grade - filename to set as selected in the dropdown
 5738: 
 5739: =cut
 5740: 
 5741: sub scantron_uploads {
 5742:     my ($file2grade) = @_;
 5743:     my $result=	'<select name="scantron_selectfile">';
 5744:     $result.="<option></option>";
 5745:     foreach my $filename (sort(&scantron_filenames())) {
 5746: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5747:     }
 5748:     $result.="</select>";
 5749:     return $result;
 5750: }
 5751: 
 5752: =pod 
 5753: 
 5754: =item scantron_scantab
 5755: 
 5756:   Returns html drop down of the scantron formats in the scantronformat.tab
 5757:   file.
 5758: 
 5759: =cut
 5760: 
 5761: sub scantron_scantab {
 5762:     my $result='<select name="scantron_format">'."\n";
 5763:     $result.='<option></option>'."\n";
 5764:     my @lines = &get_scantronformat_file();
 5765:     if (@lines > 0) {
 5766:         foreach my $line (@lines) {
 5767:             next if (($line =~ /^\#/) || ($line eq ''));
 5768: 	    my ($name,$descrip)=split(/:/,$line);
 5769: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5770:         }
 5771:     }
 5772:     $result.='</select>'."\n";
 5773:     return $result;
 5774: }
 5775: 
 5776: =pod
 5777: 
 5778: =item get_scantronformat_file
 5779: 
 5780:   Returns an array containing lines from the scantron format file for
 5781:   the domain of the course.
 5782: 
 5783:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5784:   lines are from this file.
 5785: 
 5786:   Otherwise, if a default.tab has been published in RES space by the 
 5787:   domainconfig user, lines are from this file.
 5788: 
 5789:   Otherwise, fall back to getting lines from the legacy file on the
 5790:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5791: 
 5792: =cut
 5793: 
 5794: sub get_scantronformat_file {
 5795:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5796:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5797:     my $gottab = 0;
 5798:     my @lines;
 5799:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5800:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5801:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5802:             if ($formatfile ne '-1') {
 5803:                 @lines = split("\n",$formatfile,-1);
 5804:                 $gottab = 1;
 5805:             }
 5806:         }
 5807:     }
 5808:     if (!$gottab) {
 5809:         my $confname = $cdom.'-domainconfig';
 5810:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5811:         my $formatfile =  &Apache::lonnet::getfile($default);
 5812:         if ($formatfile ne '-1') {
 5813:             @lines = split("\n",$formatfile,-1);
 5814:             $gottab = 1;
 5815:         }
 5816:     }
 5817:     if (!$gottab) {
 5818:         my @domains = &Apache::lonnet::current_machine_domains();
 5819:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5820:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5821:             @lines = <$fh>;
 5822:             close($fh);
 5823:         } else {
 5824:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5825:             @lines = <$fh>;
 5826:             close($fh);
 5827:         }
 5828:     }
 5829:     return @lines;
 5830: }
 5831: 
 5832: =pod 
 5833: 
 5834: =item scantron_CODElist
 5835: 
 5836:   Returns html drop down of the saved CODE lists from current course,
 5837:   generated from earlier printings.
 5838: 
 5839: =cut
 5840: 
 5841: sub scantron_CODElist {
 5842:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5843:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5844:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5845:     my $namechoice='<option></option>';
 5846:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5847: 	if ($name =~ /^error: 2 /) { next; }
 5848: 	if ($name =~ /^type\0/) { next; }
 5849: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5850:     }
 5851:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5852:     return $namechoice;
 5853: }
 5854: 
 5855: =pod 
 5856: 
 5857: =item scantron_CODEunique
 5858: 
 5859:   Returns the html for "Each CODE to be used once" radio.
 5860: 
 5861: =cut
 5862: 
 5863: sub scantron_CODEunique {
 5864:     my $result='<span class="LC_nobreak">
 5865:                  <label><input type="radio" name="scantron_CODEunique"
 5866:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5867:                 </span>
 5868:                 <span class="LC_nobreak">
 5869:                  <label><input type="radio" name="scantron_CODEunique"
 5870:                         value="no" />'.&mt('No').' </label>
 5871:                 </span>';
 5872:     return $result;
 5873: }
 5874: 
 5875: =pod 
 5876: 
 5877: =item scantron_selectphase
 5878: 
 5879:   Generates the initial screen to start the bubblesheet process.
 5880:   Allows for - starting a grading run.
 5881:              - downloading existing scan data (original, corrected
 5882:                                                 or skipped info)
 5883: 
 5884:              - uploading new scan data
 5885: 
 5886:  Arguments:
 5887:   $r          - The Apache request object
 5888:   $file2grade - name of the file that contain the scanned data to score
 5889: 
 5890: =cut
 5891: 
 5892: sub scantron_selectphase {
 5893:     my ($r,$file2grade,$symb) = @_;
 5894:     if (!$symb) {return '';}
 5895:     my $map_error;
 5896:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5897:     if ($map_error) {
 5898:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5899:         return;
 5900:     }
 5901:     my $default_form_data=&defaultFormData($symb);
 5902:     my $file_selector=&scantron_uploads($file2grade);
 5903:     my $format_selector=&scantron_scantab();
 5904:     my $CODE_selector=&scantron_CODElist();
 5905:     my $CODE_unique=&scantron_CODEunique();
 5906:     my $result;
 5907: 
 5908:     $ssi_error = 0;
 5909: 
 5910:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5911:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5912: 
 5913: 	# Chunk of form to prompt for a scantron file upload.
 5914: 
 5915:         $r->print('
 5916:     <br />
 5917:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5918:        '.&Apache::loncommon::start_data_table_header_row().'
 5919:             <th>
 5920:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5921:             </th>
 5922:        '.&Apache::loncommon::end_data_table_header_row().'
 5923:        '.&Apache::loncommon::start_data_table_row().'
 5924:             <td>
 5925: ');
 5926:     my $default_form_data=&defaultFormData($symb);
 5927:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5928:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5929:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 5930:     &js_escape(\$alertmsg);
 5931:     $r->print(&Apache::lonhtmlcommon::scripttag('
 5932:     function checkUpload(formname) {
 5933: 	if (formname.upfile.value == "") {
 5934: 	    alert("'.$alertmsg.'");
 5935: 	    return false;
 5936: 	}
 5937: 	formname.submit();
 5938:     }'));
 5939:     $r->print('
 5940:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5941:                 '.$default_form_data.'
 5942:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5943:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5944:                 <input name="command" value="scantronupload_save" type="hidden" />
 5945:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5946:                 <br />
 5947:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5948:               </form>
 5949: ');
 5950: 
 5951:         $r->print('
 5952:             </td>
 5953:        '.&Apache::loncommon::end_data_table_row().'
 5954:        '.&Apache::loncommon::end_data_table().'
 5955: ');
 5956:     }
 5957: 
 5958:     # Chunk of form to prompt for a file to grade and how:
 5959: 
 5960:     $result.= '
 5961:     <br />
 5962:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5963:     <input type="hidden" name="command" value="scantron_warning" />
 5964:     '.$default_form_data.'
 5965:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5966:        '.&Apache::loncommon::start_data_table_header_row().'
 5967:             <th colspan="2">
 5968:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5969:             </th>
 5970:        '.&Apache::loncommon::end_data_table_header_row().'
 5971:        '.&Apache::loncommon::start_data_table_row().'
 5972:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5973:        '.&Apache::loncommon::end_data_table_row().'
 5974:        '.&Apache::loncommon::start_data_table_row().'
 5975:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5976:        '.&Apache::loncommon::end_data_table_row().'
 5977:        '.&Apache::loncommon::start_data_table_row().'
 5978:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5979:        '.&Apache::loncommon::end_data_table_row().'
 5980:        '.&Apache::loncommon::start_data_table_row().'
 5981:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5982:        '.&Apache::loncommon::end_data_table_row().'
 5983:        '.&Apache::loncommon::start_data_table_row().'
 5984:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5985:        '.&Apache::loncommon::end_data_table_row().'
 5986:        '.&Apache::loncommon::start_data_table_row().'
 5987: 	    <td> '.&mt('Options:').' </td>
 5988:             <td>
 5989: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5990:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5991:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5992: 	    </td>
 5993:        '.&Apache::loncommon::end_data_table_row().'
 5994:        '.&Apache::loncommon::start_data_table_row().'
 5995:             <td colspan="2">
 5996:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5997:             </td>
 5998:        '.&Apache::loncommon::end_data_table_row().'
 5999:     '.&Apache::loncommon::end_data_table().'
 6000:     </form>
 6001: ';
 6002:    
 6003:     $r->print($result);
 6004: 
 6005: 
 6006: 
 6007:     # Chunk of the form that prompts to view a scoring office file,
 6008:     # corrected file, skipped records in a file.
 6009: 
 6010:     $r->print('
 6011:    <br />
 6012:    <form action="/adm/grades" name="scantron_download">
 6013:      '.$default_form_data.'
 6014:      <input type="hidden" name="command" value="scantron_download" />
 6015:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 6016:        '.&Apache::loncommon::start_data_table_header_row().'
 6017:               <th>
 6018:                 &nbsp;'.&mt('Download a scoring office file').'
 6019:               </th>
 6020:        '.&Apache::loncommon::end_data_table_header_row().'
 6021:        '.&Apache::loncommon::start_data_table_row().'
 6022:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 6023:                 <br />
 6024:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 6025:        '.&Apache::loncommon::end_data_table_row().'
 6026:      '.&Apache::loncommon::end_data_table().'
 6027:    </form>
 6028:    <br />
 6029: ');
 6030: 
 6031:     &Apache::lonpickcode::code_list($r,2);
 6032: 
 6033:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
 6034:              $default_form_data."\n".
 6035:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 6036:              &Apache::loncommon::start_data_table_header_row()."\n".
 6037:              '<th colspan="2">
 6038:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 6039:              '</th>'."\n".
 6040:               &Apache::loncommon::end_data_table_header_row()."\n".
 6041:               &Apache::loncommon::start_data_table_row()."\n".
 6042:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 6043:               '<td> '.$sequence_selector.' </td>'.
 6044:               &Apache::loncommon::end_data_table_row()."\n".
 6045:               &Apache::loncommon::start_data_table_row()."\n".
 6046:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 6047:               '<td> '.$file_selector.' </td>'."\n".
 6048:               &Apache::loncommon::end_data_table_row()."\n".
 6049:               &Apache::loncommon::start_data_table_row()."\n".
 6050:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 6051:               '<td> '.$format_selector.' </td>'."\n".
 6052:               &Apache::loncommon::end_data_table_row()."\n".
 6053:               &Apache::loncommon::start_data_table_row()."\n".
 6054:               '<td> '.&mt('Options').' </td>'."\n".
 6055:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 6056:               &Apache::loncommon::end_data_table_row()."\n".
 6057:               &Apache::loncommon::start_data_table_row()."\n".
 6058:               '<td colspan="2">'."\n".
 6059:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 6060:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 6061:               '</td>'."\n".
 6062:               &Apache::loncommon::end_data_table_row()."\n".
 6063:               &Apache::loncommon::end_data_table()."\n".
 6064:               '</form><br />');
 6065:     return;
 6066: }
 6067: 
 6068: =pod
 6069: 
 6070: =item get_scantron_config
 6071: 
 6072:    Parse and return the bubblesheet configuration line selected as a
 6073:    hash of configuration file fields.
 6074: 
 6075:  Arguments:
 6076:     which - the name of the configuration to parse from the file.
 6077: 
 6078: 
 6079:  Returns:
 6080:             If the named configuration is not in the file, an empty
 6081:             hash is returned.
 6082:     a hash with the fields
 6083:       name         - internal name for the this configuration setup
 6084:       description  - text to display to operator that describes this config
 6085:       CODElocation - if 0 or the string 'none'
 6086:                           - no CODE exists for this config
 6087:                      if -1 || the string 'letter'
 6088:                           - a CODE exists for this config and is
 6089:                             a string of letters
 6090:                      Unsupported value (but planned for future support)
 6091:                           if a positive integer
 6092:                                - The CODE exists as the first n items from
 6093:                                  the question section of the form
 6094:                           if the string 'number'
 6095:                                - The CODE exists for this config and is
 6096:                                  a string of numbers
 6097:       CODEstart   - (only matter if a CODE exists) column in the line where
 6098:                      the CODE starts
 6099:       CODElength  - length of the CODE
 6100:       IDstart     - column where the student/employee ID starts
 6101:       IDlength    - length of the student/employee ID info
 6102:       Qstart      - column where the information from the bubbled
 6103:                     'questions' start
 6104:       Qlength     - number of columns comprising a single bubble line from
 6105:                     the sheet. (usually either 1 or 10)
 6106:       Qon         - either a single character representing the character used
 6107:                     to signal a bubble was chosen in the positional setup, or
 6108:                     the string 'letter' if the letter of the chosen bubble is
 6109:                     in the final, or 'number' if a number representing the
 6110:                     chosen bubble is in the file (1->A 0->J)
 6111:       Qoff        - the character used to represent that a bubble was
 6112:                     left blank
 6113:       PaperID     - if the scanning process generates a unique number for each
 6114:                     sheet scanned the column that this ID number starts in
 6115:       PaperIDlength - number of columns that comprise the unique ID number
 6116:                       for the sheet of paper
 6117:       FirstName   - column that the first name starts in
 6118:       FirstNameLength - number of columns that the first name spans
 6119:  
 6120:       LastName    - column that the last name starts in
 6121:       LastNameLength - number of columns that the last name spans
 6122:       BubblesPerRow - number of bubbles available in each row used to 
 6123:                       bubble an answer. (If not specified, 10 assumed).
 6124: 
 6125: =cut
 6126: 
 6127: sub get_scantron_config {
 6128:     my ($which) = @_;
 6129:     my @lines = &get_scantronformat_file();
 6130:     my %config;
 6131:     #FIXME probably should move to XML it has already gotten a bit much now
 6132:     foreach my $line (@lines) {
 6133: 	my ($name,$descrip)=split(/:/,$line);
 6134: 	if ($name ne $which ) { next; }
 6135: 	chomp($line);
 6136: 	my @config=split(/:/,$line);
 6137: 	$config{'name'}=$config[0];
 6138: 	$config{'description'}=$config[1];
 6139: 	$config{'CODElocation'}=$config[2];
 6140: 	$config{'CODEstart'}=$config[3];
 6141: 	$config{'CODElength'}=$config[4];
 6142: 	$config{'IDstart'}=$config[5];
 6143: 	$config{'IDlength'}=$config[6];
 6144: 	$config{'Qstart'}=$config[7];
 6145:  	$config{'Qlength'}=$config[8];
 6146: 	$config{'Qoff'}=$config[9];
 6147: 	$config{'Qon'}=$config[10];
 6148: 	$config{'PaperID'}=$config[11];
 6149: 	$config{'PaperIDlength'}=$config[12];
 6150: 	$config{'FirstName'}=$config[13];
 6151: 	$config{'FirstNamelength'}=$config[14];
 6152: 	$config{'LastName'}=$config[15];
 6153: 	$config{'LastNamelength'}=$config[16];
 6154:         $config{'BubblesPerRow'}=$config[17];
 6155: 	last;
 6156:     }
 6157:     return %config;
 6158: }
 6159: 
 6160: =pod 
 6161: 
 6162: =item username_to_idmap
 6163: 
 6164:     creates a hash keyed by student/employee ID with values of the corresponding
 6165:     student username:domain. If a single ID occurs for more than one student,
 6166:     the status of the student is checked, and if Active, the value in the hash
 6167:     will be set to the Active student.
 6168: 
 6169:   Arguments:
 6170: 
 6171:     $classlist - reference to the class list hash. This is a hash
 6172:                  keyed by student name:domain  whose elements are references
 6173:                  to arrays containing various chunks of information
 6174:                  about the student. (See loncoursedata for more info).
 6175: 
 6176:   Returns
 6177:     %idmap - the constructed hash
 6178: 
 6179: =cut
 6180: 
 6181: sub username_to_idmap {
 6182:     my ($classlist)= @_;
 6183:     my %idmap;
 6184:     foreach my $student (keys(%$classlist)) {
 6185:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
 6186:         unless ($id eq '') {
 6187:             if (!exists($idmap{$id})) {
 6188:                 $idmap{$id} = $student;
 6189:             } else {
 6190:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
 6191:                 if ($status eq 'Active') {
 6192:                     $idmap{$id} = $student;
 6193:                 }
 6194:             }
 6195:         }
 6196:     }
 6197:     return %idmap;
 6198: }
 6199: 
 6200: =pod
 6201: 
 6202: =item scantron_fixup_scanline
 6203: 
 6204:    Process a requested correction to a scanline.
 6205: 
 6206:   Arguments:
 6207:     $scantron_config   - hash from &get_scantron_config()
 6208:     $scan_data         - hash of correction information 
 6209:                           (see &scantron_getfile())
 6210:     $line              - existing scanline
 6211:     $whichline         - line number of the passed in scanline
 6212:     $field             - type of change to process 
 6213:                          (either 
 6214:                           'ID'     -> correct the student/employee ID
 6215:                           'CODE'   -> correct the CODE
 6216:                           'answer' -> fixup the submitted answers)
 6217:     
 6218:    $args               - hash of additional info,
 6219:                           - 'ID' 
 6220:                                'newid' -> studentID to use in replacement
 6221:                                           of existing one
 6222:                           - 'CODE' 
 6223:                                'CODE_ignore_dup' - set to true if duplicates
 6224:                                                    should be ignored.
 6225: 	                       'CODE' - is new code or 'use_unfound'
 6226:                                         if the existing unfound code should
 6227:                                         be used as is
 6228:                           - 'answer'
 6229:                                'response' - new answer or 'none' if blank
 6230:                                'question' - the bubble line to change
 6231:                                'questionnum' - the question identifier,
 6232:                                                may include subquestion. 
 6233: 
 6234:   Returns:
 6235:     $line - the modified scanline
 6236: 
 6237:   Side effects: 
 6238:     $scan_data - may be updated
 6239: 
 6240: =cut
 6241: 
 6242: 
 6243: sub scantron_fixup_scanline {
 6244:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 6245:     if ($field eq 'ID') {
 6246: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 6247: 	    return ($line,1,'New value too large');
 6248: 	}
 6249: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 6250: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 6251: 				     $args->{'newid'});
 6252: 	}
 6253: 	substr($line,$$scantron_config{'IDstart'}-1,
 6254: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 6255: 	if ($args->{'newid'}=~/^\s*$/) {
 6256: 	    &scan_data($scan_data,"$whichline.user",
 6257: 		       $args->{'username'}.':'.$args->{'domain'});
 6258: 	}
 6259:     } elsif ($field eq 'CODE') {
 6260: 	if ($args->{'CODE_ignore_dup'}) {
 6261: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 6262: 	}
 6263: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 6264: 	if ($args->{'CODE'} ne 'use_unfound') {
 6265: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 6266: 		return ($line,1,'New CODE value too large');
 6267: 	    }
 6268: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 6269: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 6270: 	    }
 6271: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 6272: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 6273: 	}
 6274:     } elsif ($field eq 'answer') {
 6275: 	my $length=$scantron_config->{'Qlength'};
 6276: 	my $off=$scantron_config->{'Qoff'};
 6277: 	my $on=$scantron_config->{'Qon'};
 6278: 	my $answer=${off}x$length;
 6279: 	if ($args->{'response'} eq 'none') {
 6280: 	    &scan_data($scan_data,
 6281: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 6282: 	} else {
 6283: 	    if ($on eq 'letter') {
 6284: 		my @alphabet=('A'..'Z');
 6285: 		$answer=$alphabet[$args->{'response'}];
 6286: 	    } elsif ($on eq 'number') {
 6287: 		$answer=$args->{'response'}+1;
 6288: 		if ($answer == 10) { $answer = '0'; }
 6289: 	    } else {
 6290: 		substr($answer,$args->{'response'},1)=$on;
 6291: 	    }
 6292: 	    &scan_data($scan_data,
 6293: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 6294: 	}
 6295: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 6296: 	substr($line,$where-1,$length)=$answer;
 6297:     }
 6298:     return $line;
 6299: }
 6300: 
 6301: =pod
 6302: 
 6303: =item scan_data
 6304: 
 6305:     Edit or look up  an item in the scan_data hash.
 6306: 
 6307:   Arguments:
 6308:     $scan_data  - The hash (see scantron_getfile)
 6309:     $key        - shorthand of the key to edit (actual key is
 6310:                   scantronfilename_key).
 6311:     $data        - New value of the hash entry.
 6312:     $delete      - If true, the entry is removed from the hash.
 6313: 
 6314:   Returns:
 6315:     The new value of the hash table field (undefined if deleted).
 6316: 
 6317: =cut
 6318: 
 6319: 
 6320: sub scan_data {
 6321:     my ($scan_data,$key,$value,$delete)=@_;
 6322:     my $filename=$env{'form.scantron_selectfile'};
 6323:     if (defined($value)) {
 6324: 	$scan_data->{$filename.'_'.$key} = $value;
 6325:     }
 6326:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 6327:     return $scan_data->{$filename.'_'.$key};
 6328: }
 6329: 
 6330: # ----- These first few routines are general use routines.----
 6331: 
 6332: # Return the number of occurences of a pattern in a string.
 6333: 
 6334: sub occurence_count {
 6335:     my ($string, $pattern) = @_;
 6336: 
 6337:     my @matches = ($string =~ /$pattern/g);
 6338: 
 6339:     return scalar(@matches);
 6340: }
 6341: 
 6342: 
 6343: # Take a string known to have digits and convert all the
 6344: # digits into letters in the range J,A..I.
 6345: 
 6346: sub digits_to_letters {
 6347:     my ($input) = @_;
 6348: 
 6349:     my @alphabet = ('J', 'A'..'I');
 6350: 
 6351:     my @input    = split(//, $input);
 6352:     my $output ='';
 6353:     for (my $i = 0; $i < scalar(@input); $i++) {
 6354: 	if ($input[$i] =~ /\d/) {
 6355: 	    $output .= $alphabet[$input[$i]];
 6356: 	} else {
 6357: 	    $output .= $input[$i];
 6358: 	}
 6359:     }
 6360:     return $output;
 6361: }
 6362: 
 6363: =pod 
 6364: 
 6365: =item scantron_parse_scanline
 6366: 
 6367:   Decodes a scanline from the selected bubblesheet file
 6368: 
 6369:  Arguments:
 6370:     line             - The text of the bubblesheet file line to process
 6371:     whichline        - Line number
 6372:     scantron_config  - Hash describing the format of the bubblesheet lines.
 6373:     scan_data        - Hash of extra information about the scanline
 6374:                        (see scantron_getfile for more information)
 6375:     just_header      - True if should not process question answers but only
 6376:                        the stuff to the left of the answers.
 6377:     randomorder      - True if randomorder in use
 6378:     randompick       - True if randompick in use
 6379:     sequence         - Exam folder URL
 6380:     master_seq       - Ref to array containing symbs in exam folder
 6381:     symb_to_resource - Ref to hash of symbs for resources in exam folder
 6382:                        (corresponding values are resource objects)
 6383:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
 6384:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
 6385:                        are refs to an array of resource objects, ordered
 6386:                        according to order used for CODE, when randomorder
 6387:                        and or randompick are in use.
 6388:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
 6389:                        for current line to question number used for same question
 6390:                         in "Master Sequence" (as seen by Course Coordinator).
 6391:     startline        - Ref to hash where key is question number (0 is first)
 6392:                        and value is number of first bubble line for current 
 6393:                        student or code-based randompick and/or randomorder.
 6394:     totalref         - Ref of scalar used to score total number of bubble
 6395:                        lines needed for responses in a scan line (used when
 6396:                        randompick in use. 
 6397:     
 6398:  Returns:
 6399:    Hash containing the result of parsing the scanline
 6400: 
 6401:    Keys are all proceeded by the string 'scantron.'
 6402: 
 6403:        CODE    - the CODE in use for this scanline
 6404:        useCODE - 1 if the CODE is invalid but it usage has been forced
 6405:                  by the operator
 6406:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 6407:                             CODEs were selected, but the usage has been
 6408:                             forced by the operator
 6409:        ID  - student/employee ID
 6410:        PaperID - if used, the ID number printed on the sheet when the 
 6411:                  paper was scanned
 6412:        FirstName - first name from the sheet
 6413:        LastName  - last name from the sheet
 6414: 
 6415:      if just_header was not true these key may also exist
 6416: 
 6417:        missingerror - a list of bubble ranges that are considered to be answers
 6418:                       to a single question that don't have any bubbles filled in.
 6419:                       Of the form questionnumber:firstbubblenumber:count.
 6420:        doubleerror  - a list of bubble ranges that are considered to be answers
 6421:                       to a single question that have more than one bubble filled in.
 6422:                       Of the form questionnumber::firstbubblenumber:count
 6423:    
 6424:                 In the above, count is the number of bubble responses in the
 6425:                 input line needed to represent the possible answers to the question.
 6426:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 6427:                 per line would have count = 2.
 6428: 
 6429:        maxquest     - the number of the last bubble line that was parsed
 6430: 
 6431:        (<number> starts at 1)
 6432:        <number>.answer - zero or more letters representing the selected
 6433:                          letters from the scanline for the bubble line 
 6434:                          <number>.
 6435:                          if blank there was either no bubble or there where
 6436:                          multiple bubbles, (consult the keys missingerror and
 6437:                          doubleerror if this is an error condition)
 6438: 
 6439: =cut
 6440: 
 6441: sub scantron_parse_scanline {
 6442:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
 6443:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
 6444:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
 6445: 
 6446:     my %record;
 6447:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
 6448:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 6449: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 6450: 	if ($$scantron_config{'CODElocation'} < 0 ||
 6451: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 6452: 	    $$scantron_config{'CODElocation'} eq 'number') {
 6453: 	    $record{'scantron.CODE'}=substr($data,
 6454: 					    $$scantron_config{'CODEstart'}-1,
 6455: 					    $$scantron_config{'CODElength'});
 6456: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 6457: 		$record{'scantron.useCODE'}=1;
 6458: 	    }
 6459: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 6460: 		$record{'scantron.CODE_ignore_dup'}=1;
 6461: 	    }
 6462: 	} else {
 6463: 	    #FIXME interpret first N questions
 6464: 	}
 6465:     }
 6466:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 6467: 				  $$scantron_config{'IDlength'});
 6468:     $record{'scantron.PaperID'}=
 6469: 	substr($data,$$scantron_config{'PaperID'}-1,
 6470: 	       $$scantron_config{'PaperIDlength'});
 6471:     $record{'scantron.FirstName'}=
 6472: 	substr($data,$$scantron_config{'FirstName'}-1,
 6473: 	       $$scantron_config{'FirstNamelength'});
 6474:     $record{'scantron.LastName'}=
 6475: 	substr($data,$$scantron_config{'LastName'}-1,
 6476: 	       $$scantron_config{'LastNamelength'});
 6477:     if ($just_header) { return \%record; }
 6478: 
 6479:     my @alphabet=('A'..'Z');
 6480:     my $questnum=0;
 6481:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 6482: 
 6483:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 6484:     if ($randompick || $randomorder) {
 6485:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
 6486:                                          $master_seq,$symb_to_resource,
 6487:                                          $partids_by_symb,$orderedforcode,
 6488:                                          $respnumlookup,$startline);
 6489:         if ($total) {
 6490:             $lastpos = $total*$$scantron_config{'Qlength'}; 
 6491:         }
 6492:         if (ref($totalref)) {
 6493:             $$totalref = $total;
 6494:         }
 6495:     }
 6496:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 6497:     chomp($questions);		# Get rid of any trailing \n.
 6498:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 6499:     while (length($questions)) {
 6500:         my $answers_needed;
 6501:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6502:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
 6503:         } else {
 6504: 	    $answers_needed = $bubble_lines_per_response{$questnum};
 6505:         }
 6506:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 6507:                              || 1;
 6508:         $questnum++;
 6509:         my $quest_id = $questnum;
 6510:         my $currentquest = substr($questions,0,$answer_length);
 6511:         $questions       = substr($questions,$answer_length);
 6512:         if (length($currentquest) < $answer_length) { next; }
 6513: 
 6514:         my $subdivided;
 6515:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6516:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
 6517:         } else {
 6518:             $subdivided = $subdivided_bubble_lines{$questnum-1};
 6519:         }
 6520:         if ($subdivided =~ /,/) {
 6521:             my $subquestnum = 1;
 6522:             my $subquestions = $currentquest;
 6523:             my @subanswers_needed = split(/,/,$subdivided);
 6524:             foreach my $subans (@subanswers_needed) {
 6525:                 my $subans_length =
 6526:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 6527:                 my $currsubquest = substr($subquestions,0,$subans_length);
 6528:                 $subquestions   = substr($subquestions,$subans_length);
 6529:                 $quest_id = "$questnum.$subquestnum";
 6530:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 6531:                     ($$scantron_config{'Qon'} eq 'number')) {
 6532:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 6533:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6534:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6535:                         $randomorder,$randompick,$respnumlookup);
 6536:                 } else {
 6537:                     $ansnum = &scantron_validator_positional($ansnum,
 6538:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 6539:                         \@alphabet,\%record,$scantron_config,$scan_data,
 6540:                         $randomorder,$randompick,$respnumlookup);
 6541:                 }
 6542:                 $subquestnum ++;
 6543:             }
 6544:         } else {
 6545:             if (($$scantron_config{'Qon'} eq 'letter') ||
 6546:                 ($$scantron_config{'Qon'} eq 'number')) {
 6547:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 6548:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6549:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6550:                     $randomorder,$randompick,$respnumlookup);
 6551:             } else {
 6552:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 6553:                     $quest_id,$answers_needed,$currentquest,$whichline,
 6554:                     \@alphabet,\%record,$scantron_config,$scan_data,
 6555:                     $randomorder,$randompick,$respnumlookup);
 6556:             }
 6557:         }
 6558:     }
 6559:     $record{'scantron.maxquest'}=$questnum;
 6560:     return \%record;
 6561: }
 6562: 
 6563: sub get_master_seq {
 6564:     my ($resources,$master_seq,$symb_to_resource) = @_;
 6565:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
 6566:                    (ref($symb_to_resource) eq 'HASH'));
 6567:     my $resource_error;
 6568:     foreach my $resource (@{$resources}) {
 6569:         my $ressymb;
 6570:         if (ref($resource)) {
 6571:             $ressymb = $resource->symb();
 6572:             push(@{$master_seq},$ressymb);
 6573:             $symb_to_resource->{$ressymb} = $resource;
 6574:         } else {
 6575:             $resource_error = 1;
 6576:             last;
 6577:         }
 6578:     }
 6579:     return $resource_error;
 6580: }
 6581: 
 6582: sub get_respnum_lookups {
 6583:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
 6584:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
 6585:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
 6586:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
 6587:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
 6588:                    (ref($startline) eq 'HASH'));
 6589:     my ($user,$scancode);
 6590:     if ((exists($record->{'scantron.CODE'})) &&
 6591:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
 6592:         $scancode = $record->{'scantron.CODE'};
 6593:     } else {
 6594:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
 6595:     }
 6596:     my @mapresources =
 6597:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
 6598:                      $orderedforcode);
 6599:     my $total = 0;
 6600:     my $count = 0;
 6601:     foreach my $resource (@mapresources) {
 6602:         my $id = $resource->id();
 6603:         my $symb = $resource->symb();
 6604:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
 6605:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
 6606:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
 6607:                 if ($respnum ne '') {
 6608:                     $respnumlookup->{$count} = $respnum;
 6609:                     $startline->{$count} = $total;
 6610:                     $total += $bubble_lines_per_response{$respnum};
 6611:                     $count ++;
 6612:                 }
 6613:             }
 6614:         }
 6615:     }
 6616:     return $total;
 6617: }
 6618: 
 6619: sub scantron_validator_lettnum {
 6620:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 6621:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
 6622:         $randompick,$respnumlookup) = @_;
 6623: 
 6624:     # Qon 'letter' implies for each slot in currquest we have:
 6625:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 6626:     #    about anything else (esp. a value of Qoff) for missing
 6627:     #    bubbles.
 6628:     #
 6629:     # Qon 'number' implies each slot gives a digit that indexes the
 6630:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 6631:     #    and * or ? for double bubbles on a single line.
 6632:     #
 6633: 
 6634:     my $matchon;
 6635:     if ($$scantron_config{'Qon'} eq 'letter') {
 6636:         $matchon = '[A-Z]';
 6637:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 6638:         $matchon = '\d';
 6639:     }
 6640:     my $occurrences = 0;
 6641:     my $responsenum = $questnum-1;
 6642:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6643:        $responsenum = $respnumlookup->{$questnum-1} 
 6644:     }
 6645:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6646:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6647:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6648:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6649:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6650:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6651:         my @singlelines = split('',$currquest);
 6652:         foreach my $entry (@singlelines) {
 6653:             $occurrences = &occurence_count($entry,$matchon);
 6654:             if ($occurrences > 1) {
 6655:                 last;
 6656:             }
 6657:         }
 6658:     } else {
 6659:         $occurrences = &occurence_count($currquest,$matchon); 
 6660:     }
 6661:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 6662:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6663:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6664:             my $bubble = substr($currquest,$ans,1);
 6665:             if ($bubble =~ /$matchon/ ) {
 6666:                 if ($$scantron_config{'Qon'} eq 'number') {
 6667:                     if ($bubble == 0) {
 6668:                         $bubble = 10; 
 6669:                     }
 6670:                     $record->{"scantron.$ansnum.answer"} = 
 6671:                         $alphabet->[$bubble-1];
 6672:                 } else {
 6673:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 6674:                 }
 6675:             } else {
 6676:                 $record->{"scantron.$ansnum.answer"}='';
 6677:             }
 6678:             $ansnum++;
 6679:         }
 6680:     } elsif (!defined($currquest)
 6681:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 6682:             || (&occurence_count($currquest,$matchon) == 0)) {
 6683:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6684:             $record->{"scantron.$ansnum.answer"}='';
 6685:             $ansnum++;
 6686:         }
 6687:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6688:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 6689:         }
 6690:     } else {
 6691:         if ($$scantron_config{'Qon'} eq 'number') {
 6692:             $currquest = &digits_to_letters($currquest);            
 6693:         }
 6694:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6695:             my $bubble = substr($currquest,$ans,1);
 6696:             $record->{"scantron.$ansnum.answer"} = $bubble;
 6697:             $ansnum++;
 6698:         }
 6699:     }
 6700:     return $ansnum;
 6701: }
 6702: 
 6703: sub scantron_validator_positional {
 6704:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 6705:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
 6706:         $randomorder,$randompick,$respnumlookup) = @_;
 6707: 
 6708:     # Otherwise there's a positional notation;
 6709:     # each bubble line requires Qlength items, and there are filled in
 6710:     # bubbles for each case where there 'Qon' characters.
 6711:     #
 6712: 
 6713:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 6714: 
 6715:     # If the split only gives us one element.. the full length of the
 6716:     # answer string, no bubbles are filled in:
 6717: 
 6718:     if ($answers_needed eq '') {
 6719:         return;
 6720:     }
 6721: 
 6722:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 6723:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 6724:             $record->{"scantron.$ansnum.answer"}='';
 6725:             $ansnum++;
 6726:         }
 6727:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 6728:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 6729:         }
 6730:     } elsif (scalar(@array) == 2) {
 6731:         my $location = length($array[0]);
 6732:         my $line_num = int($location / $$scantron_config{'Qlength'});
 6733:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 6734:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6735:             if ($ans eq $line_num) {
 6736:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6737:             } else {
 6738:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6739:             }
 6740:             $ansnum++;
 6741:          }
 6742:     } else {
 6743:         #  If there's more than one instance of a bubble character
 6744:         #  That's a double bubble; with positional notation we can
 6745:         #  record all the bubbles filled in as well as the
 6746:         #  fact this response consists of multiple bubbles.
 6747:         #
 6748:         my $responsenum = $questnum-1;
 6749:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
 6750:             $responsenum = $respnumlookup->{$questnum-1}
 6751:         }
 6752:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 6753:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 6754:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 6755:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 6756:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 6757:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 6758:             my $doubleerror = 0;
 6759:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6760:                    (!$doubleerror)) {
 6761:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6762:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6763:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6764:                if (length(@currarray) > 2) {
 6765:                    $doubleerror = 1;
 6766:                } 
 6767:             }
 6768:             if ($doubleerror) {
 6769:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6770:             }
 6771:         } else {
 6772:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6773:         }
 6774:         my $item = $ansnum;
 6775:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6776:             $record->{"scantron.$item.answer"} = '';
 6777:             $item ++;
 6778:         }
 6779: 
 6780:         my @ans=@array;
 6781:         my $i=0;
 6782:         my $increment = 0;
 6783:         while ($#ans) {
 6784:             $i+=length($ans[0]) + $increment;
 6785:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6786:             my $bubble = $i%$$scantron_config{'Qlength'};
 6787:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6788:             shift(@ans);
 6789:             $increment = 1;
 6790:         }
 6791:         $ansnum += $answers_needed;
 6792:     }
 6793:     return $ansnum;
 6794: }
 6795: 
 6796: =pod
 6797: 
 6798: =item scantron_add_delay
 6799: 
 6800:    Adds an error message that occurred during the grading phase to a
 6801:    queue of messages to be shown after grading pass is complete
 6802: 
 6803:  Arguments:
 6804:    $delayqueue  - arrary ref of hash ref of error messages
 6805:    $scanline    - the scanline that caused the error
 6806:    $errormesage - the error message
 6807:    $errorcode   - a numeric code for the error
 6808: 
 6809:  Side Effects:
 6810:    updates the $delayqueue to have a new hash ref of the error
 6811: 
 6812: =cut
 6813: 
 6814: sub scantron_add_delay {
 6815:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6816:     push(@$delayqueue,
 6817: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6818: 	  'ecode' => $errorcode }
 6819: 	 );
 6820: }
 6821: 
 6822: =pod
 6823: 
 6824: =item scantron_find_student
 6825: 
 6826:    Finds the username for the current scanline
 6827: 
 6828:   Arguments:
 6829:    $scantron_record - hash result from scantron_parse_scanline
 6830:    $scan_data       - hash of correction information 
 6831:                       (see &scantron_getfile() form more information)
 6832:    $idmap           - hash from &username_to_idmap()
 6833:    $line            - number of current scanline
 6834:  
 6835:   Returns:
 6836:    Either 'username:domain' or undef if unknown
 6837: 
 6838: =cut
 6839: 
 6840: sub scantron_find_student {
 6841:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6842:     my $scanID=$$scantron_record{'scantron.ID'};
 6843:     if ($scanID =~ /^\s*$/) {
 6844:  	return &scan_data($scan_data,"$line.user");
 6845:     }
 6846:     foreach my $id (keys(%$idmap)) {
 6847:  	if (lc($id) eq lc($scanID)) {
 6848:  	    return $$idmap{$id};
 6849:  	}
 6850:     }
 6851:     return undef;
 6852: }
 6853: 
 6854: =pod
 6855: 
 6856: =item scantron_filter
 6857: 
 6858:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6859:    hidden resources was selected
 6860: 
 6861: =cut
 6862: 
 6863: sub scantron_filter {
 6864:     my ($curres)=@_;
 6865: 
 6866:     if (ref($curres) && $curres->is_problem()) {
 6867: 	# if the user has asked to not have either hidden
 6868: 	# or 'randomout' controlled resources to be graded
 6869: 	# don't include them
 6870: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6871: 	    && $curres->randomout) {
 6872: 	    return 0;
 6873: 	}
 6874: 	return 1;
 6875:     }
 6876:     return 0;
 6877: }
 6878: 
 6879: =pod
 6880: 
 6881: =item scantron_process_corrections
 6882: 
 6883:    Gets correction information out of submitted form data and corrects
 6884:    the scanline
 6885: 
 6886: =cut
 6887: 
 6888: sub scantron_process_corrections {
 6889:     my ($r) = @_;
 6890:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6891:     my ($scanlines,$scan_data)=&scantron_getfile();
 6892:     my $classlist=&Apache::loncoursedata::get_classlist();
 6893:     my $which=$env{'form.scantron_line'};
 6894:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6895:     my ($skip,$err,$errmsg);
 6896:     if ($env{'form.scantron_skip_record'}) {
 6897: 	$skip=1;
 6898:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6899: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6900: 	    $env{'form.scantron_domain'};
 6901: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6902: 	($line,$err,$errmsg)=
 6903: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6904: 				     'ID',{'newid'=>$newid,
 6905: 				    'username'=>$env{'form.scantron_username'},
 6906: 				    'domain'=>$env{'form.scantron_domain'}});
 6907:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6908: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6909: 	my $newCODE;
 6910: 	my %args;
 6911: 	if      ($resolution eq 'use_unfound') {
 6912: 	    $newCODE='use_unfound';
 6913: 	} elsif ($resolution eq 'use_found') {
 6914: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6915: 	} elsif ($resolution eq 'use_typed') {
 6916: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6917: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6918: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6919: 	}
 6920: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6921: 	    $args{'CODE_ignore_dup'}=1;
 6922: 	}
 6923: 	$args{'CODE'}=$newCODE;
 6924: 	($line,$err,$errmsg)=
 6925: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6926: 				     'CODE',\%args);
 6927:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6928: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6929: 	    ($line,$err,$errmsg)=
 6930: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6931: 					 $which,'answer',
 6932: 					 { 'question'=>$question,
 6933: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6934:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6935: 	    if ($err) { last; }
 6936: 	}
 6937:     }
 6938:     if ($err) {
 6939:         $r->print(
 6940:             '<p class="LC_error">'
 6941:            .&mt('Unable to accept last correction, an error occurred: [_1]',
 6942:                 $errmsg)
 6943:            .'</p>');
 6944:     } else {
 6945: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6946: 	&scantron_putfile($scanlines,$scan_data);
 6947:     }
 6948: }
 6949: 
 6950: =pod
 6951: 
 6952: =item reset_skipping_status
 6953: 
 6954:    Forgets the current set of remember skipped scanlines (and thus
 6955:    reverts back to considering all lines in the
 6956:    scantron_skipped_<filename> file)
 6957: 
 6958: =cut
 6959: 
 6960: sub reset_skipping_status {
 6961:     my ($scanlines,$scan_data)=&scantron_getfile();
 6962:     &scan_data($scan_data,'remember_skipping',undef,1);
 6963:     &scantron_putfile(undef,$scan_data);
 6964: }
 6965: 
 6966: =pod
 6967: 
 6968: =item start_skipping
 6969: 
 6970:    Marks a scanline to be skipped. 
 6971: 
 6972: =cut
 6973: 
 6974: sub start_skipping {
 6975:     my ($scan_data,$i)=@_;
 6976:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6977:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6978: 	$remembered{$i}=2;
 6979:     } else {
 6980: 	$remembered{$i}=1;
 6981:     }
 6982:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item should_be_skipped
 6988: 
 6989:    Checks whether a scanline should be skipped.
 6990: 
 6991: =cut
 6992: 
 6993: sub should_be_skipped {
 6994:     my ($scanlines,$scan_data,$i)=@_;
 6995:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6996: 	# not redoing old skips
 6997: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6998: 	return 0;
 6999:     }
 7000:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 7001: 
 7002:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 7003: 	return 0;
 7004:     }
 7005:     return 1;
 7006: }
 7007: 
 7008: =pod
 7009: 
 7010: =item remember_current_skipped
 7011: 
 7012:    Discovers what scanlines are in the scantron_skipped_<filename>
 7013:    file and remembers them into scan_data for later use.
 7014: 
 7015: =cut
 7016: 
 7017: sub remember_current_skipped {
 7018:     my ($scanlines,$scan_data)=&scantron_getfile();
 7019:     my %to_remember;
 7020:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7021: 	if ($scanlines->{'skipped'}[$i]) {
 7022: 	    $to_remember{$i}=1;
 7023: 	}
 7024:     }
 7025: 
 7026:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 7027:     &scantron_putfile(undef,$scan_data);
 7028: }
 7029: 
 7030: =pod
 7031: 
 7032: =item check_for_error
 7033: 
 7034:     Checks if there was an error when attempting to remove a specific
 7035:     scantron_.. bubblesheet data file. Prints out an error if
 7036:     something went wrong.
 7037: 
 7038: =cut
 7039: 
 7040: sub check_for_error {
 7041:     my ($r,$result)=@_;
 7042:     if ($result ne 'ok' && $result ne 'not_found' ) {
 7043: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 7044:     }
 7045: }
 7046: 
 7047: =pod
 7048: 
 7049: =item scantron_warning_screen
 7050: 
 7051:    Interstitial screen to make sure the operator has selected the
 7052:    correct options before we start the validation phase.
 7053: 
 7054: =cut
 7055: 
 7056: sub scantron_warning_screen {
 7057:     my ($button_text,$symb)=@_;
 7058:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 7059:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7060:     my $CODElist;
 7061:     if ($scantron_config{'CODElocation'} &&
 7062: 	$scantron_config{'CODEstart'} &&
 7063: 	$scantron_config{'CODElength'}) {
 7064: 	$CODElist=$env{'form.scantron_CODElist'};
 7065: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
 7066: 	$CODElist=
 7067: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 7068: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 7069:     }
 7070:     my $lastbubblepoints;
 7071:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7072:         $lastbubblepoints =
 7073:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
 7074:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
 7075:     }
 7076:     return ('
 7077: <p>
 7078: <span class="LC_warning">
 7079: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
 7080: </p>
 7081: <table>
 7082: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 7083: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 7084: '.$CODElist.$lastbubblepoints.'
 7085: </table>
 7086: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
 7087: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
 7088: 
 7089: <br />
 7090: ');
 7091: }
 7092: 
 7093: =pod
 7094: 
 7095: =item scantron_do_warning
 7096: 
 7097:    Check if the operator has picked something for all required
 7098:    fields. Error out if something is missing.
 7099: 
 7100: =cut
 7101: 
 7102: sub scantron_do_warning {
 7103:     my ($r,$symb)=@_;
 7104:     if (!$symb) {return '';}
 7105:     my $default_form_data=&defaultFormData($symb);
 7106:     $r->print(&scantron_form_start().$default_form_data);
 7107:     if ( $env{'form.selectpage'} eq '' ||
 7108: 	 $env{'form.scantron_selectfile'} eq '' ||
 7109: 	 $env{'form.scantron_format'} eq '' ) {
 7110: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
 7111: 	if ( $env{'form.selectpage'} eq '') {
 7112: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 7113: 	} 
 7114: 	if ( $env{'form.scantron_selectfile'} eq '') {
 7115: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
 7116: 	} 
 7117: 	if ( $env{'form.scantron_format'} eq '') {
 7118: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
 7119: 	} 
 7120:     } else {
 7121: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
 7122:         my $bubbledbyhand=&hand_bubble_option();
 7123: 	$r->print('
 7124: '.$warning.$bubbledbyhand.'
 7125: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 7126: <input type="hidden" name="command" value="scantron_validate" />
 7127: ');
 7128:     }
 7129:     $r->print("</form><br />");
 7130:     return '';
 7131: }
 7132: 
 7133: =pod
 7134: 
 7135: =item scantron_form_start
 7136: 
 7137:     html hidden input for remembering all selected grading options
 7138: 
 7139: =cut
 7140: 
 7141: sub scantron_form_start {
 7142:     my ($max_bubble)=@_;
 7143:     my $result= <<SCANTRONFORM;
 7144: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7145:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 7146:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 7147:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 7148:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 7149:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 7150:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 7151:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 7152:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 7153:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 7154: SCANTRONFORM
 7155: 
 7156:   my $line = 0;
 7157:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 7158:        my $chunk =
 7159: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 7160:        $chunk .=
 7161: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 7162:        $chunk .= 
 7163:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 7164:        $chunk .=
 7165:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 7166:        $chunk .=
 7167:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
 7168:        $result .= $chunk;
 7169:        $line++;
 7170:     }
 7171:     return $result;
 7172: }
 7173: 
 7174: =pod
 7175: 
 7176: =item scantron_validate_file
 7177: 
 7178:     Dispatch routine for doing validation of a bubblesheet data file.
 7179: 
 7180:     Also processes any necessary information resets that need to
 7181:     occur before validation begins (ignore previous corrections,
 7182:     restarting the skipped records processing)
 7183: 
 7184: =cut
 7185: 
 7186: sub scantron_validate_file {
 7187:     my ($r,$symb) = @_;
 7188:     if (!$symb) {return '';}
 7189:     my $default_form_data=&defaultFormData($symb);
 7190:     
 7191:     # do the detection of only doing skipped records first before we delete
 7192:     # them when doing the corrections reset
 7193:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 7194: 	&reset_skipping_status();
 7195:     }
 7196:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 7197: 	&remember_current_skipped();
 7198: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 7199:     }
 7200: 
 7201:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 7202: 	&check_for_error($r,&scantron_remove_file('corrected'));
 7203: 	&check_for_error($r,&scantron_remove_file('skipped'));
 7204: 	&check_for_error($r,&scantron_remove_scan_data());
 7205: 	$env{'form.scantron_options_ignore'}='done';
 7206:     }
 7207: 
 7208:     if ($env{'form.scantron_corrections'}) {
 7209: 	&scantron_process_corrections($r);
 7210:     }
 7211:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 7212:     #get the student pick code ready
 7213:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 7214:     my $nav_error;
 7215:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7216:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 7217:     if ($nav_error) {
 7218:         $r->print(&navmap_errormsg());
 7219:         return '';
 7220:     }
 7221:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 7222:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
 7223:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
 7224:     }
 7225:     $r->print($result);
 7226:     
 7227:     my @validate_phases=( 'sequence',
 7228: 			  'ID',
 7229: 			  'CODE',
 7230: 			  'doublebubble',
 7231: 			  'missingbubbles');
 7232:     if (!$env{'form.validatepass'}) {
 7233: 	$env{'form.validatepass'} = 0;
 7234:     }
 7235:     my $currentphase=$env{'form.validatepass'};
 7236: 
 7237: 
 7238:     my $stop=0;
 7239:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 7240: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 7241: 	$r->rflush();
 7242:      
 7243: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 7244: 	{
 7245: 	    no strict 'refs';
 7246: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 7247: 	}
 7248:     }
 7249:     if (!$stop) {
 7250: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
 7251: 	$r->print(&mt('Validation process complete.').'<br />'.
 7252:                   $warning.
 7253:                   &mt('Perform verification for each student after storage of submissions?').
 7254:                   '&nbsp;<span class="LC_nobreak"><label>'.
 7255:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 7256:                   ('&nbsp;'x3).'<label>'.
 7257:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 7258:                   '</label></span><br />'.
 7259:                   &mt('Grading will take longer if you use verification.').'<br />'.
 7260:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
 7261:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 7262:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 7263:     } else {
 7264: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 7265: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 7266:     }
 7267:     if ($stop) {
 7268: 	if ($validate_phases[$currentphase] eq 'sequence') {
 7269: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 7270: 	    $r->print(' '.&mt('this error').' <br />');
 7271: 
 7272: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
 7273: 	} else {
 7274:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 7275: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 7276:             } else {
 7277:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 7278:             }
 7279: 	    $r->print(' '.&mt('using corrected info').' <br />');
 7280: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 7281: 	    $r->print(" ".&mt("this scanline saving it for later."));
 7282: 	}
 7283:     }
 7284:     $r->print(" </form><br />");
 7285:     return '';
 7286: }
 7287: 
 7288: 
 7289: =pod
 7290: 
 7291: =item scantron_remove_file
 7292: 
 7293:    Removes the requested bubblesheet data file, makes sure that
 7294:    scantron_original_<filename> is never removed
 7295: 
 7296: 
 7297: =cut
 7298: 
 7299: sub scantron_remove_file {
 7300:     my ($which)=@_;
 7301:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7302:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7303:     my $file='scantron_';
 7304:     if ($which eq 'corrected' || $which eq 'skipped') {
 7305: 	$file.=$which.'_';
 7306:     } else {
 7307: 	return 'refused';
 7308:     }
 7309:     $file.=$env{'form.scantron_selectfile'};
 7310:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 7311: }
 7312: 
 7313: 
 7314: =pod
 7315: 
 7316: =item scantron_remove_scan_data
 7317: 
 7318:    Removes all scan_data correction for the requested bubblesheet
 7319:    data file.  (In the case that both the are doing skipped records we need
 7320:    to remember the old skipped lines for the time being so that element
 7321:    persists for a while.)
 7322: 
 7323: =cut
 7324: 
 7325: sub scantron_remove_scan_data {
 7326:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7327:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7328:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 7329:     my @todelete;
 7330:     my $filename=$env{'form.scantron_selectfile'};
 7331:     foreach my $key (@keys) {
 7332: 	if ($key=~/^\Q$filename\E_/) {
 7333: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 7334: 		$key=~/remember_skipping/) {
 7335: 		next;
 7336: 	    }
 7337: 	    push(@todelete,$key);
 7338: 	}
 7339:     }
 7340:     my $result;
 7341:     if (@todelete) {
 7342: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 7343: 				       \@todelete,$cdom,$cname);
 7344:     } else {
 7345: 	$result = 'ok';
 7346:     }
 7347:     return $result;
 7348: }
 7349: 
 7350: 
 7351: =pod
 7352: 
 7353: =item scantron_getfile
 7354: 
 7355:     Fetches the requested bubblesheet data file (all 3 versions), and
 7356:     the scan_data hash
 7357:   
 7358:   Arguments:
 7359:     None
 7360: 
 7361:   Returns:
 7362:     2 hash references
 7363: 
 7364:      - first one has 
 7365:          orig      -
 7366:          corrected -
 7367:          skipped   -  each of which points to an array ref of the specified
 7368:                       file broken up into individual lines
 7369:          count     - number of scanlines
 7370:  
 7371:      - second is the scan_data hash possible keys are
 7372:        ($number refers to scanline numbered $number and thus the key affects
 7373:         only that scanline
 7374:         $bubline refers to the specific bubble line element and the aspects
 7375:         refers to that specific bubble line element)
 7376: 
 7377:        $number.user - username:domain to use
 7378:        $number.CODE_ignore_dup 
 7379:                     - ignore the duplicate CODE error 
 7380:        $number.useCODE
 7381:                     - use the CODE in the scanline as is
 7382:        $number.no_bubble.$bubline
 7383:                     - it is valid that there is no bubbled in bubble
 7384:                       at $number $bubline
 7385:        remember_skipping
 7386:                     - a frozen hash containing keys of $number and values
 7387:                       of either 
 7388:                         1 - we are on a 'do skipped records pass' and plan
 7389:                             on processing this line
 7390:                         2 - we are on a 'do skipped records pass' and this
 7391:                             scanline has been marked to skip yet again
 7392: 
 7393: =cut
 7394: 
 7395: sub scantron_getfile {
 7396:     #FIXME really would prefer a scantron directory
 7397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7399:     my $lines;
 7400:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7401: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 7402:     my %scanlines;
 7403:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 7404:     my $temp=$scanlines{'orig'};
 7405:     $scanlines{'count'}=$#$temp;
 7406: 
 7407:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7408: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 7409:     if ($lines eq '-1') {
 7410: 	$scanlines{'corrected'}=[];
 7411:     } else {
 7412: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 7413:     }
 7414:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 7415: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 7416:     if ($lines eq '-1') {
 7417: 	$scanlines{'skipped'}=[];
 7418:     } else {
 7419: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 7420:     }
 7421:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 7422:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 7423:     my %scan_data = @tmp;
 7424:     return (\%scanlines,\%scan_data);
 7425: }
 7426: 
 7427: =pod
 7428: 
 7429: =item lonnet_putfile
 7430: 
 7431:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 7432: 
 7433:  Arguments:
 7434:    $contents - data to store
 7435:    $filename - filename to store $contents into
 7436: 
 7437:  Returns:
 7438:    result value from &Apache::lonnet::finishuserfileupload
 7439: 
 7440: =cut
 7441: 
 7442: sub lonnet_putfile {
 7443:     my ($contents,$filename)=@_;
 7444:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7445:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7446:     $env{'form.sillywaytopassafilearound'}=$contents;
 7447:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 7448: 
 7449: }
 7450: 
 7451: =pod
 7452: 
 7453: =item scantron_putfile
 7454: 
 7455:     Stores the current version of the bubblesheet data files, and the
 7456:     scan_data hash. (Does not modify the original version only the
 7457:     corrected and skipped versions.
 7458: 
 7459:  Arguments:
 7460:     $scanlines - hash ref that looks like the first return value from
 7461:                  &scantron_getfile()
 7462:     $scan_data - hash ref that looks like the second return value from
 7463:                  &scantron_getfile()
 7464: 
 7465: =cut
 7466: 
 7467: sub scantron_putfile {
 7468:     my ($scanlines,$scan_data) = @_;
 7469:     #FIXME really would prefer a scantron directory
 7470:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7471:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7472:     if ($scanlines) {
 7473: 	my $prefix='scantron_';
 7474: # no need to update orig, shouldn't change
 7475: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 7476: #		    $env{'form.scantron_selectfile'});
 7477: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 7478: 			$prefix.'corrected_'.
 7479: 			$env{'form.scantron_selectfile'});
 7480: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 7481: 			$prefix.'skipped_'.
 7482: 			$env{'form.scantron_selectfile'});
 7483:     }
 7484:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 7485: }
 7486: 
 7487: =pod
 7488: 
 7489: =item scantron_get_line
 7490: 
 7491:    Returns the correct version of the scanline
 7492: 
 7493:  Arguments:
 7494:     $scanlines - hash ref that looks like the first return value from
 7495:                  &scantron_getfile()
 7496:     $scan_data - hash ref that looks like the second return value from
 7497:                  &scantron_getfile()
 7498:     $i         - number of the requested line (starts at 0)
 7499: 
 7500:  Returns:
 7501:    A scanline, (either the original or the corrected one if it
 7502:    exists), or undef if the requested scanline should be
 7503:    skipped. (Either because it's an skipped scanline, or it's an
 7504:    unskipped scanline and we are not doing a 'do skipped scanlines'
 7505:    pass.
 7506: 
 7507: =cut
 7508: 
 7509: sub scantron_get_line {
 7510:     my ($scanlines,$scan_data,$i)=@_;
 7511:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 7512:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 7513:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 7514:     return $scanlines->{'orig'}[$i]; 
 7515: }
 7516: 
 7517: =pod
 7518: 
 7519: =item scantron_todo_count
 7520: 
 7521:     Counts the number of scanlines that need processing.
 7522: 
 7523:  Arguments:
 7524:     $scanlines - hash ref that looks like the first return value from
 7525:                  &scantron_getfile()
 7526:     $scan_data - hash ref that looks like the second return value from
 7527:                  &scantron_getfile()
 7528: 
 7529:  Returns:
 7530:     $count - number of scanlines to process
 7531: 
 7532: =cut
 7533: 
 7534: sub get_todo_count {
 7535:     my ($scanlines,$scan_data)=@_;
 7536:     my $count=0;
 7537:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7538: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7539: 	if ($line=~/^[\s\cz]*$/) { next; }
 7540: 	$count++;
 7541:     }
 7542:     return $count;
 7543: }
 7544: 
 7545: =pod
 7546: 
 7547: =item scantron_put_line
 7548: 
 7549:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
 7550:     data file.
 7551: 
 7552:  Arguments:
 7553:     $scanlines - hash ref that looks like the first return value from
 7554:                  &scantron_getfile()
 7555:     $scan_data - hash ref that looks like the second return value from
 7556:                  &scantron_getfile()
 7557:     $i         - line number to update
 7558:     $newline   - contents of the updated scanline
 7559:     $skip      - if true make the line for skipping and update the
 7560:                  'skipped' file
 7561: 
 7562: =cut
 7563: 
 7564: sub scantron_put_line {
 7565:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 7566:     if ($skip) {
 7567: 	$scanlines->{'skipped'}[$i]=$newline;
 7568: 	&start_skipping($scan_data,$i);
 7569: 	return;
 7570:     }
 7571:     $scanlines->{'corrected'}[$i]=$newline;
 7572: }
 7573: 
 7574: =pod
 7575: 
 7576: =item scantron_clear_skip
 7577: 
 7578:    Remove a line from the 'skipped' file
 7579: 
 7580:  Arguments:
 7581:     $scanlines - hash ref that looks like the first return value from
 7582:                  &scantron_getfile()
 7583:     $scan_data - hash ref that looks like the second return value from
 7584:                  &scantron_getfile()
 7585:     $i         - line number to update
 7586: 
 7587: =cut
 7588: 
 7589: sub scantron_clear_skip {
 7590:     my ($scanlines,$scan_data,$i)=@_;
 7591:     if (exists($scanlines->{'skipped'}[$i])) {
 7592: 	undef($scanlines->{'skipped'}[$i]);
 7593: 	return 1;
 7594:     }
 7595:     return 0;
 7596: }
 7597: 
 7598: =pod
 7599: 
 7600: =item scantron_filter_not_exam
 7601: 
 7602:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 7603:    filter out resources that are not marked as 'exam' mode
 7604: 
 7605: =cut
 7606: 
 7607: sub scantron_filter_not_exam {
 7608:     my ($curres)=@_;
 7609:     
 7610:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 7611: 	# if the user has asked to not have either hidden
 7612: 	# or 'randomout' controlled resources to be graded
 7613: 	# don't include them
 7614: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 7615: 	    && $curres->randomout) {
 7616: 	    return 0;
 7617: 	}
 7618: 	return 1;
 7619:     }
 7620:     return 0;
 7621: }
 7622: 
 7623: =pod
 7624: 
 7625: =item scantron_validate_sequence
 7626: 
 7627:     Validates the selected sequence, checking for resource that are
 7628:     not set to exam mode.
 7629: 
 7630: =cut
 7631: 
 7632: sub scantron_validate_sequence {
 7633:     my ($r,$currentphase) = @_;
 7634: 
 7635:     my $navmap=Apache::lonnavmaps::navmap->new();
 7636:     unless (ref($navmap)) {
 7637:         $r->print(&navmap_errormsg());
 7638:         return (1,$currentphase);
 7639:     }
 7640:     my (undef,undef,$sequence)=
 7641: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7642: 
 7643:     my $map=$navmap->getResourceByUrl($sequence);
 7644: 
 7645:     $r->print('<input type="hidden" name="validate_sequence_exam"
 7646:                                     value="ignore" />');
 7647:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 7648: 	my @resources=
 7649: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 7650: 	if (@resources) {
 7651: 	    $r->print(
 7652:                 '<p class="LC_warning">'
 7653:                .&mt('Some resources in the sequence currently are not set to'
 7654:                    .' bubblesheet exam mode. Grading these resources currently may not'
 7655:                    .' work correctly.')
 7656:                .'</p>'
 7657:             );
 7658: 	    return (1,$currentphase);
 7659: 	}
 7660:     }
 7661: 
 7662:     return (0,$currentphase+1);
 7663: }
 7664: 
 7665: 
 7666: 
 7667: sub scantron_validate_ID {
 7668:     my ($r,$currentphase) = @_;
 7669:     
 7670:     #get student info
 7671:     my $classlist=&Apache::loncoursedata::get_classlist();
 7672:     my %idmap=&username_to_idmap($classlist);
 7673: 
 7674:     #get scantron line setup
 7675:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7676:     my ($scanlines,$scan_data)=&scantron_getfile();
 7677: 
 7678:     my $nav_error;
 7679:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
 7680:     if ($nav_error) {
 7681:         $r->print(&navmap_errormsg());
 7682:         return(1,$currentphase);
 7683:     }
 7684: 
 7685:     my %found=('ids'=>{},'usernames'=>{});
 7686:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7687: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7688: 	if ($line=~/^[\s\cz]*$/) { next; }
 7689: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7690: 						 $scan_data);
 7691: 	my $id=$$scan_record{'scantron.ID'};
 7692: 	my $found;
 7693: 	foreach my $checkid (keys(%idmap)) {
 7694: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 7695: 	}
 7696: 	if ($found) {
 7697: 	    my $username=$idmap{$found};
 7698: 	    if ($found{'ids'}{$found}) {
 7699: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7700: 					 $line,'duplicateID',$found);
 7701: 		return(1,$currentphase);
 7702: 	    } elsif ($found{'usernames'}{$username}) {
 7703: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7704: 					 $line,'duplicateID',$username);
 7705: 		return(1,$currentphase);
 7706: 	    }
 7707: 	    #FIXME store away line we previously saw the ID on to use above
 7708: 	    $found{'ids'}{$found}++;
 7709: 	    $found{'usernames'}{$username}++;
 7710: 	} else {
 7711: 	    if ($id =~ /^\s*$/) {
 7712: 		my $username=&scan_data($scan_data,"$i.user");
 7713: 		if (defined($username) && $found{'usernames'}{$username}) {
 7714: 		    &scantron_get_correction($r,$i,$scan_record,
 7715: 					     \%scantron_config,
 7716: 					     $line,'duplicateID',$username);
 7717: 		    return(1,$currentphase);
 7718: 		} elsif (!defined($username)) {
 7719: 		    &scantron_get_correction($r,$i,$scan_record,
 7720: 					     \%scantron_config,
 7721: 					     $line,'incorrectID');
 7722: 		    return(1,$currentphase);
 7723: 		}
 7724: 		$found{'usernames'}{$username}++;
 7725: 	    } else {
 7726: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7727: 					 $line,'incorrectID');
 7728: 		return(1,$currentphase);
 7729: 	    }
 7730: 	}
 7731:     }
 7732: 
 7733:     return (0,$currentphase+1);
 7734: }
 7735: 
 7736: 
 7737: sub scantron_get_correction {
 7738:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
 7739:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
 7740: #FIXME in the case of a duplicated ID the previous line, probably need
 7741: #to show both the current line and the previous one and allow skipping
 7742: #the previous one or the current one
 7743: 
 7744:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 7745:         $r->print(
 7746:             '<p class="LC_warning">'
 7747:            .&mt('An error was detected ([_1]) for PaperID [_2]',
 7748:                 "<b>$error</b>",
 7749:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
 7750:            ."</p> \n");
 7751:     } else {
 7752:         $r->print(
 7753:             '<p class="LC_warning">'
 7754:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
 7755:                 "<b>$error</b>", $i, "<pre>$line</pre>")
 7756:            ."</p> \n");
 7757:     }
 7758:     my $message =
 7759:         '<p>'
 7760:        .&mt('The ID on the form is [_1]',
 7761:             "<tt>$$scan_record{'scantron.ID'}</tt>")
 7762:        .'<br />'
 7763:        .&mt('The name on the paper is [_1], [_2]',
 7764:             $$scan_record{'scantron.LastName'},
 7765:             $$scan_record{'scantron.FirstName'})
 7766:        .'</p>';
 7767: 
 7768:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 7769:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 7770:                            # Array populated for doublebubble or
 7771:     my @lines_to_correct;  # missingbubble errors to build javascript
 7772:                            # to validate radio button checking   
 7773: 
 7774:     if ($error =~ /ID$/) {
 7775: 	if ($error eq 'incorrectID') {
 7776:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
 7777: 		      "</p>\n");
 7778: 	} elsif ($error eq 'duplicateID') {
 7779:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7780: 	}
 7781: 	$r->print($message);
 7782: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7783: 	$r->print("\n<ul><li> ");
 7784: 	#FIXME it would be nice if this sent back the user ID and
 7785: 	#could do partial userID matches
 7786: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7787: 				       'scantron_username','scantron_domain'));
 7788: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7789: 	$r->print("\n:\n".
 7790: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7791: 
 7792: 	$r->print('</li>');
 7793:     } elsif ($error =~ /CODE$/) {
 7794: 	if ($error eq 'incorrectCODE') {
 7795: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7796: 	} elsif ($error eq 'duplicateCODE') {
 7797: 	    $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");
 7798: 	}
 7799: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
 7800: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
 7801:                  ."</p>\n");
 7802: 	$r->print($message);
 7803: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
 7804: 	$r->print("\n<br /> ");
 7805: 	my $i=0;
 7806: 	if ($error eq 'incorrectCODE' 
 7807: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7808: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7809: 	    if ($closest > 0) {
 7810: 		foreach my $testcode (@{$closest}) {
 7811: 		    my $checked='';
 7812: 		    if (!$i) { $checked=' checked="checked"'; }
 7813: 		    $r->print("
 7814:    <label>
 7815:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7816:        ".&mt("Use the similar CODE [_1] instead.",
 7817: 	    "<b><tt>".$testcode."</tt></b>")."
 7818:     </label>
 7819:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7820: 		    $r->print("\n<br />");
 7821: 		    $i++;
 7822: 		}
 7823: 	    }
 7824: 	}
 7825: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7826: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7827: 	    $r->print("
 7828:     <label>
 7829:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7830:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
 7831: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7832:     </label>");
 7833: 	    $r->print("\n<br />");
 7834: 	}
 7835: 
 7836: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
 7837: function change_radio(field) {
 7838:     var slct=document.scantronupload.scantron_CODE_resolution;
 7839:     var i;
 7840:     for (i=0;i<slct.length;i++) {
 7841:         if (slct[i].value==field) { slct[i].checked=true; }
 7842:     }
 7843: }
 7844: ENDSCRIPT
 7845: 	my $href="/adm/pickcode?".
 7846: 	   "form=".&escape("scantronupload").
 7847: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7848: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7849: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7850: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7851: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7852: 	    $r->print("
 7853:     <label>
 7854:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7855:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7856: 	     "<a target='_blank' href='$href'>","</a>")."
 7857:     </label> 
 7858:     ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
 7859: 	    $r->print("\n<br />");
 7860: 	}
 7861: 	$r->print("
 7862:     <label>
 7863:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7864:        ".&mt("Use [_1] as the CODE.",
 7865: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7866: 	$r->print("\n<br /><br />");
 7867:     } elsif ($error eq 'doublebubble') {
 7868: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7869: 
 7870: 	# The form field scantron_questions is acutally a list of line numbers.
 7871: 	# represented by this form so:
 7872: 
 7873: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7874:                                                 $respnumlookup,$startline);
 7875: 
 7876: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7877: 		  $line_list.'" />');
 7878: 	$r->print($message);
 7879: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7880: 	foreach my $question (@{$arg}) {
 7881: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7882:                                                    $scan_record, $error,
 7883:                                                    $randomorder,$randompick,
 7884:                                                    $respnumlookup,$startline);
 7885:             push(@lines_to_correct,@linenums);
 7886: 	}
 7887:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7888:     } elsif ($error eq 'missingbubble') {
 7889: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
 7890: 	$r->print($message);
 7891: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7892: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7893: 
 7894: 	# The form field scantron_questions is actually a list of line numbers not
 7895: 	# a list of question numbers. Therefore:
 7896: 	#
 7897: 
 7898: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
 7899:                                                 $respnumlookup,$startline);
 7900: 
 7901: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7902: 		  $line_list.'" />');
 7903: 	foreach my $question (@{$arg}) {
 7904: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7905:                                                    $scan_record, $error,
 7906:                                                    $randomorder,$randompick,
 7907:                                                    $respnumlookup,$startline);
 7908:             push(@lines_to_correct,@linenums);
 7909: 	}
 7910:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7911:     } else {
 7912: 	$r->print("\n<ul>");
 7913:     }
 7914:     $r->print("\n</li></ul>");
 7915: }
 7916: 
 7917: sub verify_bubbles_checked {
 7918:     my (@ansnums) = @_;
 7919:     my $ansnumstr = join('","',@ansnums);
 7920:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7921:     &js_escape(\$warning);
 7922:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
 7923: function verify_bubble_radio(form) {
 7924:     var ansnumArray = new Array ("$ansnumstr");
 7925:     var need_bubble_count = 0;
 7926:     for (var i=0; i<ansnumArray.length; i++) {
 7927:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7928:             var bubble_picked = 0; 
 7929:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7930:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7931:                     bubble_picked = 1;
 7932:                 }
 7933:             }
 7934:             if (bubble_picked == 0) {
 7935:                 need_bubble_count ++;
 7936:             }
 7937:         }
 7938:     }
 7939:     if (need_bubble_count) {
 7940:         alert("$warning");
 7941:         return;
 7942:     }
 7943:     form.submit(); 
 7944: }
 7945: ENDSCRIPT
 7946:     return $output;
 7947: }
 7948: 
 7949: =pod
 7950: 
 7951: =item  questions_to_line_list
 7952: 
 7953: Converts a list of questions into a string of comma separated
 7954: line numbers in the answer sheet used by the questions.  This is
 7955: used to fill in the scantron_questions form field.
 7956: 
 7957:   Arguments:
 7958:      questions    - Reference to an array of questions.
 7959:      randomorder  - True if randomorder in use.
 7960:      randompick   - True if randompick in use.
 7961:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
 7962:                      for current line to question number used for same question
 7963:                      in "Master Seqence" (as seen by Course Coordinator).
 7964:      startline    - Reference to hash where key is question number (0 is first)
 7965:                     and key is number of first bubble line for current student
 7966:                     or code-based randompick and/or randomorder.
 7967: 
 7968: =cut
 7969: 
 7970: 
 7971: sub questions_to_line_list {
 7972:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
 7973:     my @lines;
 7974: 
 7975:     foreach my $item (@{$questions}) {
 7976:         my $question = $item;
 7977:         my ($first,$count,$last);
 7978:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7979:             $question = $1;
 7980:             my $subquestion = $2;
 7981:             my $responsenum = $question-1;
 7982:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 7983:                 $responsenum = $respnumlookup->{$question-1};
 7984:                 if (ref($startline) eq 'HASH') {
 7985:                     $first = $startline->{$question-1} + 1;
 7986:                 }
 7987:             } else {
 7988:                 $first = $first_bubble_line{$responsenum} + 1;
 7989:             }
 7990:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 7991:             my $subcount = 1;
 7992:             while ($subcount<$subquestion) {
 7993:                 $first += $subans[$subcount-1];
 7994:                 $subcount ++;
 7995:             }
 7996:             $count = $subans[$subquestion-1];
 7997:         } else {
 7998:             my $responsenum = $question-1;
 7999:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8000:                 $responsenum = $respnumlookup->{$question-1};
 8001:                 if (ref($startline) eq 'HASH') {
 8002:                     $first = $startline->{$question-1} + 1;
 8003:                 }
 8004:             } else {
 8005:                 $first = $first_bubble_line{$responsenum} + 1;
 8006:             }
 8007: 	    $count   = $bubble_lines_per_response{$responsenum};
 8008:         }
 8009:         $last = $first+$count-1;
 8010:         push(@lines, ($first..$last));
 8011:     }
 8012:     return join(',', @lines);
 8013: }
 8014: 
 8015: =pod 
 8016: 
 8017: =item prompt_for_corrections
 8018: 
 8019: Prompts for a potentially multiline correction to the
 8020: user's bubbling (factors out common code from scantron_get_correction
 8021: for multi and missing bubble cases).
 8022: 
 8023:  Arguments:
 8024:    $r           - Apache request object.
 8025:    $question    - The question number to prompt for.
 8026:    $scan_config - The scantron file configuration hash.
 8027:    $scan_record - Reference to the hash that has the the parsed scanlines.
 8028:    $error       - Type of error
 8029:    $randomorder - True if randomorder in use.
 8030:    $randompick  - True if randompick in use.
 8031:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
 8032:                     for current line to question number used for same question
 8033:                     in "Master Seqence" (as seen by Course Coordinator).
 8034:    $startline   - Reference to hash where key is question number (0 is first)
 8035:                   and value is number of first bubble line for current student
 8036:                   or code-based randompick and/or randomorder.
 8037: 
 8038: 
 8039:  Implicit inputs:
 8040:    %bubble_lines_per_response   - Starting line numbers for each question.
 8041:                                   Numbered from 0 (but question numbers are from
 8042:                                   1.
 8043:    %first_bubble_line           - Starting bubble line for each question.
 8044:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 8045:                                   type problems render as separate sub-questions, 
 8046:                                   in exam mode. This hash contains a 
 8047:                                   comma-separated list of the lines per 
 8048:                                   sub-question.
 8049:    %responsetype_per_response   - essayresponse, formularesponse,
 8050:                                   stringresponse, imageresponse, reactionresponse,
 8051:                                   and organicresponse type problem parts can have
 8052:                                   multiple lines per response if the weight
 8053:                                   assigned exceeds 10.  In this case, only
 8054:                                   one bubble per line is permitted, but more 
 8055:                                   than one line might contain bubbles, e.g.
 8056:                                   bubbling of: line 1 - J, line 2 - J, 
 8057:                                   line 3 - B would assign 22 points.  
 8058: 
 8059: =cut
 8060: 
 8061: sub prompt_for_corrections {
 8062:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
 8063:         $randompick, $respnumlookup, $startline) = @_;
 8064:     my ($current_line,$lines);
 8065:     my @linenums;
 8066:     my $questionnum = $question;
 8067:     my ($first,$responsenum);
 8068:     if ($question =~ /^(\d+)\.(\d+)$/) {
 8069:         $question = $1;
 8070:         my $subquestion = $2;
 8071:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8072:             $responsenum = $respnumlookup->{$question-1};
 8073:             if (ref($startline) eq 'HASH') {
 8074:                 $first = $startline->{$question-1};
 8075:             }
 8076:         } else {
 8077:             $responsenum = $question-1;
 8078:             $first = $first_bubble_line{$responsenum};
 8079:         }
 8080:         $current_line = $first + 1 ;
 8081:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8082:         my $subcount = 1;
 8083:         while ($subcount<$subquestion) {
 8084:             $current_line += $subans[$subcount-1];
 8085:             $subcount ++;
 8086:         }
 8087:         $lines = $subans[$subquestion-1];
 8088:     } else {
 8089:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
 8090:             $responsenum = $respnumlookup->{$question-1};
 8091:             if (ref($startline) eq 'HASH') { 
 8092:                 $first = $startline->{$question-1};
 8093:             }
 8094:         } else {
 8095:             $responsenum = $question-1;
 8096:             $first = $first_bubble_line{$responsenum};
 8097:         }
 8098:         $current_line = $first + 1;
 8099:         $lines        = $bubble_lines_per_response{$responsenum};
 8100:     }
 8101:     if ($lines > 1) {
 8102:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 8103:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
 8104:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
 8105:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
 8106:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
 8107:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
 8108:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
 8109:             $r->print(
 8110:                 &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)
 8111:                .'<br /><br />'
 8112:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
 8113:                .'<br />'
 8114:                .&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.')
 8115:                .'<br />'
 8116:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
 8117:                .'<br /><br />'
 8118:             );
 8119:         } else {
 8120:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 8121:         }
 8122:     }
 8123:     for (my $i =0; $i < $lines; $i++) {
 8124:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 8125: 	&scantron_bubble_selector($r,$scan_config,$current_line,
 8126: 	        		  $questionnum,$error,split('', $selected));
 8127:         push(@linenums,$current_line);
 8128: 	$current_line++;
 8129:     }
 8130:     if ($lines > 1) {
 8131: 	$r->print("<hr /><br />");
 8132:     }
 8133:     return @linenums;
 8134: }
 8135: 
 8136: =pod
 8137: 
 8138: =item scantron_bubble_selector
 8139:   
 8140:    Generates the html radiobuttons to correct a single bubble line
 8141:    possibly showing the existing the selected bubbles if known
 8142: 
 8143:  Arguments:
 8144:     $r           - Apache request object
 8145:     $scan_config - hash from &get_scantron_config()
 8146:     $line        - Number of the line being displayed.
 8147:     $questionnum - Question number (may include subquestion)
 8148:     $error       - Type of error.
 8149:     @selected    - Array of bubbles picked on this line.
 8150: 
 8151: =cut
 8152: 
 8153: sub scantron_bubble_selector {
 8154:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 8155:     my $max=$$scan_config{'Qlength'};
 8156: 
 8157:     my $scmode=$$scan_config{'Qon'};
 8158:     if ($scmode eq 'number' || $scmode eq 'letter') { 
 8159:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
 8160:             ($$scan_config{'BubblesPerRow'} > 0)) {
 8161:             $max=$$scan_config{'BubblesPerRow'};
 8162:             if (($scmode eq 'number') && ($max > 10)) {
 8163:                 $max = 10;
 8164:             } elsif (($scmode eq 'letter') && $max > 26) {
 8165:                 $max = 26;
 8166:             }
 8167:         } else {
 8168:             $max = 10;
 8169:         }
 8170:     }
 8171: 
 8172:     my @alphabet=('A'..'Z');
 8173:     $r->print(&Apache::loncommon::start_data_table().
 8174:               &Apache::loncommon::start_data_table_row());
 8175:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 8176:     for (my $i=0;$i<$max+1;$i++) {
 8177: 	$r->print("\n".'<td align="center">');
 8178: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 8179: 	else { $r->print('&nbsp;'); }
 8180: 	$r->print('</td>');
 8181:     }
 8182:     $r->print(&Apache::loncommon::end_data_table_row().
 8183:               &Apache::loncommon::start_data_table_row());
 8184:     for (my $i=0;$i<$max;$i++) {
 8185: 	$r->print("\n".
 8186: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 8187: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 8188:     }
 8189:     my $nobub_checked = ' ';
 8190:     if ($error eq 'missingbubble') {
 8191:         $nobub_checked = ' checked = "checked" ';
 8192:     }
 8193:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 8194: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 8195:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 8196:               $line.'" value="'.$questionnum.'" /></td>');
 8197:     $r->print(&Apache::loncommon::end_data_table_row().
 8198:               &Apache::loncommon::end_data_table());
 8199: }
 8200: 
 8201: =pod
 8202: 
 8203: =item num_matches
 8204: 
 8205:    Counts the number of characters that are the same between the two arguments.
 8206: 
 8207:  Arguments:
 8208:    $orig - CODE from the scanline
 8209:    $code - CODE to match against
 8210: 
 8211:  Returns:
 8212:    $count - integer count of the number of same characters between the
 8213:             two arguments
 8214: 
 8215: =cut
 8216: 
 8217: sub num_matches {
 8218:     my ($orig,$code) = @_;
 8219:     my @code=split(//,$code);
 8220:     my @orig=split(//,$orig);
 8221:     my $same=0;
 8222:     for (my $i=0;$i<scalar(@code);$i++) {
 8223: 	if ($code[$i] eq $orig[$i]) { $same++; }
 8224:     }
 8225:     return $same;
 8226: }
 8227: 
 8228: =pod
 8229: 
 8230: =item scantron_get_closely_matching_CODEs
 8231: 
 8232:    Cycles through all CODEs and finds the set that has the greatest
 8233:    number of same characters as the provided CODE
 8234: 
 8235:  Arguments:
 8236:    $allcodes - hash ref returned by &get_codes()
 8237:    $CODE     - CODE from the current scanline
 8238: 
 8239:  Returns:
 8240:    2 element list
 8241:     - first elements is number of how closely matching the best fit is 
 8242:       (5 means best set has 5 matching characters)
 8243:     - second element is an arrary ref containing the set of valid CODEs
 8244:       that best fit the passed in CODE
 8245: 
 8246: =cut
 8247: 
 8248: sub scantron_get_closely_matching_CODEs {
 8249:     my ($allcodes,$CODE)=@_;
 8250:     my @CODEs;
 8251:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 8252: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 8253:     }
 8254: 
 8255:     return ($#CODEs,$CODEs[-1]);
 8256: }
 8257: 
 8258: =pod
 8259: 
 8260: =item get_codes
 8261: 
 8262:    Builds a hash which has keys of all of the valid CODEs from the selected
 8263:    set of remembered CODEs.
 8264: 
 8265:  Arguments:
 8266:   $old_name - name of the set of remembered CODEs
 8267:   $cdom     - domain of the course
 8268:   $cnum     - internal course name
 8269: 
 8270:  Returns:
 8271:   %allcodes - keys are the valid CODEs, values are all 1
 8272: 
 8273: =cut
 8274: 
 8275: sub get_codes {
 8276:     my ($old_name, $cdom, $cnum) = @_;
 8277:     if (!$old_name) {
 8278: 	$old_name=$env{'form.scantron_CODElist'};
 8279:     }
 8280:     if (!$cdom) {
 8281: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 8282:     }
 8283:     if (!$cnum) {
 8284: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 8285:     }
 8286:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 8287: 				    $cdom,$cnum);
 8288:     my %allcodes;
 8289:     if ($result{"type\0$old_name"} eq 'number') {
 8290: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 8291:     } else {
 8292: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 8293:     }
 8294:     return %allcodes;
 8295: }
 8296: 
 8297: =pod
 8298: 
 8299: =item scantron_validate_CODE
 8300: 
 8301:    Validates all scanlines in the selected file to not have any
 8302:    invalid or underspecified CODEs and that none of the codes are
 8303:    duplicated if this was requested.
 8304: 
 8305: =cut
 8306: 
 8307: sub scantron_validate_CODE {
 8308:     my ($r,$currentphase) = @_;
 8309:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8310:     if ($scantron_config{'CODElocation'} &&
 8311: 	$scantron_config{'CODEstart'} &&
 8312: 	$scantron_config{'CODElength'}) {
 8313: 	if (!defined($env{'form.scantron_CODElist'})) {
 8314: 	    &FIXME_blow_up()
 8315: 	}
 8316:     } else {
 8317: 	return (0,$currentphase+1);
 8318:     }
 8319:     
 8320:     my %usedCODEs;
 8321: 
 8322:     my %allcodes=&get_codes();
 8323: 
 8324:     my $nav_error;
 8325:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
 8326:     if ($nav_error) {
 8327:         $r->print(&navmap_errormsg());
 8328:         return(1,$currentphase);
 8329:     }
 8330: 
 8331:     my ($scanlines,$scan_data)=&scantron_getfile();
 8332:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8333: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8334: 	if ($line=~/^[\s\cz]*$/) { next; }
 8335: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8336: 						 $scan_data);
 8337: 	my $CODE=$$scan_record{'scantron.CODE'};
 8338: 	my $error=0;
 8339: 	if (!&Apache::lonnet::validCODE($CODE)) {
 8340: 	    &scantron_get_correction($r,$i,$scan_record,
 8341: 				     \%scantron_config,
 8342: 				     $line,'incorrectCODE',\%allcodes);
 8343: 	    return(1,$currentphase);
 8344: 	}
 8345: 	if (%allcodes && !exists($allcodes{$CODE}) 
 8346: 	    && !$$scan_record{'scantron.useCODE'}) {
 8347: 	    &scantron_get_correction($r,$i,$scan_record,
 8348: 				     \%scantron_config,
 8349: 				     $line,'incorrectCODE',\%allcodes);
 8350: 	    return(1,$currentphase);
 8351: 	}
 8352: 	if (exists($usedCODEs{$CODE}) 
 8353: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 8354: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 8355: 	    &scantron_get_correction($r,$i,$scan_record,
 8356: 				     \%scantron_config,
 8357: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 8358: 	    return(1,$currentphase);
 8359: 	}
 8360: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 8361:     }
 8362:     return (0,$currentphase+1);
 8363: }
 8364: 
 8365: =pod
 8366: 
 8367: =item scantron_validate_doublebubble
 8368: 
 8369:    Validates all scanlines in the selected file to not have any
 8370:    bubble lines with multiple bubbles marked.
 8371: 
 8372: =cut
 8373: 
 8374: sub scantron_validate_doublebubble {
 8375:     my ($r,$currentphase) = @_;
 8376:     #get student info
 8377:     my $classlist=&Apache::loncoursedata::get_classlist();
 8378:     my %idmap=&username_to_idmap($classlist);
 8379:     my (undef,undef,$sequence)=
 8380:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8381: 
 8382:     #get scantron line setup
 8383:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8384:     my ($scanlines,$scan_data)=&scantron_getfile();
 8385: 
 8386:     my $navmap = Apache::lonnavmaps::navmap->new();
 8387:     unless (ref($navmap)) {
 8388:         $r->print(&navmap_errormsg());
 8389:         return(1,$currentphase);
 8390:     }
 8391:     my $map=$navmap->getResourceByUrl($sequence);
 8392:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8393:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8394:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8395:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8396: 
 8397:     my $nav_error;
 8398:     if (ref($map)) {
 8399:         $randomorder = $map->randomorder();
 8400:         $randompick = $map->randompick();
 8401:         if ($randomorder || $randompick) {
 8402:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8403:             if ($nav_error) {
 8404:                 $r->print(&navmap_errormsg());
 8405:                 return(1,$currentphase);
 8406:             }
 8407:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8408:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8409:         }
 8410:     } else {
 8411:         $r->print(&navmap_errormsg());
 8412:         return(1,$currentphase);
 8413:     }
 8414: 
 8415:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
 8416:     if ($nav_error) {
 8417:         $r->print(&navmap_errormsg());
 8418:         return(1,$currentphase);
 8419:     }
 8420: 
 8421:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8422: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8423: 	if ($line=~/^[\s\cz]*$/) { next; }
 8424: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8425: 						 $scan_data,undef,\%idmap,$randomorder,
 8426:                                                  $randompick,$sequence,\@master_seq,
 8427:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8428:                                                  \%orderedforcode,\%respnumlookup,\%startline);
 8429: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 8430: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 8431: 				 'doublebubble',
 8432: 				 $$scan_record{'scantron.doubleerror'},
 8433:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
 8434:     	return (1,$currentphase);
 8435:     }
 8436:     return (0,$currentphase+1);
 8437: }
 8438: 
 8439: 
 8440: sub scantron_get_maxbubble {
 8441:     my ($nav_error,$scantron_config) = @_;
 8442:     if (defined($env{'form.scantron_maxbubble'}) &&
 8443: 	$env{'form.scantron_maxbubble'}) {
 8444: 	&restore_bubble_lines();
 8445: 	return $env{'form.scantron_maxbubble'};
 8446:     }
 8447: 
 8448:     my (undef, undef, $sequence) =
 8449: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8450: 
 8451:     my $navmap=Apache::lonnavmaps::navmap->new();
 8452:     unless (ref($navmap)) {
 8453:         if (ref($nav_error)) {
 8454:             $$nav_error = 1;
 8455:         }
 8456:         return;
 8457:     }
 8458:     my $map=$navmap->getResourceByUrl($sequence);
 8459:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8460:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
 8461: 
 8462:     &Apache::lonxml::clear_problem_counter();
 8463: 
 8464:     my $uname       = $env{'user.name'};
 8465:     my $udom        = $env{'user.domain'};
 8466:     my $cid         = $env{'request.course.id'};
 8467:     my $total_lines = 0;
 8468:     %bubble_lines_per_response = ();
 8469:     %first_bubble_line         = ();
 8470:     %subdivided_bubble_lines   = ();
 8471:     %responsetype_per_response = ();
 8472:     %masterseq_id_responsenum  = ();
 8473: 
 8474:     my $response_number = 0;
 8475:     my $bubble_line     = 0;
 8476:     foreach my $resource (@resources) {
 8477:         my $resid = $resource->id(); 
 8478:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
 8479:                                                           $udom,undef,$bubbles_per_row);
 8480:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 8481: 	    foreach my $part_id (@{$parts}) {
 8482:                 my $lines;
 8483: 
 8484: 	        # TODO - make this a persistent hash not an array.
 8485: 
 8486:                 # optionresponse, matchresponse and rankresponse type items 
 8487:                 # render as separate sub-questions in exam mode.
 8488:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 8489:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 8490:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 8491:                     my ($numbub,$numshown);
 8492:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 8493:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 8494:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 8495:                         }
 8496:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 8497:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 8498:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 8499:                         }
 8500:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 8501:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 8502:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 8503:                         }
 8504:                     }
 8505:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 8506:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 8507:                     }
 8508:                     my $bubbles_per_row =
 8509:                         &bubblesheet_bubbles_per_row($scantron_config);
 8510:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
 8511:                     if (($numbub % $bubbles_per_row) != 0) {
 8512:                         $inner_bubble_lines++;
 8513:                     }
 8514:                     for (my $i=0; $i<$numshown; $i++) {
 8515:                         $subdivided_bubble_lines{$response_number} .= 
 8516:                             $inner_bubble_lines.',';
 8517:                     }
 8518:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 8519:                     $lines = $numshown * $inner_bubble_lines;
 8520:                 } else {
 8521:                     $lines = $analysis->{"$part_id.bubble_lines"};
 8522:                 }
 8523: 
 8524:                 $first_bubble_line{$response_number} = $bubble_line;
 8525: 	        $bubble_lines_per_response{$response_number} = $lines;
 8526:                 $responsetype_per_response{$response_number} = 
 8527:                     $analysis->{$part_id.'.type'};
 8528:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
 8529: 	        $response_number++;
 8530: 
 8531: 	        $bubble_line +=  $lines;
 8532: 	        $total_lines +=  $lines;
 8533: 	    }
 8534:         }
 8535:     }
 8536:     &Apache::lonnet::delenv('scantron.');
 8537: 
 8538:     &save_bubble_lines();
 8539:     $env{'form.scantron_maxbubble'} =
 8540: 	$total_lines;
 8541:     return $env{'form.scantron_maxbubble'};
 8542: }
 8543: 
 8544: sub bubblesheet_bubbles_per_row {
 8545:     my ($scantron_config) = @_;
 8546:     my $bubbles_per_row;
 8547:     if (ref($scantron_config) eq 'HASH') {
 8548:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
 8549:     }
 8550:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
 8551:         $bubbles_per_row = 10;
 8552:     }
 8553:     return $bubbles_per_row;
 8554: }
 8555: 
 8556: sub scantron_validate_missingbubbles {
 8557:     my ($r,$currentphase) = @_;
 8558:     #get student info
 8559:     my $classlist=&Apache::loncoursedata::get_classlist();
 8560:     my %idmap=&username_to_idmap($classlist);
 8561:     my (undef,undef,$sequence)=
 8562:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8563: 
 8564:     #get scantron line setup
 8565:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8566:     my ($scanlines,$scan_data)=&scantron_getfile();
 8567: 
 8568:     my $navmap = Apache::lonnavmaps::navmap->new();
 8569:     unless (ref($navmap)) {
 8570:         $r->print(&navmap_errormsg());
 8571:         return(1,$currentphase);
 8572:     }
 8573: 
 8574:     my $map=$navmap->getResourceByUrl($sequence);
 8575:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8576:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8577:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
 8578:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8579: 
 8580:     my $nav_error;
 8581:     if (ref($map)) {
 8582:         $randomorder = $map->randomorder();
 8583:         $randompick = $map->randompick();
 8584:         if ($randomorder || $randompick) {
 8585:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8586:             if ($nav_error) {
 8587:                 $r->print(&navmap_errormsg());
 8588:                 return(1,$currentphase);
 8589:             }
 8590:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8591:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
 8592:         }
 8593:     } else {
 8594:         $r->print(&navmap_errormsg());
 8595:         return(1,$currentphase);
 8596:     }
 8597: 
 8598: 
 8599:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
 8600:     if ($nav_error) {
 8601:         $r->print(&navmap_errormsg());
 8602:         return(1,$currentphase);
 8603:     }
 8604: 
 8605:     if (!$max_bubble) { $max_bubble=2**31; }
 8606:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 8607: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8608: 	if ($line=~/^[\s\cz]*$/) { next; }
 8609: 	my $scan_record =
 8610:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
 8611: 				     $randomorder,$randompick,$sequence,\@master_seq,
 8612:                                      \%symb_to_resource,\%grader_partids_by_symb,
 8613:                                      \%orderedforcode,\%respnumlookup,\%startline);
 8614: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 8615: 	my @to_correct;
 8616: 	
 8617: 	# Probably here's where the error is...
 8618: 
 8619: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 8620:             my $lastbubble;
 8621:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 8622:                my $question = $1;
 8623:                my $subquestion = $2;
 8624:                my ($first,$responsenum);
 8625:                if ($randomorder || $randompick) {
 8626:                    $responsenum = $respnumlookup{$question-1};
 8627:                    $first = $startline{$question-1};
 8628:                } else {
 8629:                    $responsenum = $question-1; 
 8630:                    $first = $first_bubble_line{$responsenum};
 8631:                }
 8632:                if (!defined($first)) { next; }
 8633:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
 8634:                my $subcount = 1;
 8635:                while ($subcount<$subquestion) {
 8636:                    $first += $subans[$subcount-1];
 8637:                    $subcount ++;
 8638:                }
 8639:                my $count = $subans[$subquestion-1];
 8640:                $lastbubble = $first + $count;
 8641:             } else {
 8642:                my ($first,$responsenum);
 8643:                if ($randomorder || $randompick) {
 8644:                    $responsenum = $respnumlookup{$missing-1};
 8645:                    $first = $startline{$missing-1};
 8646:                } else {
 8647:                    $responsenum = $missing-1;
 8648:                    $first = $first_bubble_line{$responsenum};
 8649:                }
 8650:                if (!defined($first)) { next; }
 8651:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
 8652:             }
 8653:             if ($lastbubble > $max_bubble) { next; }
 8654: 	    push(@to_correct,$missing);
 8655: 	}
 8656: 	if (@to_correct) {
 8657: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 8658: 				     $line,'missingbubble',\@to_correct,
 8659:                                      $randomorder,$randompick,\%respnumlookup,
 8660:                                      \%startline);
 8661: 	    return (1,$currentphase);
 8662: 	}
 8663: 
 8664:     }
 8665:     return (0,$currentphase+1);
 8666: }
 8667: 
 8668: sub hand_bubble_option {
 8669:     my (undef, undef, $sequence) =
 8670:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8671:     return if ($sequence eq '');
 8672:     my $navmap = Apache::lonnavmaps::navmap->new();
 8673:     unless (ref($navmap)) {
 8674:         return;
 8675:     }
 8676:     my $needs_hand_bubbles;
 8677:     my $map=$navmap->getResourceByUrl($sequence);
 8678:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8679:     foreach my $res (@resources) {
 8680:         if (ref($res)) {
 8681:             if ($res->is_problem()) {
 8682:                 my $partlist = $res->parts();
 8683:                 foreach my $part (@{ $partlist }) {
 8684:                     my @types = $res->responseType($part);
 8685:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
 8686:                         $needs_hand_bubbles = 1;
 8687:                         last;
 8688:                     }
 8689:                 }
 8690:             }
 8691:         }
 8692:     }
 8693:     if ($needs_hand_bubbles) {
 8694:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8695:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 8696:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
 8697:                &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 />').
 8698:                '<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;'.
 8699:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
 8700:     }
 8701:     return;
 8702: }
 8703: 
 8704: sub scantron_process_students {
 8705:     my ($r,$symb) = @_;
 8706: 
 8707:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 8708:     if (!$symb) {
 8709: 	return '';
 8710:     }
 8711:     my $default_form_data=&defaultFormData($symb);
 8712: 
 8713:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 8714:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
 8715:     my ($scanlines,$scan_data)=&scantron_getfile();
 8716:     my $classlist=&Apache::loncoursedata::get_classlist();
 8717:     my %idmap=&username_to_idmap($classlist);
 8718:     my $navmap=Apache::lonnavmaps::navmap->new();
 8719:     unless (ref($navmap)) {
 8720:         $r->print(&navmap_errormsg());
 8721:         return '';
 8722:     }
 8723:     my $map=$navmap->getResourceByUrl($sequence);
 8724:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 8725:         %grader_randomlists_by_symb);
 8726:     if (ref($map)) {
 8727:         $randomorder = $map->randomorder();
 8728:         $randompick = $map->randompick();
 8729:     } else {
 8730:         $r->print(&navmap_errormsg());
 8731:         return '';
 8732:     }
 8733:     my $nav_error;
 8734:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8735:     if ($randomorder || $randompick) {
 8736:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 8737:         if ($nav_error) {
 8738:             $r->print(&navmap_errormsg());
 8739:             return '';
 8740:         }
 8741:     }
 8742:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 8743:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 8744: 
 8745:     my ($uname,$udom);
 8746:     my $result= <<SCANTRONFORM;
 8747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 8748:   <input type="hidden" name="command" value="scantron_configphase" />
 8749:   $default_form_data
 8750: SCANTRONFORM
 8751:     $r->print($result);
 8752: 
 8753:     my @delayqueue;
 8754:     my (%completedstudents,%scandata);
 8755:     
 8756:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 8757:     my $count=&get_todo_count($scanlines,$scan_data);
 8758:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 8759:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 8760:     $r->print('<br />');
 8761:     my $start=&Time::HiRes::time();
 8762:     my $i=-1;
 8763:     my $started;
 8764: 
 8765:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 8766:     if ($nav_error) {
 8767:         $r->print(&navmap_errormsg());
 8768:         return '';
 8769:     }
 8770: 
 8771:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 8772:     # the user and return.
 8773: 
 8774:     if ($ssi_error) {
 8775: 	$r->print("</form>");
 8776: 	&ssi_print_error($r);
 8777:         &Apache::lonnet::remove_lock($lock);
 8778: 	return '';		# Dunno why the other returns return '' rather than just returning.
 8779:     }
 8780: 
 8781:     my %lettdig = &letter_to_digits();
 8782:     my $numletts = scalar(keys(%lettdig));
 8783:     my %orderedforcode;
 8784: 
 8785:     while ($i<$scanlines->{'count'}) {
 8786:  	($uname,$udom)=('','');
 8787:  	$i++;
 8788:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 8789:  	if ($line=~/^[\s\cz]*$/) { next; }
 8790: 	if ($started) {
 8791: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 8792: 	}
 8793: 	$started=1;
 8794:         my %respnumlookup = ();
 8795:         my %startline = ();
 8796:         my $total;
 8797:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 8798:                                                  $scan_data,undef,\%idmap,$randomorder,
 8799:                                                  $randompick,$sequence,\@master_seq,
 8800:                                                  \%symb_to_resource,\%grader_partids_by_symb,
 8801:                                                  \%orderedforcode,\%respnumlookup,\%startline,
 8802:                                                  \$total);
 8803:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 8804:  					      \%idmap,$i)) {
 8805:   	    &scantron_add_delay(\@delayqueue,$line,
 8806:  				'Unable to find a student that matches',1);
 8807:  	    next;
 8808:   	}
 8809:  	if (exists $completedstudents{$uname}) {
 8810:  	    &scantron_add_delay(\@delayqueue,$line,
 8811:  				'Student '.$uname.' has multiple sheets',2);
 8812:  	    next;
 8813:  	}
 8814:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 8815:         my $user = $uname.':'.$usec;
 8816:   	($uname,$udom)=split(/:/,$uname);
 8817: 
 8818:         my $scancode;
 8819:         if ((exists($scan_record->{'scantron.CODE'})) &&
 8820:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 8821:             $scancode = $scan_record->{'scantron.CODE'};
 8822:         } else {
 8823:             $scancode = '';
 8824:         }
 8825: 
 8826:         my @mapresources = @resources;
 8827:         if ($randomorder || $randompick) {
 8828:             @mapresources = 
 8829:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 8830:                              \%orderedforcode);
 8831:         }
 8832:         my (%partids_by_symb,$res_error);
 8833:         foreach my $resource (@mapresources) {
 8834:             my $ressymb;
 8835:             if (ref($resource)) {
 8836:                 $ressymb = $resource->symb();
 8837:             } else {
 8838:                 $res_error = 1;
 8839:                 last;
 8840:             }
 8841:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8842:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8843:                 my $currcode;
 8844:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 8845:                     $currcode = $scancode;
 8846:                 }
 8847:                 my ($analysis,$parts) =
 8848:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 8849:                                               $uname,$udom,undef,$bubbles_per_row,
 8850:                                               $currcode);
 8851:                 $partids_by_symb{$ressymb} = $parts;
 8852:             } else {
 8853:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 8854:             }
 8855:         }
 8856: 
 8857:         if ($res_error) {
 8858:             &scantron_add_delay(\@delayqueue,$line,
 8859:                                 'An error occurred while grading student '.$uname,2);
 8860:             next;
 8861:         }
 8862: 
 8863: 	&Apache::lonxml::clear_problem_counter();
 8864:   	&Apache::lonnet::appenv($scan_record);
 8865: 
 8866: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 8867: 	    &scantron_putfile($scanlines,$scan_data);
 8868: 	}
 8869: 	
 8870:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8871:                                    \@mapresources,\%partids_by_symb,
 8872:                                    $bubbles_per_row,$randomorder,$randompick,
 8873:                                    \%respnumlookup,\%startline) 
 8874:             eq 'ssi_error') {
 8875:             $ssi_error = 0; # So end of handler error message does not trigger.
 8876:             $r->print("</form>");
 8877:             &ssi_print_error($r);
 8878:             &Apache::lonnet::remove_lock($lock);
 8879:             return '';      # Why return ''?  Beats me.
 8880:         }
 8881: 
 8882:         if (($scancode) && ($randomorder || $randompick)) {
 8883:             my $parmresult =
 8884:                 &Apache::lonparmset::storeparm_by_symb($symb,
 8885:                                                        '0_examcode',2,$scancode,
 8886:                                                        'string_examcode',$uname,
 8887:                                                        $udom);
 8888:         }
 8889: 	$completedstudents{$uname}={'line'=>$line};
 8890:         if ($env{'form.verifyrecord'}) {
 8891:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8892:             if ($randompick) {
 8893:                 if ($total) {
 8894:                     $lastpos = $total*$scantron_config{'Qlength'};
 8895:                 }
 8896:             }
 8897: 
 8898:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8899:             chomp($studentdata);
 8900:             $studentdata =~ s/\r$//;
 8901:             my $studentrecord = '';
 8902:             my $counter = -1;
 8903:             foreach my $resource (@mapresources) {
 8904:                 my $ressymb = $resource->symb();
 8905:                 ($counter,my $recording) =
 8906:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8907:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 8908:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
 8909:                                              $randompick,\%respnumlookup,\%startline);
 8910:                 $studentrecord .= $recording;
 8911:             }
 8912:             if ($studentrecord ne $studentdata) {
 8913:                 &Apache::lonxml::clear_problem_counter();
 8914:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 8915:                                            \@mapresources,\%partids_by_symb,
 8916:                                            $bubbles_per_row,$randomorder,$randompick,
 8917:                                            \%respnumlookup,\%startline) 
 8918:                     eq 'ssi_error') {
 8919:                     $ssi_error = 0; # So end of handler error message does not trigger.
 8920:                     $r->print("</form>");
 8921:                     &ssi_print_error($r);
 8922:                     &Apache::lonnet::remove_lock($lock);
 8923:                     delete($completedstudents{$uname});
 8924:                     return '';
 8925:                 }
 8926:                 $counter = -1;
 8927:                 $studentrecord = '';
 8928:                 foreach my $resource (@mapresources) {
 8929:                     my $ressymb = $resource->symb();
 8930:                     ($counter,my $recording) =
 8931:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 8932:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 8933:                                                  \%scantron_config,\%lettdig,$numletts,
 8934:                                                  $randomorder,$randompick,\%respnumlookup,
 8935:                                                  \%startline);
 8936:                     $studentrecord .= $recording;
 8937:                 }
 8938:                 if ($studentrecord ne $studentdata) {
 8939:                     $r->print('<p><span class="LC_warning">');
 8940:                     if ($scancode eq '') {
 8941:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
 8942:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 8943:                     } else {
 8944:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
 8945:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 8946:                     }
 8947:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 8948:                               &Apache::loncommon::start_data_table_header_row()."\n".
 8949:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 8950:                               &Apache::loncommon::end_data_table_header_row()."\n".
 8951:                               &Apache::loncommon::start_data_table_row().
 8952:                               '<td>'.&mt('Bubblesheet').'</td>'.
 8953:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
 8954:                               &Apache::loncommon::end_data_table_row().
 8955:                               &Apache::loncommon::start_data_table_row().
 8956:                               '<td>'.&mt('Stored submissions').'</td>'.
 8957:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
 8958:                               &Apache::loncommon::end_data_table_row().
 8959:                               &Apache::loncommon::end_data_table().'</p>');
 8960:                 } else {
 8961:                     $r->print('<br /><span class="LC_warning">'.
 8962:                              &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 />'.
 8963:                              &mt("As a consequence, this user's submission history records two tries.").
 8964:                                  '</span><br />');
 8965:                 }
 8966:             }
 8967:         }
 8968:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 8969:     } continue {
 8970: 	&Apache::lonxml::clear_problem_counter();
 8971: 	&Apache::lonnet::delenv('scantron.');
 8972:     }
 8973:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8974:     &Apache::lonnet::remove_lock($lock);
 8975: #    my $lasttime = &Time::HiRes::time()-$start;
 8976: #    $r->print("<p>took $lasttime</p>");
 8977: 
 8978:     $r->print("</form>");
 8979:     return '';
 8980: }
 8981: 
 8982: sub graders_resources_pass {
 8983:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
 8984:         $bubbles_per_row) = @_;
 8985:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 8986:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 8987:         foreach my $resource (@{$resources}) {
 8988:             my $ressymb = $resource->symb();
 8989:             my ($analysis,$parts) =
 8990:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 8991:                                           $env{'user.name'},$env{'user.domain'},
 8992:                                           1,$bubbles_per_row);
 8993:             $grader_partids_by_symb->{$ressymb} = $parts;
 8994:             if (ref($analysis) eq 'HASH') {
 8995:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 8996:                     $grader_randomlists_by_symb->{$ressymb} =
 8997:                         $analysis->{'parts_withrandomlist'};
 8998:                 }
 8999:             }
 9000:         }
 9001:     }
 9002:     return;
 9003: }
 9004: 
 9005: =pod
 9006: 
 9007: =item users_order
 9008: 
 9009:   Returns array of resources in current map, ordered based on either CODE,
 9010:   if this is a CODEd exam, or based on student's identity if this is a 
 9011:   "NAMEd" exam.
 9012: 
 9013:   Should be used when randomorder and/or randompick applied when the 
 9014:   corresponding exam was printed, prior to students completing bubblesheets 
 9015:   for the version of the exam the student received.
 9016: 
 9017: =cut
 9018: 
 9019: sub users_order  {
 9020:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
 9021:     my @mapresources;
 9022:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
 9023:         return @mapresources;
 9024:     }
 9025:     if ($scancode) {
 9026:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
 9027:             @mapresources = @{$orderedforcode->{$scancode}};
 9028:         } else {
 9029:             $env{'form.CODE'} = $scancode;
 9030:             my $actual_seq =
 9031:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9032:                                                                $master_seq,
 9033:                                                                $user,$scancode,1);
 9034:             if (ref($actual_seq) eq 'ARRAY') {
 9035:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
 9036:                 if (ref($orderedforcode) eq 'HASH') {
 9037:                     if (@mapresources > 0) { 
 9038:                         $orderedforcode->{$scancode} = \@mapresources;
 9039:                     }
 9040:                 }
 9041:             }
 9042:             delete($env{'form.CODE'});
 9043:         }
 9044:     } else {
 9045:         my $actual_seq =
 9046:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
 9047:                                                            $master_seq,
 9048:                                                            $user,undef,1);
 9049:         if (ref($actual_seq) eq 'ARRAY') {
 9050:             @mapresources = 
 9051:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
 9052:         }
 9053:     }
 9054:     return @mapresources;
 9055: }
 9056: 
 9057: sub grade_student_bubbles {
 9058:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
 9059:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
 9060:     my $uselookup = 0;
 9061:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
 9062:         (ref($startline) eq 'HASH')) {
 9063:         $uselookup = 1;
 9064:     }
 9065: 
 9066:     if (ref($resources) eq 'ARRAY') {
 9067:         my $count = 0;
 9068:         foreach my $resource (@{$resources}) {
 9069:             my $ressymb = $resource->symb();
 9070:             my %form = ('submitted'      => 'scantron',
 9071:                         'grade_target'   => 'grade',
 9072:                         'grade_username' => $uname,
 9073:                         'grade_domain'   => $udom,
 9074:                         'grade_courseid' => $env{'request.course.id'},
 9075:                         'grade_symb'     => $ressymb,
 9076:                         'CODE'           => $scancode
 9077:                        );
 9078:             if ($bubbles_per_row ne '') {
 9079:                 $form{'bubbles_per_row'} = $bubbles_per_row;
 9080:             }
 9081:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
 9082:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
 9083:             }
 9084:             if (ref($parts) eq 'HASH') {
 9085:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 9086:                     foreach my $part (@{$parts->{$ressymb}}) {
 9087:                         if ($uselookup) {
 9088:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
 9089:                         } else {
 9090:                             $form{'scantron_questnum_start.'.$part} =
 9091:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
 9092:                         }
 9093:                         $count++;
 9094:                     }
 9095:                 }
 9096:             }
 9097:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 9098:             return 'ssi_error' if ($ssi_error);
 9099:             last if (&Apache::loncommon::connection_aborted($r));
 9100:         }
 9101:     }
 9102:     return;
 9103: }
 9104: 
 9105: sub scantron_upload_scantron_data {
 9106:     my ($r,$symb)=@_;
 9107:     my $dom = $env{'request.role.domain'};
 9108:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 9109:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 9110:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 9111: 							  'domainid',
 9112: 							  'coursename',$dom);
 9113:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 9114:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 9115:     my $default_form_data=&defaultFormData($symb);
 9116:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 9117:     &js_escape(\$nofile_alert);
 9118:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
 9119:     &js_escape(\$nocourseid_alert);
 9120:     $r->print(&Apache::lonhtmlcommon::scripttag('
 9121:     function checkUpload(formname) {
 9122: 	if (formname.upfile.value == "") {
 9123: 	    alert("'.$nofile_alert.'");
 9124: 	    return false;
 9125: 	}
 9126:         if (formname.courseid.value == "") {
 9127:             alert("'.$nocourseid_alert.'");
 9128:             return false;
 9129:         }
 9130: 	formname.submit();
 9131:     }
 9132: 
 9133:     function ToSyllabus() {
 9134:         var cdom = '."'$dom'".';
 9135:         var cnum = document.rules.courseid.value;
 9136:         if (cdom == "" || cdom == null) {
 9137:             return;
 9138:         }
 9139:         if (cnum == "" || cnum == null) {
 9140:            return;
 9141:         }
 9142:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 9143:                             "height=350,width=350,scrollbars=yes,menubar=no");
 9144:         return;
 9145:     }
 9146: 
 9147: '));
 9148:     $r->print('
 9149: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
 9150: 
 9151: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 9152: '.$default_form_data.
 9153:   &Apache::lonhtmlcommon::start_pick_box().
 9154:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 9155:   '<input name="courseid" type="text" size="30" />'.$select_link.
 9156:   &Apache::lonhtmlcommon::row_closure().
 9157:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 9158:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 9159:   &Apache::lonhtmlcommon::row_closure().
 9160:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 9161:   '<input name="domainid" type="hidden" />'.$domdesc.
 9162:   &Apache::lonhtmlcommon::row_closure().
 9163:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 9164:   '<input type="file" name="upfile" size="50" />'.
 9165:   &Apache::lonhtmlcommon::row_closure(1).
 9166:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 9167: 
 9168: <input name="command" value="scantronupload_save" type="hidden" />
 9169: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 9170: </form>
 9171: ');
 9172:     return '';
 9173: }
 9174: 
 9175: 
 9176: sub scantron_upload_scantron_data_save {
 9177:     my($r,$symb)=@_;
 9178:     my $doanotherupload=
 9179: 	'<br /><form action="/adm/grades" method="post">'."\n".
 9180: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 9181: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 9182: 	'</form>'."\n";
 9183:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 9184: 	!&Apache::lonnet::allowed('usc',
 9185: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 9186: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 9187: 	unless ($symb) {
 9188: 	    $r->print($doanotherupload);
 9189: 	}
 9190: 	return '';
 9191:     }
 9192:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 9193:     my $uploadedfile;
 9194:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
 9195:     if (length($env{'form.upfile'}) < 2) {
 9196:         $r->print(
 9197:             &Apache::lonhtmlcommon::confirm_success(
 9198:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
 9199:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
 9200:     } else {
 9201:         my $result = 
 9202:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 9203:                                             $env{'form.courseid'},$env{'form.domainid'});
 9204:         if ($result =~ m{^/uploaded/}) {
 9205:             $r->print(
 9206:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
 9207:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
 9208:                         (length($env{'form.upfile'})-1),
 9209:                         '<span class="LC_filename">'.$result.'</span>'));
 9210:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 9211:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 9212:                                                        $env{'form.courseid'},$uploadedfile));
 9213:         } else {
 9214:             $r->print(
 9215:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
 9216:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
 9217:                           $result,
 9218: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 9219: 	}
 9220:     }
 9221:     if ($symb) {
 9222: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
 9223:     } else {
 9224: 	$r->print($doanotherupload);
 9225:     }
 9226:     return '';
 9227: }
 9228: 
 9229: sub validate_uploaded_scantron_file {
 9230:     my ($cdom,$cname,$fname) = @_;
 9231:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 9232:     my @lines;
 9233:     if ($scanlines ne '-1') {
 9234:         @lines=split("\n",$scanlines,-1);
 9235:     }
 9236:     my $output;
 9237:     if (@lines) {
 9238:         my (%counts,$max_match_format);
 9239:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
 9240:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 9241:         my %idmap = &username_to_idmap($classlist);
 9242:         foreach my $key (keys(%idmap)) {
 9243:             my $lckey = lc($key);
 9244:             $idmap{$lckey} = $idmap{$key};
 9245:         }
 9246:         my %unique_formats;
 9247:         my @formatlines = &get_scantronformat_file();
 9248:         foreach my $line (@formatlines) {
 9249:             chomp($line);
 9250:             my @config = split(/:/,$line);
 9251:             my $idstart = $config[5];
 9252:             my $idlength = $config[6];
 9253:             if (($idstart ne '') && ($idlength > 0)) {
 9254:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 9255:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 9256:                 } else {
 9257:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 9258:                 }
 9259:             }
 9260:         }
 9261:         foreach my $key (keys(%unique_formats)) {
 9262:             my ($idstart,$idlength) = split(':',$key);
 9263:             %{$counts{$key}} = (
 9264:                                'found'   => 0,
 9265:                                'total'   => 0,
 9266:                               );
 9267:             foreach my $line (@lines) {
 9268:                 next if ($line =~ /^#/);
 9269:                 next if ($line =~ /^[\s\cz]*$/);
 9270:                 my $id = substr($line,$idstart-1,$idlength);
 9271:                 $id = lc($id);
 9272:                 if (exists($idmap{$id})) {
 9273:                     $counts{$key}{'found'} ++;
 9274:                 }
 9275:                 $counts{$key}{'total'} ++;
 9276:             }
 9277:             if ($counts{$key}{'total'}) {
 9278:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 9279:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 9280:                     $max_match_pct = $percent_match;
 9281:                     $max_match_format = $key;
 9282:                     $found_match_count = $counts{$key}{'found'};
 9283:                     $max_match_count = $counts{$key}{'total'};
 9284:                 }
 9285:             }
 9286:         }
 9287:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 9288:             my $format_descs;
 9289:             my $numwithformat = @{$unique_formats{$max_match_format}};
 9290:             for (my $i=0; $i<$numwithformat; $i++) {
 9291:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 9292:                 if ($i<$numwithformat-2) {
 9293:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 9294:                 } elsif ($i==$numwithformat-2) {
 9295:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 9296:                 } elsif ($i==$numwithformat-1) {
 9297:                     $format_descs .= '"<i>'.$desc.'</i>"';
 9298:                 }
 9299:             }
 9300:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 9301:             $output .= '<br />';
 9302:             if ($found_match_count == $max_match_count) {
 9303:                 # 100% matching entries
 9304:                 $output .= &Apache::lonhtmlcommon::confirm_success(
 9305:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
 9306:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
 9307:                 &mt('Comparison of student IDs in the uploaded file with'.
 9308:                     ' the course roster found matches for [_1] of the [_2] entries'.
 9309:                     ' in the file (for the format defined for [_3]).',
 9310:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
 9311:             } else {
 9312:                 # Not all entries matching? -> Show warning and additional info
 9313:                 $output .=
 9314:                     &Apache::lonhtmlcommon::confirm_success(
 9315:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
 9316:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
 9317:                         &mt('Not all entries could be matched!'),1).'<br />'.
 9318:                     &mt('Comparison of student IDs in the uploaded file with'.
 9319:                         ' the course roster found matches for [_1] of the [_2] entries'.
 9320:                         ' in the file (for the format defined for [_3]).',
 9321:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 9322:                     '<p class="LC_info">'.
 9323:                     &mt('A low percentage of matches results from one of the following:').
 9324:                     '</p><ul>'.
 9325:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
 9326:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
 9327:                                '<i>'.$cdom.'</i>').'</li>'.
 9328:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 9329:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
 9330:                     '</ul>';
 9331:             }
 9332:         }
 9333:     } else {
 9334:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
 9335:     }
 9336:     return $output;
 9337: }
 9338: 
 9339: sub valid_file {
 9340:     my ($requested_file)=@_;
 9341:     foreach my $filename (sort(&scantron_filenames())) {
 9342: 	if ($requested_file eq $filename) { return 1; }
 9343:     }
 9344:     return 0;
 9345: }
 9346: 
 9347: sub scantron_download_scantron_data {
 9348:     my ($r,$symb)=@_;
 9349:     my $default_form_data=&defaultFormData($symb);
 9350:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9351:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9352:     my $file=$env{'form.scantron_selectfile'};
 9353:     if (! &valid_file($file)) {
 9354: 	$r->print('
 9355: 	<p>
 9356: 	    '.&mt('The requested filename was invalid.').'
 9357:         </p>
 9358: ');
 9359: 	return;
 9360:     }
 9361:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 9362:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 9363:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 9364:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 9365:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 9366:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 9367:     $r->print('
 9368:     <p>
 9369: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
 9370: 	      '<a href="'.$orig.'">','</a>').'
 9371:     </p>
 9372:     <p>
 9373: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 9374: 	      '<a href="'.$corrected.'">','</a>').'
 9375:     </p>
 9376:     <p>
 9377: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 9378: 	      '<a href="'.$skipped.'">','</a>').'
 9379:     </p>
 9380: ');
 9381:     return '';
 9382: }
 9383: 
 9384: sub checkscantron_results {
 9385:     my ($r,$symb) = @_;
 9386:     if (!$symb) {return '';}
 9387:     my $cid = $env{'request.course.id'};
 9388:     my %lettdig = &letter_to_digits();
 9389:     my $numletts = scalar(keys(%lettdig));
 9390:     my $cnum = $env{'course.'.$cid.'.num'};
 9391:     my $cdom = $env{'course.'.$cid.'.domain'};
 9392:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 9393:     my %record;
 9394:     my %scantron_config =
 9395:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 9396:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
 9397:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 9398:     my $classlist=&Apache::loncoursedata::get_classlist();
 9399:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 9400:     my $navmap=Apache::lonnavmaps::navmap->new();
 9401:     unless (ref($navmap)) {
 9402:         $r->print(&navmap_errormsg());
 9403:         return '';
 9404:     }
 9405:     my $map=$navmap->getResourceByUrl($sequence);
 9406:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
 9407:         %grader_randomlists_by_symb,%orderedforcode);
 9408:     if (ref($map)) { 
 9409:         $randomorder=$map->randomorder();
 9410:         $randompick=$map->randompick();
 9411:     }
 9412:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 9413:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
 9414:     if ($nav_error) {
 9415:         $r->print(&navmap_errormsg());
 9416:         return '';
 9417:     }
 9418:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 9419:                             \%grader_randomlists_by_symb,$bubbles_per_row);
 9420:     my ($uname,$udom);
 9421:     my (%scandata,%lastname,%bylast);
 9422:     $r->print('
 9423: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 9424: 
 9425:     my @delayqueue;
 9426:     my %completedstudents;
 9427: 
 9428:     my $count=&get_todo_count($scanlines,$scan_data);
 9429:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
 9430:     my ($username,$domain,$started);
 9431:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
 9432:     if ($nav_error) {
 9433:         $r->print(&navmap_errormsg());
 9434:         return '';
 9435:     }
 9436: 
 9437:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
 9438:     my $start=&Time::HiRes::time();
 9439:     my $i=-1;
 9440: 
 9441:     while ($i<$scanlines->{'count'}) {
 9442:         ($username,$domain,$uname)=('','','');
 9443:         $i++;
 9444:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 9445:         if ($line=~/^[\s\cz]*$/) { next; }
 9446:         if ($started) {
 9447:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 9448:         }
 9449:         $started=1;
 9450:         my $scan_record=
 9451:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 9452:                                                      $scan_data);
 9453:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
 9454:                                               \%idmap,$i)) {
 9455:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9456:                                 'Unable to find a student that matches',1);
 9457:             next;
 9458:         }
 9459:         if (exists $completedstudents{$uname}) {
 9460:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 9461:                                 'Student '.$uname.' has multiple sheets',2);
 9462:             next;
 9463:         }
 9464:         my $pid = $scan_record->{'scantron.ID'};
 9465:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 9466:         push(@{$bylast{$lastname{$pid}}},$pid);
 9467:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
 9468:         my $user = $uname.':'.$usec;
 9469:         ($username,$domain)=split(/:/,$uname);
 9470: 
 9471:         my $scancode;
 9472:         if ((exists($scan_record->{'scantron.CODE'})) &&
 9473:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 9474:             $scancode = $scan_record->{'scantron.CODE'};
 9475:         } else {
 9476:             $scancode = '';
 9477:         }
 9478: 
 9479:         my @mapresources = @resources;
 9480:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 9481:         my %respnumlookup=();
 9482:         my %startline=();
 9483:         if ($randomorder || $randompick) {
 9484:             @mapresources =
 9485:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
 9486:                              \%orderedforcode);
 9487:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
 9488:                                              $scan_record,\@master_seq,\%symb_to_resource,
 9489:                                              \%grader_partids_by_symb,\%orderedforcode,
 9490:                                              \%respnumlookup,\%startline);
 9491:             if ($randompick && $total) {
 9492:                 $lastpos = $total*$scantron_config{'Qlength'};
 9493:             }
 9494:         }
 9495:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 9496:         chomp($scandata{$pid});
 9497:         $scandata{$pid} =~ s/\r$//;
 9498: 
 9499:         my $counter = -1;
 9500:         foreach my $resource (@mapresources) {
 9501:             my $parts;
 9502:             my $ressymb = $resource->symb();
 9503:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 9504:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 9505:                 my $currcode;
 9506:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
 9507:                     $currcode = $scancode;
 9508:                 }
 9509:                 (my $analysis,$parts) =
 9510:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
 9511:                                               $username,$domain,undef,
 9512:                                               $bubbles_per_row,$currcode);
 9513:             } else {
 9514:                 $parts = $grader_partids_by_symb{$ressymb};
 9515:             }
 9516:             ($counter,my $recording) =
 9517:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 9518:                                          $scandata{$pid},$parts,
 9519:                                          \%scantron_config,\%lettdig,$numletts,
 9520:                                          $randomorder,$randompick,
 9521:                                          \%respnumlookup,\%startline);
 9522:             $record{$pid} .= $recording;
 9523:         }
 9524:     }
 9525:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 9526:     $r->print('<br />');
 9527:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 9528:     $passed = 0;
 9529:     $failed = 0;
 9530:     $numstudents = 0;
 9531:     foreach my $last (sort(keys(%bylast))) {
 9532:         if (ref($bylast{$last}) eq 'ARRAY') {
 9533:             foreach my $pid (sort(@{$bylast{$last}})) {
 9534:                 my $showscandata = $scandata{$pid};
 9535:                 my $showrecord = $record{$pid};
 9536:                 $showscandata =~ s/\s/&nbsp;/g;
 9537:                 $showrecord =~ s/\s/&nbsp;/g;
 9538:                 if ($scandata{$pid} eq $record{$pid}) {
 9539:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 9540:                     $okstudents .= '<tr class="'.$css_class.'">'.
 9541: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 9542: '</tr>'."\n".
 9543: '<tr class="'.$css_class.'">'."\n".
 9544: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
 9545:                     $passed ++;
 9546:                 } else {
 9547:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 9548:                     $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".
 9549: '</tr>'."\n".
 9550: '<tr class="'.$css_class.'">'."\n".
 9551: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 9552: '</tr>'."\n";
 9553:                     $failed ++;
 9554:                 }
 9555:                 $numstudents ++;
 9556:             }
 9557:         }
 9558:     }
 9559:     $r->print(
 9560:         '<p>'
 9561:        .&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).',
 9562:             '<b>',
 9563:             $numstudents,
 9564:             '</b>',
 9565:             $env{'form.scantron_maxbubble'})
 9566:        .'</p>'
 9567:     );
 9568:     $r->print('<p>'
 9569:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
 9570:              .'<br />'
 9571:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
 9572:              .'</p>'
 9573:     );
 9574:     if ($passed) {
 9575:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 9576:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9577:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9578:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9579:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9580:                  $okstudents."\n".
 9581:                  &Apache::loncommon::end_data_table().'<br />');
 9582:     }
 9583:     if ($failed) {
 9584:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 9585:         $r->print(&Apache::loncommon::start_data_table()."\n".
 9586:                  &Apache::loncommon::start_data_table_header_row()."\n".
 9587:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 9588:                  &Apache::loncommon::end_data_table_header_row()."\n".
 9589:                  $badstudents."\n".
 9590:                  &Apache::loncommon::end_data_table()).'<br />'.
 9591:                  &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.');  
 9592:     }
 9593:     $r->print('</form><br />');
 9594:     return;
 9595: }
 9596: 
 9597: sub verify_scantron_grading {
 9598:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 9599:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
 9600:         $respnumlookup,$startline) = @_;
 9601:     my ($record,%expected,%startpos);
 9602:     return ($counter,$record) if (!ref($resource));
 9603:     return ($counter,$record) if (!$resource->is_problem());
 9604:     my $symb = $resource->symb();
 9605:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 9606:     foreach my $part_id (@{$partids}) {
 9607:         $counter ++;
 9608:         $expected{$part_id} = 0;
 9609:         my $respnum = $counter;
 9610:         if ($randomorder || $randompick) {
 9611:             $respnum = $respnumlookup->{$counter};
 9612:             $startpos{$part_id} = $startline->{$counter} + 1;
 9613:         } else {
 9614:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 9615:         }
 9616:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
 9617:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
 9618:             foreach my $item (@sub_lines) {
 9619:                 $expected{$part_id} += $item;
 9620:             }
 9621:         } else {
 9622:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
 9623:         }
 9624:     }
 9625:     if ($symb) {
 9626:         my %recorded;
 9627:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 9628:         if ($returnhash{'version'}) {
 9629:             my %lasthash=();
 9630:             my $version;
 9631:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 9632:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 9633:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 9634:                 }
 9635:             }
 9636:             foreach my $key (keys(%lasthash)) {
 9637:                 if ($key =~ /\.scantron$/) {
 9638:                     my $value = &unescape($lasthash{$key});
 9639:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 9640:                     if ($value eq '') {
 9641:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 9642:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 9643:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9644:                             }
 9645:                         }
 9646:                     } else {
 9647:                         my @tocheck;
 9648:                         my @items = split(//,$value);
 9649:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 9650:                             ($scantron_config->{'Qon'} eq 'number')) {
 9651:                             if (@items < $expected{$part_id}) {
 9652:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 9653:                                 my @singles = split(//,$fragment);
 9654:                                 foreach my $pos (@singles) {
 9655:                                     if ($pos eq ' ') {
 9656:                                         push(@tocheck,$pos);
 9657:                                     } else {
 9658:                                         my $next = shift(@items);
 9659:                                         push(@tocheck,$next);
 9660:                                     }
 9661:                                 }
 9662:                             } else {
 9663:                                 @tocheck = @items;
 9664:                             }
 9665:                             foreach my $letter (@tocheck) {
 9666:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 9667:                                     if ($letter !~ /^[A-J]$/) {
 9668:                                         $letter = $scantron_config->{'Qoff'};
 9669:                                     }
 9670:                                     $recorded{$part_id} .= $letter;
 9671:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 9672:                                     my $digit;
 9673:                                     if ($letter !~ /^[A-J]$/) {
 9674:                                         $digit = $scantron_config->{'Qoff'};
 9675:                                     } else {
 9676:                                         $digit = $lettdig->{$letter};
 9677:                                     }
 9678:                                     $recorded{$part_id} .= $digit;
 9679:                                 }
 9680:                             }
 9681:                         } else {
 9682:                             @tocheck = @items;
 9683:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 9684:                                 my $curr_sub = shift(@tocheck);
 9685:                                 my $digit;
 9686:                                 if ($curr_sub =~ /^[A-J]$/) {
 9687:                                     $digit = $lettdig->{$curr_sub}-1;
 9688:                                 }
 9689:                                 if ($curr_sub eq 'J') {
 9690:                                     $digit += scalar($numletts);
 9691:                                 }
 9692:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9693:                                     if ($j == $digit) {
 9694:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 9695:                                     } else {
 9696:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9697:                                     }
 9698:                                 }
 9699:                             }
 9700:                         }
 9701:                     }
 9702:                 }
 9703:             }
 9704:         }
 9705:         foreach my $part_id (@{$partids}) {
 9706:             if ($recorded{$part_id} eq '') {
 9707:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 9708:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 9709:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 9710:                     }
 9711:                 }
 9712:             }
 9713:             $record .= $recorded{$part_id};
 9714:         }
 9715:     }
 9716:     return ($counter,$record);
 9717: }
 9718: 
 9719: sub letter_to_digits {
 9720:     my %lettdig = (
 9721:                     A => 1,
 9722:                     B => 2,
 9723:                     C => 3,
 9724:                     D => 4,
 9725:                     E => 5,
 9726:                     F => 6,
 9727:                     G => 7,
 9728:                     H => 8,
 9729:                     I => 9,
 9730:                     J => 0,
 9731:                   );
 9732:     return %lettdig;
 9733: }
 9734: 
 9735: 
 9736: #-------- end of section for handling grading scantron forms -------
 9737: #
 9738: #-------------------------------------------------------------------
 9739: 
 9740: #-------------------------- Menu interface -------------------------
 9741: #
 9742: #--- Href with symb and command ---
 9743: 
 9744: sub href_symb_cmd {
 9745:     my ($symb,$cmd)=@_;
 9746:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
 9747: }
 9748: 
 9749: sub grading_menu {
 9750:     my ($request,$symb) = @_;
 9751:     if (!$symb) {return '';}
 9752: 
 9753:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 9754:                   'command'=>'individual');
 9755:     
 9756:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9757: 
 9758:     $fields{'command'}='ungraded';
 9759:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9760: 
 9761:     $fields{'command'}='table';
 9762:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9763: 
 9764:     $fields{'command'}='all_for_one';
 9765:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9766: 
 9767:     $fields{'command'}='downloadfilesselect';
 9768:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9769: 
 9770:     $fields{'command'} = 'csvform';
 9771:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9772:     
 9773:     $fields{'command'} = 'processclicker';
 9774:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9775:     
 9776:     $fields{'command'} = 'scantron_selectphase';
 9777:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9778: 
 9779:     $fields{'command'} = 'initialverifyreceipt';
 9780:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 9781:     
 9782:     my @menu = ({	categorytitle=>'Hand Grading',
 9783:             items =>[
 9784:                         {	linktext => 'Select individual students to grade',
 9785:                     		url => $url1a,
 9786:                     		permission => 'F',
 9787:                     		icon => 'grade_students.png',
 9788:                     		linktitle => 'Grade current resource for a selection of students.'
 9789:                         }, 
 9790:                         {       linktext => 'Grade ungraded submissions.',
 9791:                                 url => $url1b,
 9792:                                 permission => 'F',
 9793:                                 icon => 'ungrade_sub.png',
 9794:                                 linktitle => 'Grade all submissions that have not been graded yet.'
 9795:                         },
 9796: 
 9797:                         {       linktext => 'Grading table',
 9798:                                 url => $url1c,
 9799:                                 permission => 'F',
 9800:                                 icon => 'grading_table.png',
 9801:                                 linktitle => 'Grade current resource for all students.'
 9802:                         },
 9803:                         {       linktext => 'Grade page/folder for one student',
 9804:                                 url => $url1d,
 9805:                                 permission => 'F',
 9806:                                 icon => 'grade_PageFolder.png',
 9807:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
 9808:                         },
 9809:                         {       linktext => 'Download submissions',
 9810:                                 url => $url1e,
 9811:                                 permission => 'F',
 9812:                                 icon => 'download_sub.png',
 9813:                                 linktitle => 'Download all students submissions.'
 9814:                         }]},
 9815:                          { categorytitle=>'Automated Grading',
 9816:                items =>[
 9817: 
 9818:                 	    {	linktext => 'Upload Scores',
 9819:                     		url => $url2,
 9820:                     		permission => 'F',
 9821:                     		icon => 'uploadscores.png',
 9822:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 9823:                 	    },
 9824:                 	    {	linktext => 'Process Clicker',
 9825:                     		url => $url3,
 9826:                     		permission => 'F',
 9827:                     		icon => 'addClickerInfoFile.png',
 9828:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 9829:                 	    },
 9830:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 9831:                     		url => $url4,
 9832:                     		permission => 'F',
 9833:                     		icon => 'bubblesheet.png',
 9834:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
 9835:                 	    },
 9836:                             {   linktext => 'Verify Receipt Number',
 9837:                                 url => $url5,
 9838:                                 permission => 'F',
 9839:                                 icon => 'receipt_number.png',
 9840:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
 9841:                             }
 9842: 
 9843:                     ]
 9844:             });
 9845: 
 9846:     # Create the menu
 9847:     my $Str;
 9848:     $Str .= '<form method="post" action="" name="gradingMenu">';
 9849:     $Str .= '<input type="hidden" name="command" value="" />'.
 9850:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9851: 
 9852:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
 9853:     return $Str;    
 9854: }
 9855: 
 9856: 
 9857: sub ungraded {
 9858:     my ($request)=@_;
 9859:     &submit_options($request);
 9860: }
 9861: 
 9862: sub submit_options_sequence {
 9863:     my ($request,$symb) = @_;
 9864:     if (!$symb) {return '';}
 9865:     &commonJSfunctions($request);
 9866:     my $result;
 9867: 
 9868:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9869:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9870:     $result.=&selectfield(0).
 9871:             '<input type="hidden" name="command" value="pickStudentPage" />
 9872:             <div>
 9873:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9874:             </div>
 9875:         </div>
 9876:   </form>';
 9877:     return $result;
 9878: }
 9879: 
 9880: sub submit_options_table {
 9881:     my ($request,$symb) = @_;
 9882:     if (!$symb) {return '';}
 9883:     &commonJSfunctions($request);
 9884:     my $is_tool = ($symb =~ /ext\.tool$/);
 9885:     my $result;
 9886: 
 9887:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9888:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9889: 
 9890:     $result.=&selectfield(1,$is_tool).
 9891:             '<input type="hidden" name="command" value="viewgrades" />
 9892:             <div>
 9893:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9894:             </div>
 9895:         </div>
 9896:   </form>';
 9897:     return $result;
 9898: }
 9899: 
 9900: sub submit_options_download {
 9901:     my ($request,$symb) = @_;
 9902:     if (!$symb) {return '';}
 9903: 
 9904:     my $is_tool = ($symb =~ /ext\.tool$/);
 9905:     &commonJSfunctions($request);
 9906: 
 9907:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9908:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9909:     $result.='
 9910: <h2>
 9911:   '.&mt('Select Students for whom to Download Submissions').'
 9912: </h2>'.&selectfield(1,$is_tool).'
 9913:                 <input type="hidden" name="command" value="downloadfileslink" /> 
 9914:               <input type="submit" value="'.&mt('Next').' &rarr;" />
 9915:             </div>
 9916:           </div>
 9917: 
 9918: 
 9919:   </form>';
 9920:     return $result;
 9921: }
 9922: 
 9923: #--- Displays the submissions first page -------
 9924: sub submit_options {
 9925:     my ($request,$symb) = @_;
 9926:     if (!$symb) {return '';}
 9927: 
 9928:     my $is_tool = ($symb =~ /ext\.tool$/);
 9929:     &commonJSfunctions($request);
 9930:     my $result;
 9931: 
 9932:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 9933: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
 9934:     $result.=&selectfield(1,$is_tool).'
 9935:                 <input type="hidden" name="command" value="submission" /> 
 9936: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
 9937:             </div>
 9938:           </div>
 9939: 
 9940: 
 9941:   </form>';
 9942:     return $result;
 9943: }
 9944: 
 9945: sub selectfield {
 9946:    my ($full,$is_tool)=@_;
 9947:    my %options;
 9948:    if ($is_tool) {
 9949:        %options =
 9950:            (&transtatus_options,
 9951:             'select_form_order' => ['yes','incorrect','all']);
 9952:    } else {
 9953:        %options = 
 9954:            (&substatus_options,
 9955:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
 9956:    }
 9957:    my $result='<div class="LC_columnSection">
 9958:   
 9959:     <fieldset>
 9960:       <legend>
 9961:        '.&mt('Sections').'
 9962:       </legend>
 9963:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
 9964:     </fieldset>
 9965:   
 9966:     <fieldset>
 9967:       <legend>
 9968:         '.&mt('Groups').'
 9969:       </legend>
 9970:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 9971:     </fieldset>
 9972:   
 9973:     <fieldset>
 9974:       <legend>
 9975:         '.&mt('Access Status').'
 9976:       </legend>
 9977:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
 9978:     </fieldset>';
 9979:     if ($full) {
 9980:         my $heading = &mt('Submission Status');
 9981:         if ($is_tool) {
 9982:             $heading = &mt('Transaction Status');
 9983:         }
 9984:         $result.='
 9985:     <fieldset>
 9986:       <legend>
 9987:         '.$heading.'
 9988:       </legend>'.
 9989:        &Apache::loncommon::select_form('all','submitonly',\%options).
 9990:    '</fieldset>';
 9991:     }
 9992:     $result.='</div><br />';
 9993:     return $result;
 9994: }
 9995: 
 9996: sub substatus_options {
 9997:     return &Apache::lonlocal::texthash(
 9998:                                       'yes'       => 'with submissions',
 9999:                                       'queued'    => 'in grading queue',
10000:                                       'graded'    => 'with ungraded submissions',
10001:                                       'incorrect' => 'with incorrect submissions',
10002:                                       'all'       => 'with any status',
10003:                                       );
10004: }
10005: 
10006: sub transtatus_options {
10007:     return &Apache::lonlocal::texthash(
10008:                                        'yes'       => 'with score transactions',
10009:                                        'incorrect' => 'with less than full credit',
10010:                                        'all'       => 'with any status',
10011:                                       );
10012: }
10013: 
10014: sub reset_perm {
10015:     undef(%perm);
10016: }
10017: 
10018: sub init_perm {
10019:     &reset_perm();
10020:     foreach my $test_perm ('vgr','mgr','opa') {
10021: 
10022: 	my $scope = $env{'request.course.id'};
10023: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10024: 
10025: 	    $scope .= '/'.$env{'request.course.sec'};
10026: 	    if ( $perm{$test_perm}=
10027: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
10028: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
10029: 	    } else {
10030: 		delete($perm{$test_perm});
10031: 	    }
10032: 	}
10033:     }
10034: }
10035: 
10036: sub init_old_essays {
10037:     my ($symb,$apath,$adom,$aname) = @_;
10038:     if ($symb ne '') {
10039:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10040:         if (keys(%essays) > 0) {
10041:             $old_essays{$symb} = \%essays;
10042:         }
10043:     }
10044:     return;
10045: }
10046: 
10047: sub reset_old_essays {
10048:     undef(%old_essays);
10049: }
10050: 
10051: sub gather_clicker_ids {
10052:     my %clicker_ids;
10053: 
10054:     my $classlist = &Apache::loncoursedata::get_classlist();
10055: 
10056:     # Set up a couple variables.
10057:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
10058:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
10059:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
10060: 
10061:     foreach my $student (keys(%$classlist)) {
10062:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10063:         my $username = $classlist->{$student}->[$username_idx];
10064:         my $domain   = $classlist->{$student}->[$domain_idx];
10065:         my $clickers =
10066: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10067:         foreach my $id (split(/\,/,$clickers)) {
10068:             $id=~s/^[\#0]+//;
10069:             $id=~s/[\-\:]//g;
10070:             if (exists($clicker_ids{$id})) {
10071: 		$clicker_ids{$id}.=','.$username.':'.$domain;
10072:             } else {
10073: 		$clicker_ids{$id}=$username.':'.$domain;
10074:             }
10075:         }
10076:     }
10077:     return %clicker_ids;
10078: }
10079: 
10080: sub gather_adv_clicker_ids {
10081:     my %clicker_ids;
10082:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10083:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10084:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10085:     foreach my $element (sort(keys(%coursepersonnel))) {
10086:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10087:             my ($puname,$pudom)=split(/\:/,$person);
10088:             my $clickers =
10089: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10090:             foreach my $id (split(/\,/,$clickers)) {
10091: 		$id=~s/^[\#0]+//;
10092:                 $id=~s/[\-\:]//g;
10093: 		if (exists($clicker_ids{$id})) {
10094: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
10095: 		} else {
10096: 		    $clicker_ids{$id}=$puname.':'.$pudom;
10097: 		}
10098:             }
10099:         }
10100:     }
10101:     return %clicker_ids;
10102: }
10103: 
10104: sub clicker_grading_parameters {
10105:     return ('gradingmechanism' => 'scalar',
10106:             'upfiletype' => 'scalar',
10107:             'specificid' => 'scalar',
10108:             'pcorrect' => 'scalar',
10109:             'pincorrect' => 'scalar');
10110: }
10111: 
10112: sub process_clicker {
10113:     my ($r,$symb)=@_;
10114:     if (!$symb) {return '';}
10115:     my $result=&checkforfile_js();
10116:     $result.=&Apache::loncommon::start_data_table().
10117:              &Apache::loncommon::start_data_table_header_row().
10118:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10119:              &Apache::loncommon::end_data_table_header_row().
10120:              &Apache::loncommon::start_data_table_row()."<td>\n";
10121: # Attempt to restore parameters from last session, set defaults if not present
10122:     my %Saveable_Parameters=&clicker_grading_parameters();
10123:     &Apache::loncommon::restore_course_settings('grades_clicker',
10124:                                                  \%Saveable_Parameters);
10125:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10126:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10127:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10128:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10129: 
10130:     my %checked;
10131:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10132:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10133:           $checked{$gradingmechanism}=' checked="checked"';
10134:        }
10135:     }
10136: 
10137:     my $upload=&mt("Evaluate File");
10138:     my $type=&mt("Type");
10139:     my $attendance=&mt("Award points just for participation");
10140:     my $personnel=&mt("Correctness determined from response by course personnel");
10141:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
10142:     my $given=&mt("Correctness determined from given list of answers").' '.
10143:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10144:     my $pcorrect=&mt("Percentage points for correct solution");
10145:     my $pincorrect=&mt("Percentage points for incorrect solution");
10146:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10147: 						   {'iclicker' => 'i>clicker',
10148:                                                     'interwrite' => 'interwrite PRS',
10149:                                                     'turning' => 'Turning Technologies'});
10150:     $symb = &Apache::lonenc::check_encrypt($symb);
10151:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10152: function sanitycheck() {
10153: // Accept only integer percentages
10154:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10155:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10156: // Find out grading choice
10157:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10158:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
10159:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10160:       }
10161:    }
10162: // By default, new choice equals user selection
10163:    newgradingchoice=gradingchoice;
10164: // Not good to give more points for false answers than correct ones
10165:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10166:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10167:    }
10168: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10169:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10170:       document.forms.gradesupload.pcorrect.value=100;
10171:       document.forms.gradesupload.pincorrect.value=100;
10172:    }
10173: // If the values are different, cannot be attendance only
10174:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10175:        (gradingchoice=='attendance')) {
10176:        newgradingchoice='personnel';
10177:    }
10178: // Change grading choice to new one
10179:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10180:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10181:          document.forms.gradesupload.gradingmechanism[i].checked=true;
10182:       } else {
10183:          document.forms.gradesupload.gradingmechanism[i].checked=false;
10184:       }
10185:    }
10186: // Remember the old state
10187:    document.forms.gradesupload.waschecked.value=newgradingchoice;
10188: }
10189: ENDUPFORM
10190:     $result.= <<ENDUPFORM;
10191: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10192: <input type="hidden" name="symb" value="$symb" />
10193: <input type="hidden" name="command" value="processclickerfile" />
10194: <input type="file" name="upfile" size="50" />
10195: <br /><label>$type: $selectform</label>
10196: ENDUPFORM
10197:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
10198:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10199:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10200: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10201: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10202: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10203: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10204: <br />&nbsp;&nbsp;&nbsp;
10205: <input type="text" name="givenanswer" size="50" />
10206: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10207: ENDGRADINGFORM
10208:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
10209:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10210:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10211: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10212: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10213: </form>'
10214: ENDPERCFORM
10215:     $result.='</td>'.
10216:              &Apache::loncommon::end_data_table_row().
10217:              &Apache::loncommon::end_data_table();
10218:     return $result;
10219: }
10220: 
10221: sub process_clicker_file {
10222:     my ($r,$symb)=@_;
10223:     if (!$symb) {return '';}
10224: 
10225:     my %Saveable_Parameters=&clicker_grading_parameters();
10226:     &Apache::loncommon::store_course_settings('grades_clicker',
10227:                                               \%Saveable_Parameters);
10228:     my $result='';
10229:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10230: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10231: 	return $result;
10232:     }
10233:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10234:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10235:         return $result;
10236:     }
10237:     my $foundgiven=0;
10238:     if ($env{'form.gradingmechanism'} eq 'given') {
10239:         $env{'form.givenanswer'}=~s/^\s*//gs;
10240:         $env{'form.givenanswer'}=~s/\s*$//gs;
10241:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10242:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10243:         my @answers=split(/\,/,$env{'form.givenanswer'});
10244:         $foundgiven=$#answers+1;
10245:     }
10246:     my %clicker_ids=&gather_clicker_ids();
10247:     my %correct_ids;
10248:     if ($env{'form.gradingmechanism'} eq 'personnel') {
10249: 	%correct_ids=&gather_adv_clicker_ids();
10250:     }
10251:     if ($env{'form.gradingmechanism'} eq 'specific') {
10252: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10253: 	   $correct_id=~tr/a-z/A-Z/;
10254: 	   $correct_id=~s/\s//gs;
10255: 	   $correct_id=~s/^[\#0]+//;
10256:            $correct_id=~s/[\-\:]//g;
10257:            if ($correct_id) {
10258: 	      $correct_ids{$correct_id}='specified';
10259:            }
10260:         }
10261:     }
10262:     if ($env{'form.gradingmechanism'} eq 'attendance') {
10263: 	$result.=&mt('Score based on attendance only');
10264:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
10265:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10266:     } else {
10267: 	my $number=0;
10268: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10269: 	foreach my $id (sort(keys(%correct_ids))) {
10270: 	    $result.='<br /><tt>'.$id.'</tt> - ';
10271: 	    if ($correct_ids{$id} eq 'specified') {
10272: 		$result.=&mt('specified');
10273: 	    } else {
10274: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10275: 		$result.=&Apache::loncommon::plainname($uname,$udom);
10276: 	    }
10277: 	    $number++;
10278: 	}
10279:         $result.="</p>\n";
10280:         if ($number==0) {
10281:             $result .=
10282:                  &Apache::lonhtmlcommon::confirm_success(
10283:                      &mt('No IDs found to determine correct answer'),1);
10284:             return $result;
10285:         }
10286:     }
10287:     if (length($env{'form.upfile'}) < 2) {
10288:         $result .=
10289:             &Apache::lonhtmlcommon::confirm_success(
10290:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10291:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10292:         return $result;
10293:     }
10294: 
10295: # Were able to get all the info needed, now analyze the file
10296: 
10297:     $result.=&Apache::loncommon::studentbrowser_javascript();
10298:     $symb = &Apache::lonenc::check_encrypt($symb);
10299:     $result.=&Apache::loncommon::start_data_table().
10300:              &Apache::loncommon::start_data_table_header_row().
10301:              '<th>'.&mt('Evaluate clicker file').'</th>'.
10302:              &Apache::loncommon::end_data_table_header_row().
10303:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10304: <td>
10305: <form method="post" action="/adm/grades" name="clickeranalysis">
10306: <input type="hidden" name="symb" value="$symb" />
10307: <input type="hidden" name="command" value="assignclickergrades" />
10308: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10309: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10310: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10311: ENDHEADER
10312:     if ($env{'form.gradingmechanism'} eq 'given') {
10313:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10314:     } 
10315:     my %responses;
10316:     my @questiontitles;
10317:     my $errormsg='';
10318:     my $number=0;
10319:     if ($env{'form.upfiletype'} eq 'iclicker') {
10320: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10321:     }
10322:     if ($env{'form.upfiletype'} eq 'interwrite') {
10323:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10324:     }
10325:     if ($env{'form.upfiletype'} eq 'turning') {
10326:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10327:     }
10328:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10329:              '<input type="hidden" name="number" value="'.$number.'" />'.
10330:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10331:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
10332:              '<br />';
10333:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10334:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10335:        return $result;
10336:     } 
10337: # Remember Question Titles
10338: # FIXME: Possibly need delimiter other than ":"
10339:     for (my $i=0;$i<$number;$i++) {
10340:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
10341:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10342:     }
10343:     my $correct_count=0;
10344:     my $student_count=0;
10345:     my $unknown_count=0;
10346: # Match answers with usernames
10347: # FIXME: Possibly need delimiter other than ":"
10348:     foreach my $id (keys(%responses)) {
10349:        if ($correct_ids{$id}) {
10350:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10351:           $correct_count++;
10352:        } elsif ($clicker_ids{$id}) {
10353:           if ($clicker_ids{$id}=~/\,/) {
10354: # More than one user with the same clicker!
10355:              $result.="</td>".&Apache::loncommon::end_data_table_row().
10356:                            &Apache::loncommon::start_data_table_row()."<td>".
10357:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10358:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10359:                            "<select name='multi".$id."'>";
10360:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10361:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10362:              }
10363:              $result.='</select>';
10364:              $unknown_count++;
10365:           } else {
10366: # Good: found one and only one user with the right clicker
10367:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10368:              $student_count++;
10369:           }
10370:        } else {
10371:           $result.="</td>".&Apache::loncommon::end_data_table_row().
10372:                            &Apache::loncommon::start_data_table_row()."<td>".
10373:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10374:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10375:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
10376:                    "\n".&mt("Domain").": ".
10377:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
10378:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10379:           $unknown_count++;
10380:        }
10381:     }
10382:     $result.='<hr />'.
10383:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10384:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10385:        if ($correct_count==0) {
10386:           $errormsg.="Found no correct answers for grading!";
10387:        } elsif ($correct_count>1) {
10388:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10389:        }
10390:     }
10391:     if ($number<1) {
10392:        $errormsg.="Found no questions.";
10393:     }
10394:     if ($errormsg) {
10395:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10396:     } else {
10397:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10398:     }
10399:     $result.='</form></td>'.
10400:              &Apache::loncommon::end_data_table_row().
10401:              &Apache::loncommon::end_data_table();
10402:     return $result;
10403: }
10404: 
10405: sub iclicker_eval {
10406:     my ($questiontitles,$responses)=@_;
10407:     my $number=0;
10408:     my $errormsg='';
10409:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10410:         my %components=&Apache::loncommon::record_sep($line);
10411:         my @entries=map {$components{$_}} (sort(keys(%components)));
10412: 	if ($entries[0] eq 'Question') {
10413: 	    for (my $i=3;$i<$#entries;$i+=6) {
10414: 		$$questiontitles[$number]=$entries[$i];
10415: 		$number++;
10416: 	    }
10417: 	}
10418: 	if ($entries[0]=~/^\#/) {
10419: 	    my $id=$entries[0];
10420: 	    my @idresponses;
10421: 	    $id=~s/^[\#0]+//;
10422: 	    for (my $i=0;$i<$number;$i++) {
10423: 		my $idx=3+$i*6;
10424:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10425: 		push(@idresponses,$entries[$idx]);
10426: 	    }
10427: 	    $$responses{$id}=join(',',@idresponses);
10428: 	}
10429:     }
10430:     return ($errormsg,$number);
10431: }
10432: 
10433: sub interwrite_eval {
10434:     my ($questiontitles,$responses)=@_;
10435:     my $number=0;
10436:     my $errormsg='';
10437:     my $skipline=1;
10438:     my $questionnumber=0;
10439:     my %idresponses=();
10440:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10441:         my %components=&Apache::loncommon::record_sep($line);
10442:         my @entries=map {$components{$_}} (sort(keys(%components)));
10443:         if ($entries[1] eq 'Time') { $skipline=0; next; }
10444:         if ($entries[1] eq 'Response') { $skipline=1; }
10445:         next if $skipline;
10446:         if ($entries[0]!=$questionnumber) {
10447:            $questionnumber=$entries[0];
10448:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10449:            $number++;
10450:         }
10451:         my $id=$entries[4];
10452:         $id=~s/^[\#0]+//;
10453:         $id=~s/^v\d*\://i;
10454:         $id=~s/[\-\:]//g;
10455:         $idresponses{$id}[$number]=$entries[6];
10456:     }
10457:     foreach my $id (keys(%idresponses)) {
10458:        $$responses{$id}=join(',',@{$idresponses{$id}});
10459:        $$responses{$id}=~s/^\s*\,//;
10460:     }
10461:     return ($errormsg,$number);
10462: }
10463: 
10464: sub turning_eval {
10465:     my ($questiontitles,$responses)=@_;
10466:     my $number=0;
10467:     my $errormsg='';
10468:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10469:         my %components=&Apache::loncommon::record_sep($line);
10470:         my @entries=map {$components{$_}} (sort(keys(%components)));
10471:         if ($#entries>$number) { $number=$#entries; }
10472:         my $id=$entries[0];
10473:         my @idresponses;
10474:         $id=~s/^[\#0]+//;
10475:         unless ($id) { next; }
10476:         for (my $idx=1;$idx<=$#entries;$idx++) {
10477:             $entries[$idx]=~s/\,/\;/g;
10478:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10479:             push(@idresponses,$entries[$idx]);
10480:         }
10481:         $$responses{$id}=join(',',@idresponses);
10482:     }
10483:     for (my $i=1; $i<=$number; $i++) {
10484:         $$questiontitles[$i]=&mt('Question [_1]',$i);
10485:     }
10486:     return ($errormsg,$number);
10487: }
10488: 
10489: 
10490: sub assign_clicker_grades {
10491:     my ($r,$symb)=@_;
10492:     if (!$symb) {return '';}
10493: # See which part we are saving to
10494:     my $res_error;
10495:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10496:     if ($res_error) {
10497:         return &navmap_errormsg();
10498:     }
10499: # FIXME: This should probably look for the first handgradeable part
10500:     my $part=$$partlist[0];
10501: # Start screen output
10502:     my $result=&Apache::loncommon::start_data_table().
10503:              &Apache::loncommon::start_data_table_header_row().
10504:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10505:              &Apache::loncommon::end_data_table_header_row().
10506:              &Apache::loncommon::start_data_table_row().'<td>';
10507: # Get correct result
10508: # FIXME: Possibly need delimiter other than ":"
10509:     my @correct=();
10510:     my $gradingmechanism=$env{'form.gradingmechanism'};
10511:     my $number=$env{'form.number'};
10512:     if ($gradingmechanism ne 'attendance') {
10513:        foreach my $key (keys(%env)) {
10514:           if ($key=~/^form\.correct\:/) {
10515:              my @input=split(/\,/,$env{$key});
10516:              for (my $i=0;$i<=$#input;$i++) {
10517:                  if (($correct[$i]) && ($input[$i]) &&
10518:                      ($correct[$i] ne $input[$i])) {
10519:                     $result.='<br /><span class="LC_warning">'.
10520:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10521:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10522:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
10523:                     $correct[$i]=$input[$i];
10524:                  }
10525:              }
10526:           }
10527:        }
10528:        for (my $i=0;$i<$number;$i++) {
10529:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10530:              $result.='<br /><span class="LC_error">'.
10531:                       &mt('No correct result given for question "[_1]"!',
10532:                           $env{'form.question:'.$i}).'</span>';
10533:           }
10534:        }
10535:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10536:     }
10537: # Start grading
10538:     my $pcorrect=$env{'form.pcorrect'};
10539:     my $pincorrect=$env{'form.pincorrect'};
10540:     my $storecount=0;
10541:     my %users=();
10542:     foreach my $key (keys(%env)) {
10543:        my $user='';
10544:        if ($key=~/^form\.student\:(.*)$/) {
10545:           $user=$1;
10546:        }
10547:        if ($key=~/^form\.unknown\:(.*)$/) {
10548:           my $id=$1;
10549:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10550:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10551:           } elsif ($env{'form.multi'.$id}) {
10552:              $user=$env{'form.multi'.$id};
10553:           }
10554:        }
10555:        if ($user) {
10556:           if ($users{$user}) {
10557:              $result.='<br /><span class="LC_warning">'.
10558:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10559:                       '</span><br />';
10560:           }
10561:           $users{$user}=1; 
10562:           my @answer=split(/\,/,$env{$key});
10563:           my $sum=0;
10564:           my $realnumber=$number;
10565:           for (my $i=0;$i<$number;$i++) {
10566:              if  ($correct[$i] eq '-') {
10567:                 $realnumber--;
10568:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
10569:                 if ($gradingmechanism eq 'attendance') {
10570:                    $sum+=$pcorrect;
10571:                 } elsif ($correct[$i] eq '*') {
10572:                    $sum+=$pcorrect;
10573:                 } else {
10574: # We actually grade if correct or not
10575:                    my $increment=$pincorrect;
10576: # Special case: numerical answer "0"
10577:                    if ($correct[$i] eq '0') {
10578:                       if ($answer[$i]=~/^[0\.]+$/) {
10579:                          $increment=$pcorrect;
10580:                       }
10581: # General numerical answer, both evaluate to something non-zero
10582:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10583:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
10584:                          $increment=$pcorrect;
10585:                       }
10586: # Must be just alphanumeric
10587:                    } elsif ($answer[$i] eq $correct[$i]) {
10588:                       $increment=$pcorrect;
10589:                    }
10590:                    $sum+=$increment;
10591:                 }
10592:              }
10593:           }
10594:           my $ave=$sum/(100*$realnumber);
10595: # Store
10596:           my ($username,$domain)=split(/\:/,$user);
10597:           my %grades=();
10598:           $grades{"resource.$part.solved"}='correct_by_override';
10599:           $grades{"resource.$part.awarded"}=$ave;
10600:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10601:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10602:                                                  $env{'request.course.id'},
10603:                                                  $domain,$username);
10604:           if ($returncode ne 'ok') {
10605:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10606:           } else {
10607:              $storecount++;
10608:           }
10609:        }
10610:     }
10611: # We are done
10612:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10613:              '</td>'.
10614:              &Apache::loncommon::end_data_table_row().
10615:              &Apache::loncommon::end_data_table();
10616:     return $result;
10617: }
10618: 
10619: sub navmap_errormsg {
10620:     return '<div class="LC_error">'.
10621:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10622:            &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>').
10623:            '</div>';
10624: }
10625: 
10626: sub startpage {
10627:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10628:     if ($nomenu) {
10629:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10630:     } else {
10631:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10632:         $r->print(&Apache::loncommon::start_page('Grading',$js,
10633:                                                  {'bread_crumbs' => $crumbs}));
10634:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10635:     }
10636:     unless ($nodisplayflag) {
10637:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10638:     }
10639: }
10640: 
10641: sub select_problem {
10642:     my ($r)=@_;
10643:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10644:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
10645:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10646:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
10647: }
10648: 
10649: sub handler {
10650:     my $request=$_[0];
10651:     &reset_caches();
10652:     if ($request->header_only) {
10653:         &Apache::loncommon::content_type($request,'text/html');
10654:         $request->send_http_header;
10655:         return OK;
10656:     }
10657:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10658: 
10659: # see what command we need to execute
10660: 
10661:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
10662:     my $command=$commands[0];
10663: 
10664:     &init_perm();
10665:     if (!$env{'request.course.id'}) {
10666:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10667:                 ($command =~ /^scantronupload/)) {
10668:             # Not in a course.
10669:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10670:             return HTTP_NOT_ACCEPTABLE;
10671:         }
10672:     } elsif (!%perm) {
10673:         $request->internal_redirect('/adm/quickgrades');
10674:         return OK;
10675:     }
10676:     &Apache::loncommon::content_type($request,'text/html');
10677:     $request->send_http_header;
10678: 
10679:     if ($#commands > 0) {
10680: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10681:     }
10682: 
10683: # see what the symb is
10684: 
10685:     my $symb=$env{'form.symb'};
10686:     unless ($symb) {
10687:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10688:        $symb=&Apache::lonnet::symbread($url);
10689:     }
10690:     &Apache::lonenc::check_decrypt(\$symb);
10691: 
10692:     $ssi_error = 0;
10693:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10694: #
10695: # Not called from a resource, but inside a course
10696: #    
10697:         &startpage($request,undef,[],1,1);
10698:         &select_problem($request);
10699:     } else {
10700: 	if ($command eq 'submission' && $perm{'vgr'}) {
10701:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
10702:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10703:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
10704:                     &choose_task_version_form($symb,$env{'form.student'},
10705:                                               $env{'form.userdom'});
10706:             }
10707:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10708:             if ($versionform) {
10709:                 $request->print($versionform);
10710:             }
10711:             $request->print('<br clear="all" />');
10712: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10713:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10714:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10715:                 &choose_task_version_form($symb,$env{'form.student'},
10716:                                           $env{'form.userdom'},
10717:                                           $env{'form.inhibitmenu'});
10718:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10719:             if ($versionform) {
10720:                 $request->print($versionform);
10721:             }
10722:             $request->print('<br clear="all" />');
10723:             $request->print(&show_previous_task_version($request,$symb));
10724: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10725:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10726:                                        {href=>'',text=>'Select student'}],1,1);
10727: 	    &pickStudentPage($request,$symb);
10728: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10729:             &startpage($request,$symb,
10730:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10731:                                        {href=>'',text=>'Select student'},
10732:                                        {href=>'',text=>'Grade student'}],1,1);
10733: 	    &displayPage($request,$symb);
10734: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10735:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10736:                                        {href=>'',text=>'Select student'},
10737:                                        {href=>'',text=>'Grade student'},
10738:                                        {href=>'',text=>'Store grades'}],1,1);
10739: 	    &updateGradeByPage($request,$symb);
10740: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10741:             &startpage($request,$symb,[{href=>'',text=>'...'},
10742:                                        {href=>'',text=>'Modify grades'}]);
10743: 	    &processGroup($request,$symb);
10744: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10745:             &startpage($request,$symb);
10746: 	    $request->print(&grading_menu($request,$symb));
10747: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
10748:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10749: 	    $request->print(&submit_options($request,$symb));
10750:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10751:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10752:             $request->print(&listStudents($request,$symb,'graded'));
10753:         } elsif ($command eq 'table' && $perm{'vgr'}) {
10754:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10755:             $request->print(&submit_options_table($request,$symb));
10756:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10757:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10758:             $request->print(&submit_options_sequence($request,$symb));
10759: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10760:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10761: 	    $request->print(&viewgrades($request,$symb));
10762: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10763:             &startpage($request,$symb,[{href=>'',text=>'...'},
10764:                                        {href=>'',text=>'Store grades'}]);
10765: 	    $request->print(&processHandGrade($request,$symb));
10766: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10767:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10768:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
10769:                                                                              text=>"Modify grades"},
10770:                                        {href=>'', text=>"Store grades"}]);
10771: 	    $request->print(&editgrades($request,$symb));
10772:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10773:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10774:             $request->print(&initialverifyreceipt($request,$symb));
10775: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
10776:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10777:                                        {href=>'',text=>'Verification Result'}]);
10778: 	    $request->print(&verifyreceipt($request,$symb));
10779:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10780:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10781:             $request->print(&process_clicker($request,$symb));
10782:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10783:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10784:                                        {href=>'', text=>'Process clicker file'}]);
10785:             $request->print(&process_clicker_file($request,$symb));
10786:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10787:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10788:                                        {href=>'', text=>'Process clicker file'},
10789:                                        {href=>'', text=>'Store grades'}]);
10790:             $request->print(&assign_clicker_grades($request,$symb));
10791: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
10792:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10793: 	    $request->print(&upcsvScores_form($request,$symb));
10794: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10795:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10796: 	    $request->print(&csvupload($request,$symb));
10797: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10798:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10799: 	    $request->print(&csvuploadmap($request,$symb));
10800: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10801: 	    if ($env{'form.associate'} ne 'Reverse Association') {
10802:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10803: 		$request->print(&csvuploadoptions($request,$symb));
10804: 	    } else {
10805: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10806: 		    $env{'form.upfile_associate'} = 'reverse';
10807: 		} else {
10808: 		    $env{'form.upfile_associate'} = 'forward';
10809: 		}
10810:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10811: 		$request->print(&csvuploadmap($request,$symb));
10812: 	    }
10813: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10814:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10815: 	    $request->print(&csvuploadassign($request,$symb));
10816: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10817:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10818: 	    $request->print(&scantron_selectphase($request,undef,$symb));
10819:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10820:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10821:  	    $request->print(&scantron_do_warning($request,$symb));
10822: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10823:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10824: 	    $request->print(&scantron_validate_file($request,$symb));
10825: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10826:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10827: 	    $request->print(&scantron_process_students($request,$symb));
10828:  	} elsif ($command eq 'scantronupload' && 
10829:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10830: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10831:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10832:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
10833:  	} elsif ($command eq 'scantronupload_save' &&
10834:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10835: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10836:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10837:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
10838:  	} elsif ($command eq 'scantron_download' &&
10839: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10840:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10841:  	    $request->print(&scantron_download_scantron_data($request,$symb));
10842:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10843:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10844:             $request->print(&checkscantron_results($request,$symb));
10845:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10846:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10847:             $request->print(&submit_options_download($request,$symb));
10848:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10849:             &startpage($request,$symb,
10850:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10851:     {href=>'', text=>'Download submitted files'}]);
10852:             &submit_download_link($request,$symb);
10853: 	} elsif ($command) {
10854:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10855: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10856: 	}
10857:     }
10858:     if ($ssi_error) {
10859: 	&ssi_print_error($request);
10860:     }
10861:     if ($env{'form.inhibitmenu'}) {
10862:         $request->print(&Apache::loncommon::end_page());
10863:     } else {
10864:         &Apache::lonquickgrades::endGradeScreen($request);
10865:     }
10866:     &reset_caches();
10867:     return OK;
10868: }
10869: 
10870: 1;
10871: 
10872: __END__;
10873: 
10874: 
10875: =head1 NAME
10876: 
10877: Apache::grades
10878: 
10879: =head1 SYNOPSIS
10880: 
10881: Handles the viewing of grades.
10882: 
10883: This is part of the LearningOnline Network with CAPA project
10884: described at http://www.lon-capa.org.
10885: 
10886: =head1 OVERVIEW
10887: 
10888: Do an ssi with retries:
10889: While I'd love to factor out this with the version in lonprintout,
10890: 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
10891: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10892: 
10893: At least the logic that drives this has been pulled out into loncommon.
10894: 
10895: 
10896: 
10897: ssi_with_retries - Does the server side include of a resource.
10898:                      if the ssi call returns an error we'll retry it up to
10899:                      the number of times requested by the caller.
10900:                      If we still have a problem, no text is appended to the
10901:                      output and we set some global variables.
10902:                      to indicate to the caller an SSI error occurred.  
10903:                      All of this is supposed to deal with the issues described
10904:                      in LON-CAPA BZ 5631 see:
10905:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
10906:                      by informing the user that this happened.
10907: 
10908: Parameters:
10909:   resource   - The resource to include.  This is passed directly, without
10910:                interpretation to lonnet::ssi.
10911:   form       - The form hash parameters that guide the interpretation of the resource
10912:                
10913:   retries    - Number of retries allowed before giving up completely.
10914: Returns:
10915:   On success, returns the rendered resource identified by the resource parameter.
10916: Side Effects:
10917:   The following global variables can be set:
10918:    ssi_error                - If an unrecoverable error occurred this becomes true.
10919:                               It is up to the caller to initialize this to false
10920:                               if desired.
10921:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
10922:                               of the resource that could not be rendered by the ssi
10923:                               call.
10924:    ssi_error_message   - The error string fetched from the ssi response
10925:                               in the event of an error.
10926: 
10927: 
10928: =head1 HANDLER SUBROUTINE
10929: 
10930: ssi_with_retries()
10931: 
10932: =head1 SUBROUTINES
10933: 
10934: =over
10935: 
10936: =head1 Routines to display previous version of a Task for a specific student
10937: 
10938: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10939: can receive another opportunity. Access to tasks is slot-based. If a slot
10940: requires a proctor to check-in the student, a new version of the Task will
10941: be created when the student is checked in to the new opportunity.
10942: 
10943: If a particular student has tried two or more versions of a particular task,
10944: the submission screen provides a user with vgr privileges (e.g., a Course
10945: Coordinator) the ability to display a previous version worked on by the
10946: student.  By default, the current version is displayed. If a previous version
10947: has been selected for display, submission data are only shown that pertain
10948: to that particular version, and the interface to submit grades is not shown.
10949: 
10950: =over 4
10951: 
10952: =item show_previous_task_version()
10953: 
10954: Displays a specified version of a student's Task, as the student sees it.
10955: 
10956: Inputs: 2
10957:         request - request object
10958:         symb    - unique symb for current instance of resource
10959: 
10960: Output: None.
10961: 
10962: Side Effects: calls &show_problem() to print version of Task, with
10963:               version contained in form item: $env{'form.previousversion'}
10964: 
10965: =item choose_task_version_form()
10966: 
10967: Displays a web form used to select which version of a student's view of a
10968: Task should be displayed.  Either launches a pop-up window, or replaces
10969: content in existing pop-up, or replaces page in main window.
10970: 
10971: Inputs: 4
10972:         symb    - unique symb for current instance of resource
10973:         uname   - username of student
10974:         udom    - domain of student
10975:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10976:                   breadcrumbs etc., are displayed
10977: 
10978: Output: 4
10979:         current   - student's current version
10980:         displayed - student's version being displayed
10981:         result    - scalar containing HTML for web form used to switch to
10982:                     a different version (or a link to close window, if pop-up).
10983:         js        - javascript for processing selection in versions web form
10984: 
10985: Side Effects: None.
10986: 
10987: =item previous_display_javascript()
10988: 
10989: Inputs: 2
10990:         nomenu  - 1 if display is in a pop-up window, and hence no menu
10991:                   breadcrumbs etc., are displayed.
10992:         current - student's current version number.
10993: 
10994: Output: 1
10995:         js      - javascript for processing selection in versions web form.
10996: 
10997: Side Effects: None.
10998: 
10999: =back
11000: 
11001: =head1 Routines to process bubblesheet data.
11002: 
11003: =over 4
11004: 
11005: =item scantron_get_correction() : 
11006: 
11007:    Builds the interface screen to interact with the operator to fix a
11008:    specific error condition in a specific scanline
11009: 
11010:  Arguments:
11011:     $r           - Apache request object
11012:     $i           - number of the current scanline
11013:     $scan_record - hash ref as returned from &scantron_parse_scanline()
11014:     $scan_config - hash ref as returned from &get_scantron_config()
11015:     $line        - full contents of the current scanline
11016:     $error       - error condition, valid values are
11017:                    'incorrectCODE', 'duplicateCODE',
11018:                    'doublebubble', 'missingbubble',
11019:                    'duplicateID', 'incorrectID'
11020:     $arg         - extra information needed
11021:        For errors:
11022:          - duplicateID   - paper number that this studentID was seen before on
11023:          - duplicateCODE - array ref of the paper numbers this CODE was
11024:                            seen on before
11025:          - incorrectCODE - current incorrect CODE 
11026:          - doublebubble  - array ref of the bubble lines that have double
11027:                            bubble errors
11028:          - missingbubble - array ref of the bubble lines that have missing
11029:                            bubble errors
11030: 
11031:    $randomorder - True if exam folder has randomorder set
11032:    $randompick  - True if exam folder has randompick set
11033:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11034:                      for current line to question number used for same question
11035:                      in "Master Seqence" (as seen by Course Coordinator).
11036:    $startline   - Reference to hash where key is question number (0 is first)
11037:                   and value is number of first bubble line for current student
11038:                   or code-based randompick and/or randomorder.
11039: 
11040: 
11041: 
11042: =item  scantron_get_maxbubble() : 
11043: 
11044:    Arguments:
11045:        $nav_error  - Reference to scalar which is a flag to indicate a
11046:                       failure to retrieve a navmap object.
11047:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
11048:        calling routine should trap the error condition and display the warning
11049:        found in &navmap_errormsg().
11050: 
11051:        $scantron_config - Reference to bubblesheet format configuration hash.
11052: 
11053:    Returns the maximum number of bubble lines that are expected to
11054:    occur. Does this by walking the selected sequence rendering the
11055:    resource and then checking &Apache::lonxml::get_problem_counter()
11056:    for what the current value of the problem counter is.
11057: 
11058:    Caches the results to $env{'form.scantron_maxbubble'},
11059:    $env{'form.scantron.bubble_lines.n'}, 
11060:    $env{'form.scantron.first_bubble_line.n'} and
11061:    $env{"form.scantron.sub_bubblelines.n"}
11062:    which are the total number of bubble lines, the number of bubble
11063:    lines for response n and number of the first bubble line for response n,
11064:    and a comma separated list of numbers of bubble lines for sub-questions
11065:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
11066: 
11067: 
11068: =item  scantron_validate_missingbubbles() : 
11069: 
11070:    Validates all scanlines in the selected file to not have any
11071:     answers that don't have bubbles that have not been verified
11072:     to be bubble free.
11073: 
11074: =item  scantron_process_students() : 
11075: 
11076:    Routine that does the actual grading of the bubblesheet information.
11077: 
11078:    The parsed scanline hash is added to %env 
11079: 
11080:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11081:    foreach resource , with the form data of
11082: 
11083: 	'submitted'     =>'scantron' 
11084: 	'grade_target'  =>'grade',
11085: 	'grade_username'=> username of student
11086: 	'grade_domain'  => domain of student
11087: 	'grade_courseid'=> of course
11088: 	'grade_symb'    => symb of resource to grade
11089: 
11090:     This triggers a grading pass. The problem grading code takes care
11091:     of converting the bubbled letter information (now in %env) into a
11092:     valid submission.
11093: 
11094: =item  scantron_upload_scantron_data() :
11095: 
11096:     Creates the screen for adding a new bubblesheet data file to a course.
11097: 
11098: =item  scantron_upload_scantron_data_save() : 
11099: 
11100:    Adds a provided bubble information data file to the course if user
11101:    has the correct privileges to do so. 
11102: 
11103: =item  valid_file() :
11104: 
11105:    Validates that the requested bubble data file exists in the course.
11106: 
11107: =item  scantron_download_scantron_data() : 
11108: 
11109:    Shows a list of the three internal files (original, corrected,
11110:    skipped) for a specific bubblesheet data file that exists in the
11111:    course.
11112: 
11113: =item  scantron_validate_ID() : 
11114: 
11115:    Validates all scanlines in the selected file to not have any
11116:    invalid or underspecified student/employee IDs
11117: 
11118: =item navmap_errormsg() :
11119: 
11120:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11121:    Should be called whenever the request to instantiate a navmap object fails.
11122: 
11123: =back
11124: 
11125: =back
11126: 
11127: =cut

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