File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.3: download - view: text, annotated - select for diffs
Wed Dec 22 17:11:12 2010 UTC (13 years, 4 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC2, version_2_10_0
- Backport 1.641

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.3 2010/12/22 17:11:12 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);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &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 />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: sub getpartlist {
  100:     my ($symb,$errorref) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     unless (ref($navmap)) {
  104:         if (ref($errorref)) { 
  105:             $$errorref = 'navmap';
  106:             return;
  107:         }
  108:     }
  109:     my $res      = $navmap->getBySymb($symb);
  110:     my $partlist = $res->parts();
  111:     my $url      = $res->src();
  112:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  113: 
  114:     my @stores;
  115:     foreach my $part (@{ $partlist }) {
  116: 	foreach my $key (@metakeys) {
  117: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  118: 	}
  119:     }
  120:     return @stores;
  121: }
  122: 
  123: # --- Get the symbolic name of a problem and the url
  124: sub get_symb {
  125:     my ($request,$silent) = @_;
  126:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  127:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  128:     if ($symb eq '') { 
  129: 	if (!$silent) {
  130: 	    $request->print("Unable to handle ambiguous references:$url:.");
  131: 	    return ();
  132: 	}
  133:     }
  134:     &Apache::lonenc::check_decrypt(\$symb);
  135:     return ($symb);
  136: }
  137: 
  138: #--- Format fullname, username:domain if different for display
  139: #--- Use anywhere where the student names are listed
  140: sub nameUserString {
  141:     my ($type,$fullname,$uname,$udom) = @_;
  142:     if ($type eq 'header') {
  143: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  144:     } else {
  145: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  146: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  147:     }
  148: }
  149: 
  150: #--- Get the partlist and the response type for a given problem. ---
  151: #--- Indicate if a response type is coded handgraded or not. ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     unless (ref($res)) {
  164:         $$response_error = 1;
  165:         return;
  166:     }
  167:     my $partlist = $res->parts();
  168:     my %vPart = 
  169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  170:     my (%response_types,%handgrade);
  171:     foreach my $part (@{ $partlist }) {
  172: 	next if (%vPart && !exists($vPart{$part}));
  173: 
  174: 	my @types = $res->responseType($part);
  175: 	my @ids = $res->responseIds($part);
  176: 	for (my $i=0; $i < scalar(@ids); $i++) {
  177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  178: 	    $handgrade{$part.'_'.$ids[$i]} = 
  179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  180: 				     '.handgrade',$symb);
  181: 	}
  182:     }
  183:     return ($partlist,\%handgrade,\%response_types);
  184: }
  185: 
  186: sub flatten_responseType {
  187:     my ($responseType) = @_;
  188:     my @part_response_id =
  189: 	map { 
  190: 	    my $part = $_;
  191: 	    map {
  192: 		[$part,$_]
  193: 		} sort(keys(%{ $responseType->{$part} }));
  194: 	} sort(keys(%$responseType));
  195:     return @part_response_id;
  196: }
  197: 
  198: sub get_display_part {
  199:     my ($partID,$symb)=@_;
  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  201:     if (defined($display) and $display ne '') {
  202:         $display.= ' (<span class="LC_internal_info">'
  203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  204:     } else {
  205: 	$display=$partID;
  206:     }
  207:     return $display;
  208: }
  209: 
  210: #--- Show resource title
  211: #--- and parts and response type
  212: sub showResourceInfo {
  213:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  214:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  215:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  216:     if (ref($res_error)) {
  217:         if ($$res_error) {
  218:             return;
  219:         }
  220:     }
  221:     $result.=&Apache::loncommon::start_data_table()
  222:             .&Apache::loncommon::start_data_table_header_row();
  223:     if ($checkboxes) {
  224:         $result.='<th>&nbsp;</th>';
  225:     }
  226:     $result.='<th>'.&mt('Problem Part').'</th>'
  227:             .'<th>'.&mt('Res. ID').'</th>'
  228:             .'<th>'.&mt('Type').'</th>'
  229:             .&Apache::loncommon::end_data_table_header_row();
  230:     my %resptype = ();
  231:     my $hdgrade='no';
  232:     my %partsseen;
  233:     foreach my $partID (sort(keys(%$responseType))) {
  234:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  235:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  236:             my $responsetype = $responseType->{$partID}->{$resID};
  237:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  238:             $result.=&Apache::loncommon::start_data_table_row();
  239:             if ($checkboxes) {
  240:                 if (exists($partsseen{$partID})) {
  241:                     $result.="<td>&nbsp;</td>";
  242:                 } else {
  243:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  244:                 }
  245:                 $partsseen{$partID}=1;
  246:             }
  247:             my $display_part=&get_display_part($partID,$symb);
  248:             $result.='<td>'.$display_part.'</td>'
  249:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  250:                     .'<td>'.&mt($responsetype).'</td>'
  251: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  252:                     .&Apache::loncommon::end_data_table_row();
  253:         }
  254:     }
  255:     $result.=&Apache::loncommon::end_data_table();
  256:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  257: }
  258: 
  259: sub reset_caches {
  260:     &reset_analyze_cache();
  261:     &reset_perm();
  262: }
  263: 
  264: {
  265:     my %analyze_cache;
  266:     my %analyze_cache_formkeys;
  267: 
  268:     sub reset_analyze_cache {
  269: 	undef(%analyze_cache);
  270:         undef(%analyze_cache_formkeys);
  271:     }
  272: 
  273:     sub get_analyze {
  274: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed)=@_;
  275: 	my $key = "$symb\0$uname\0$udom";
  276:         if ($type eq 'randomizetry') {
  277:             if ($trial ne '') {
  278:                 $key .= "\0".$trial;
  279:             }
  280:         }
  281: 	if (exists($analyze_cache{$key})) {
  282:             my $getupdate = 0;
  283:             if (ref($add_to_hash) eq 'HASH') {
  284:                 foreach my $item (keys(%{$add_to_hash})) {
  285:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  286:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  287:                             $getupdate = 1;
  288:                             last;
  289:                         }
  290:                     } else {
  291:                         $getupdate = 1;
  292:                     }
  293:                 }
  294:             }
  295:             if (!$getupdate) {
  296:                 return $analyze_cache{$key};
  297:             }
  298:         }
  299: 
  300: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  301: 	$url=&Apache::lonnet::clutter($url);
  302:         my %form = ('grade_target'      => 'analyze',
  303:                     'grade_domain'      => $udom,
  304:                     'grade_symb'        => $symb,
  305:                     'grade_courseid'    =>  $env{'request.course.id'},
  306:                     'grade_username'    => $uname,
  307:                     'grade_noincrement' => $no_increment);
  308:         if ($type eq 'randomizetry') {
  309:             $form{'grade_questiontype'} = $type;
  310:             if ($rndseed ne '') {
  311:                 $form{'grade_rndseed'} = $rndseed;
  312:             }
  313:         }
  314:         if (ref($add_to_hash)) {
  315:             %form = (%form,%{$add_to_hash});
  316:         }
  317: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  318: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  319: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  320:         if (ref($add_to_hash) eq 'HASH') {
  321:             $analyze_cache_formkeys{$key} = $add_to_hash;
  322:         } else {
  323:             $analyze_cache_formkeys{$key} = {};
  324:         }
  325: 	return $analyze_cache{$key} = \%analyze;
  326:     }
  327: 
  328:     sub get_order {
  329: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
  330: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
  331: 	return $analyze->{"$partid.$respid.shown"};
  332:     }
  333: 
  334:     sub get_radiobutton_correct_foil {
  335: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
  336: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
  337:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
  338:         if (ref($foils) eq 'ARRAY') {
  339: 	    foreach my $foil (@{$foils}) {
  340: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  341: 		    return $foil;
  342: 	        }
  343: 	    }
  344: 	}
  345:     }
  346: 
  347:     sub scantron_partids_tograde {
  348:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  349:         my (%analysis,@parts);
  350:         if (ref($resource)) {
  351:             my $symb = $resource->symb();
  352:             my $add_to_form;
  353:             if ($check_for_randomlist) {
  354:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  355:             }
  356:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  357:             if (ref($analyze) eq 'HASH') {
  358:                 %analysis = %{$analyze};
  359:             }
  360:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  361:                 foreach my $part (@{$analysis{'parts'}}) {
  362:                     my ($id,$respid) = split(/\./,$part);
  363:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  364:                         push(@parts,$part);
  365:                     }
  366:                 }
  367:             }
  368:         }
  369:         return (\%analysis,\@parts);
  370:     }
  371: 
  372: }
  373: 
  374: #--- Clean response type for display
  375: #--- Currently filters option/rank/radiobutton/match/essay/Task
  376: #        response types only.
  377: sub cleanRecord {
  378:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  379: 	$uname,$udom,$type,$trial,$rndseed) = @_;
  380:     my $grayFont = '<span class="LC_internal_info">';
  381:     if ($response =~ /^(option|rank)$/) {
  382: 	my %answer=&Apache::lonnet::str2hash($answer);
  383: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  384: 	my ($toprow,$bottomrow);
  385: 	foreach my $foil (@$order) {
  386: 	    if ($grading{$foil} == 1) {
  387: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  388: 	    } else {
  389: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  390: 	    }
  391: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  392: 	}
  393: 	return '<blockquote><table border="1">'.
  394: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  395: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  396: 	    $bottomrow.'</tr></table></blockquote>';
  397:     } elsif ($response eq 'match') {
  398: 	my %answer=&Apache::lonnet::str2hash($answer);
  399: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  400: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  401: 	my ($toprow,$middlerow,$bottomrow);
  402: 	foreach my $foil (@$order) {
  403: 	    my $item=shift(@items);
  404: 	    if ($grading{$foil} == 1) {
  405: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  406: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  407: 	    } else {
  408: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  409: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  410: 	    }
  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  412: 	}
  413: 	return '<blockquote><table border="1">'.
  414: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  415: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  416: 	    $middlerow.'</tr>'.
  417: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  418: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  419:     } elsif ($response eq 'radiobutton') {
  420: 	my %answer=&Apache::lonnet::str2hash($answer);
  421: 	my ($toprow,$bottomrow);
  422: 	my $correct = 
  423: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
  424: 	foreach my $foil (@$order) {
  425: 	    if (exists($answer{$foil})) {
  426: 		if ($foil eq $correct) {
  427: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  428: 		} else {
  429: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  430: 		}
  431: 	    } else {
  432: 		$toprow.='<td>'.&mt('false').'</td>';
  433: 	    }
  434: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  435: 	}
  436: 	return '<blockquote><table border="1">'.
  437: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  438: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  439: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  440:     } elsif ($response eq 'essay') {
  441: 	if (! exists ($env{'form.'.$symb})) {
  442: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  443: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  444: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  445: 
  446: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  447: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  448: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  449: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  450: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  451: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  452: 	}
  453: 	$answer =~ s-\n-<br />-g;
  454: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  455:     } elsif ( $response eq 'organic') {
  456: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  457: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  458: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  459: 	return $result;
  460:     } elsif ( $response eq 'Task') {
  461: 	if ( $answer eq 'SUBMITTED') {
  462: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  463: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  464: 	    return $result;
  465: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  466: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  467: 			       keys(%{$record}));
  468: 	    return join('<br />',($version,@matches));
  469: 			       
  470: 			       
  471: 	} else {
  472: 	    my $result =
  473: 		'<p>'
  474: 		.&mt('Overall result: [_1]',
  475: 		     $record->{$version."resource.$respid.$partid.status"})
  476: 		.'</p>';
  477: 	    
  478: 	    $result .= '<ul>';
  479: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  480: 			     keys(%{$record}));
  481: 	    foreach my $grade (sort(@grade)) {
  482: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  483: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  484: 				     $dim, $record->{$grade}).
  485: 			  '</li>';
  486: 	    }
  487: 	    $result.='</ul>';
  488: 	    return $result;
  489: 	}
  490:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  491: 	$answer = 
  492: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  493: 							      $answer);
  494:     }
  495:     return $answer;
  496: }
  497: 
  498: #-- A couple of common js functions
  499: sub commonJSfunctions {
  500:     my $request = shift;
  501:     $request->print(<<COMMONJSFUNCTIONS);
  502: <script type="text/javascript" language="javascript">
  503:     function radioSelection(radioButton) {
  504: 	var selection=null;
  505: 	if (radioButton.length > 1) {
  506: 	    for (var i=0; i<radioButton.length; i++) {
  507: 		if (radioButton[i].checked) {
  508: 		    return radioButton[i].value;
  509: 		}
  510: 	    }
  511: 	} else {
  512: 	    if (radioButton.checked) return radioButton.value;
  513: 	}
  514: 	return selection;
  515:     }
  516: 
  517:     function pullDownSelection(selectOne) {
  518: 	var selection="";
  519: 	if (selectOne.length > 1) {
  520: 	    for (var i=0; i<selectOne.length; i++) {
  521: 		if (selectOne[i].selected) {
  522: 		    return selectOne[i].value;
  523: 		}
  524: 	    }
  525: 	} else {
  526:             // only one value it must be the selected one
  527: 	    return selectOne.value;
  528: 	}
  529:     }
  530: </script>
  531: COMMONJSFUNCTIONS
  532: }
  533: 
  534: #--- Dumps the class list with usernames,list of sections,
  535: #--- section, ids and fullnames for each user.
  536: sub getclasslist {
  537:     my ($getsec,$filterlist,$getgroup) = @_;
  538:     my @getsec;
  539:     my @getgroup;
  540:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  541:     if (!ref($getsec)) {
  542: 	if ($getsec ne '' && $getsec ne 'all') {
  543: 	    @getsec=($getsec);
  544: 	}
  545:     } else {
  546: 	@getsec=@{$getsec};
  547:     }
  548:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  549:     if (!ref($getgroup)) {
  550: 	if ($getgroup ne '' && $getgroup ne 'all') {
  551: 	    @getgroup=($getgroup);
  552: 	}
  553:     } else {
  554: 	@getgroup=@{$getgroup};
  555:     }
  556:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  557: 
  558:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  559:     # Bail out if we were unable to get the classlist
  560:     return if (! defined($classlist));
  561:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  562:     #
  563:     my %sections;
  564:     my %fullnames;
  565:     foreach my $student (keys(%$classlist)) {
  566:         my $end      = 
  567:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  568:         my $start    = 
  569:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  570:         my $id       = 
  571:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  572:         my $section  = 
  573:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  574:         my $fullname = 
  575:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  576:         my $status   = 
  577:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  578:         my $group   = 
  579:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  580: 	# filter students according to status selected
  581: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  582: 	    if (!($stu_status =~ $status)) {
  583: 		delete($classlist->{$student});
  584: 		next;
  585: 	    }
  586: 	}
  587: 	# filter students according to groups selected
  588: 	my @stu_groups = split(/,/,$group);
  589: 	if (@getgroup) {
  590: 	    my $exclude = 1;
  591: 	    foreach my $grp (@getgroup) {
  592: 	        foreach my $stu_group (@stu_groups) {
  593: 	            if ($stu_group eq $grp) {
  594: 	                $exclude = 0;
  595:     	            } 
  596: 	        }
  597:     	        if (($grp eq 'none') && !$group) {
  598:         	        $exclude = 0;
  599:         	}
  600: 	    }
  601: 	    if ($exclude) {
  602: 	        delete($classlist->{$student});
  603: 	    }
  604: 	}
  605: 	$section = ($section ne '' ? $section : 'none');
  606: 	if (&canview($section)) {
  607: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  608: 		$sections{$section}++;
  609: 		if ($classlist->{$student}) {
  610: 		    $fullnames{$student}=$fullname;
  611: 		}
  612: 	    } else {
  613: 		delete($classlist->{$student});
  614: 	    }
  615: 	} else {
  616: 	    delete($classlist->{$student});
  617: 	}
  618:     }
  619:     my %seen = ();
  620:     my @sections = sort(keys(%sections));
  621:     return ($classlist,\@sections,\%fullnames);
  622: }
  623: 
  624: sub canmodify {
  625:     my ($sec)=@_;
  626:     if ($perm{'mgr'}) {
  627: 	if (!defined($perm{'mgr_section'})) {
  628: 	    # can modify whole class
  629: 	    return 1;
  630: 	} else {
  631: 	    if ($sec eq $perm{'mgr_section'}) {
  632: 		#can modify the requested section
  633: 		return 1;
  634: 	    } else {
  635: 		# can't modify the request section
  636: 		return 0;
  637: 	    }
  638: 	}
  639:     }
  640:     #can't modify
  641:     return 0;
  642: }
  643: 
  644: sub canview {
  645:     my ($sec)=@_;
  646:     if ($perm{'vgr'}) {
  647: 	if (!defined($perm{'vgr_section'})) {
  648: 	    # can modify whole class
  649: 	    return 1;
  650: 	} else {
  651: 	    if ($sec eq $perm{'vgr_section'}) {
  652: 		#can modify the requested section
  653: 		return 1;
  654: 	    } else {
  655: 		# can't modify the request section
  656: 		return 0;
  657: 	    }
  658: 	}
  659:     }
  660:     #can't modify
  661:     return 0;
  662: }
  663: 
  664: #--- Retrieve the grade status of a student for all the parts
  665: sub student_gradeStatus {
  666:     my ($symb,$udom,$uname,$partlist) = @_;
  667:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  668:     my %partstatus = ();
  669:     foreach (@$partlist) {
  670: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  671: 	$status              = 'nothing' if ($status eq '');
  672: 	$partstatus{$_}      = $status;
  673: 	my $subkey           = "resource.$_.submitted_by";
  674: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  675:     }
  676:     return %partstatus;
  677: }
  678: 
  679: # hidden form and javascript that calls the form
  680: # Use by verifyscript and viewgrades
  681: # Shows a student's view of problem and submission
  682: sub jscriptNform {
  683:     my ($symb) = @_;
  684:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  685:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  686: 	'    function viewOneStudent(user,domain) {'."\n".
  687: 	'	document.onestudent.student.value = user;'."\n".
  688: 	'	document.onestudent.userdom.value = domain;'."\n".
  689: 	'	document.onestudent.submit();'."\n".
  690: 	'    }'."\n".
  691: 	'</script>'."\n";
  692:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  693: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  694: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  695: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  696: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  697: 	'<input type="hidden" name="command" value="submission" />'."\n".
  698: 	'<input type="hidden" name="student" value="" />'."\n".
  699: 	'<input type="hidden" name="userdom" value="" />'."\n".
  700: 	'</form>'."\n";
  701:     return $jscript;
  702: }
  703: 
  704: 
  705: 
  706: # Given the score (as a number [0-1] and the weight) what is the final
  707: # point value? This function will round to the nearest tenth, third,
  708: # or quarter if one of those is within the tolerance of .00001.
  709: sub compute_points {
  710:     my ($score, $weight) = @_;
  711:     
  712:     my $tolerance = .00001;
  713:     my $points = $score * $weight;
  714: 
  715:     # Check for nearness to 1/x.
  716:     my $check_for_nearness = sub {
  717:         my ($factor) = @_;
  718:         my $num = ($points * $factor) + $tolerance;
  719:         my $floored_num = floor($num);
  720:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  721:             return $floored_num / $factor;
  722:         }
  723:         return $points;
  724:     };
  725: 
  726:     $points = $check_for_nearness->(10);
  727:     $points = $check_for_nearness->(3);
  728:     $points = $check_for_nearness->(4);
  729:     
  730:     return $points;
  731: }
  732: 
  733: #------------------ End of general use routines --------------------
  734: 
  735: #
  736: # Find most similar essay
  737: #
  738: 
  739: sub most_similar {
  740:     my ($uname,$udom,$uessay,$old_essays)=@_;
  741: 
  742: # ignore spaces and punctuation
  743: 
  744:     $uessay=~s/\W+/ /gs;
  745: 
  746: # ignore empty submissions (occuring when only files are sent)
  747: 
  748:     unless ($uessay=~/\w+/) { return ''; }
  749: 
  750: # these will be returned. Do not care if not at least 50 percent similar
  751:     my $limit=0.6;
  752:     my $sname='';
  753:     my $sdom='';
  754:     my $scrsid='';
  755:     my $sessay='';
  756: # go through all essays ...
  757:     foreach my $tkey (keys(%$old_essays)) {
  758: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  759: # ... except the same student
  760:         next if (($tname eq $uname) && ($tdom eq $udom));
  761: 	my $tessay=$old_essays->{$tkey};
  762: 	$tessay=~s/\W+/ /gs;
  763: # String similarity gives up if not even limit
  764: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  765: # Found one
  766: 	if ($tsimilar>$limit) {
  767: 	    $limit=$tsimilar;
  768: 	    $sname=$tname;
  769: 	    $sdom=$tdom;
  770: 	    $scrsid=$tcrsid;
  771: 	    $sessay=$old_essays->{$tkey};
  772: 	}
  773:     }
  774:     if ($limit>0.6) {
  775:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  776:     } else {
  777:        return ('','','','',0);
  778:     }
  779: }
  780: 
  781: #-------------------------------------------------------------------
  782: 
  783: #------------------------------------ Receipt Verification Routines
  784: #
  785: #--- Check whether a receipt number is valid.---
  786: sub verifyreceipt {
  787:     my $request  = shift;
  788: 
  789:     my $courseid = $env{'request.course.id'};
  790:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  791: 	$env{'form.receipt'};
  792:     $receipt     =~ s/[^\-\d]//g;
  793:     my ($symb)   = &get_symb($request);
  794: 
  795:     my $title.=
  796: 	'<h3><span class="LC_info">'.
  797: 	&mt('Verifying Receipt No. [_1]',$receipt).
  798: 	'</span></h3>'."\n".
  799: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  800: 	'</h4>'."\n";
  801: 
  802:     my ($string,$contents,$matches) = ('','',0);
  803:     my (undef,undef,$fullname) = &getclasslist('all','0');
  804:     
  805:     my $receiptparts=0;
  806:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  807: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  808:     my $parts=['0'];
  809:     if ($receiptparts) {
  810:         my $res_error; 
  811:         ($parts)=&response_type($symb,\$res_error);
  812:         if ($res_error) {
  813:             return &navmap_errormsg();
  814:         } 
  815:     }
  816:     
  817:     my $header = 
  818: 	&Apache::loncommon::start_data_table().
  819: 	&Apache::loncommon::start_data_table_header_row().
  820: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  821: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  822: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  823:     if ($receiptparts) {
  824: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  825:     }
  826:     $header.=
  827: 	&Apache::loncommon::end_data_table_header_row();
  828: 
  829:     foreach (sort 
  830: 	     {
  831: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  832: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  833: 		 }
  834: 		 return $a cmp $b;
  835: 	     } (keys(%$fullname))) {
  836: 	my ($uname,$udom)=split(/\:/);
  837: 	foreach my $part (@$parts) {
  838: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  839: 		$contents.=
  840: 		    &Apache::loncommon::start_data_table_row().
  841: 		    '<td>&nbsp;'."\n".
  842: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  843: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  844: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  845: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  846: 		if ($receiptparts) {
  847: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  848: 		}
  849: 		$contents.= 
  850: 		    &Apache::loncommon::end_data_table_row()."\n";
  851: 		
  852: 		$matches++;
  853: 	    }
  854: 	}
  855:     }
  856:     if ($matches == 0) {
  857:         $string = $title
  858:                  .'<p class="LC_warning">'
  859:                  .&mt('No match found for the above receipt number.')
  860:                  .'</p>';
  861:     } else {
  862: 	$string = &jscriptNform($symb).$title.
  863: 	    '<p>'.
  864: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  865: 	    '</p>'.
  866: 	    $header.
  867: 	    $contents.
  868: 	    &Apache::loncommon::end_data_table()."\n";
  869:     }
  870:     return $string.&show_grading_menu_form($symb);
  871: }
  872: 
  873: #--- This is called by a number of programs.
  874: #--- Called from the Grading Menu - View/Grade an individual student
  875: #--- Also called directly when one clicks on the subm button 
  876: #    on the problem page.
  877: sub listStudents {
  878:     my ($request) = shift;
  879: 
  880:     my ($symb) = &get_symb($request);
  881:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  882:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  883:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  884:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  885:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  886:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  887:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  888: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  889: 
  890:     my $result='<h3><span class="LC_info">&nbsp;'
  891: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  892: 	.'</span></h3>';
  893: 
  894:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  895: 
  896:     my %lt = &Apache::lonlocal::texthash (
  897: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  898: 		'single'   => 'Please select the student before clicking on the Next button.',
  899: 	     );
  900:     $request->print(<<LISTJAVASCRIPT);
  901: <script type="text/javascript" language="javascript">
  902:     function checkSelect(checkBox) {
  903: 	var ctr=0;
  904: 	var sense="";
  905: 	if (checkBox.length > 1) {
  906: 	    for (var i=0; i<checkBox.length; i++) {
  907: 		if (checkBox[i].checked) {
  908: 		    ctr++;
  909: 		}
  910: 	    }
  911: 	    sense = '$lt{'multiple'}';
  912: 	} else {
  913: 	    if (checkBox.checked) {
  914: 		ctr = 1;
  915: 	    }
  916: 	    sense = '$lt{'single'}';
  917: 	}
  918: 	if (ctr == 0) {
  919: 	    alert(sense);
  920: 	    return false;
  921: 	}
  922: 	document.gradesub.submit();
  923:     }
  924: 
  925:     function reLoadList(formname) {
  926: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  927: 	formname.command.value = 'submission';
  928: 	formname.submit();
  929:     }
  930: </script>
  931: LISTJAVASCRIPT
  932: 
  933:     &commonJSfunctions($request);
  934:     $request->print($result);
  935: 
  936:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  937:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  938:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  939: 	"\n".$table;
  940: 	
  941:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  943:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  944:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  945:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  946:                   .&Apache::lonhtmlcommon::row_closure();
  947:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  948:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  949:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  950:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  951:                   .&Apache::lonhtmlcommon::row_closure();
  952: 
  953:     my $submission_options;
  954:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  955: 	$submission_options.=
  956: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  957:     }
  958:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  959:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  960:     $env{'form.Status'} = $saveStatus;
  961:     $submission_options.=
  962:         '<span class="LC_nobreak">'.
  963:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
  964:         &mt('last submission only').' </label></span>'."\n".
  965:         '<span class="LC_nobreak">'.
  966:         '<label><input type="radio" name="lastSub" value="last" /> '.
  967:         &mt('last submission &amp; parts info').' </label></span>'."\n".
  968:         '<span class="LC_nobreak">'.
  969:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
  970:         &mt('by dates and submissions').'</label></span>'."\n".
  971:         '<span class="LC_nobreak">'.
  972:         '<label><input type="radio" name="lastSub" value="all" /> '.
  973:         &mt('all details').'</label></span>';
  974:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  975:                   .$submission_options
  976:                   .&Apache::lonhtmlcommon::row_closure();
  977: 
  978:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  979:                   .'<select name="increment">'
  980:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  981:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  982:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  983:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  984:                   .'</select>'
  985:                   .&Apache::lonhtmlcommon::row_closure();
  986: 
  987:     $gradeTable .= 
  988:         &build_section_inputs().
  989: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  990: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  991: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  992: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  993: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  994: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  995: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  996: 
  997:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  998: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  999:     } else {
 1000:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
 1001:                       .&Apache::lonhtmlcommon::StatusOptions(
 1002:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
 1003:                       .&Apache::lonhtmlcommon::row_closure();
 1004:     }
 1005: 
 1006:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
 1007:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
 1008:                   .&Apache::lonhtmlcommon::row_closure(1)
 1009:                   .&Apache::lonhtmlcommon::end_pick_box();
 1010: 
 1011:     $gradeTable .= '<p>'
 1012:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
 1013:                   .'<input type="hidden" name="command" value="processGroup" />'
 1014:                   .'</p>';
 1015: 
 1016: # checkall buttons
 1017:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1018:     $gradeTable.='<input type="button" '."\n".
 1019:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1020:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
 1021:     $gradeTable.=&check_buttons();
 1022:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1023:     $gradeTable.= &Apache::loncommon::start_data_table().
 1024: 	&Apache::loncommon::start_data_table_header_row();
 1025:     my $loop = 0;
 1026:     while ($loop < 2) {
 1027: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1028: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1029: 	if ($env{'form.showgrading'} eq 'yes' 
 1030: 	    && $submitonly ne 'queued'
 1031: 	    && $submitonly ne 'all') {
 1032: 	    foreach my $part (sort(@$partlist)) {
 1033: 		my $display_part=
 1034: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1035: 		$gradeTable.=
 1036: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1037: 	    }
 1038: 	} elsif ($submitonly eq 'queued') {
 1039: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1040: 	}
 1041: 	$loop++;
 1042: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1043:     }
 1044:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1045: 
 1046:     my $ctr = 0;
 1047:     foreach my $student (sort 
 1048: 			 {
 1049: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1050: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1051: 			     }
 1052: 			     return $a cmp $b;
 1053: 			 }
 1054: 			 (keys(%$fullname))) {
 1055: 	my ($uname,$udom) = split(/:/,$student);
 1056: 
 1057: 	my %status = ();
 1058: 
 1059: 	if ($submitonly eq 'queued') {
 1060: 	    my %queue_status = 
 1061: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1062: 							$udom,$uname);
 1063: 	    next if (!defined($queue_status{'gradingqueue'}));
 1064: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1065: 	}
 1066: 
 1067: 	if ($env{'form.showgrading'} eq 'yes' 
 1068: 	    && $submitonly ne 'queued'
 1069: 	    && $submitonly ne 'all') {
 1070: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1071: 	    my $submitted = 0;
 1072: 	    my $graded = 0;
 1073: 	    my $incorrect = 0;
 1074: 	    foreach (keys(%status)) {
 1075: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1076: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1077: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1078: 		
 1079: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1080: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1081: 		    $submitted = 0;
 1082: 		    my ($part)=split(/\./,$partid);
 1083: 		    $gradeTable.='<input type="hidden" name="'.
 1084: 			$student.':'.$part.':submitted_by" value="'.
 1085: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1086: 		}
 1087: 	    }
 1088: 	    
 1089: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1090: 				     $submitonly eq 'incorrect' ||
 1091: 				     $submitonly eq 'graded'));
 1092: 	    next if (!$graded && ($submitonly eq 'graded'));
 1093: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1094: 	}
 1095: 
 1096: 	$ctr++;
 1097: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1098:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1099: 	if ( $perm{'vgr'} eq 'F' ) {
 1100: 	    if ($ctr%2 ==1) {
 1101: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1102: 	    }
 1103: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1104:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1105:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1106: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1107: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1108: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1109: 
 1110: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1111: 		foreach (sort(keys(%status))) {
 1112: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1113: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1114: 		}
 1115: 	    }
 1116: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1117: 	    if ($ctr%2 ==0) {
 1118: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1119: 	    }
 1120: 	}
 1121:     }
 1122:     if ($ctr%2 ==1) {
 1123: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1124: 	    if ($env{'form.showgrading'} eq 'yes' 
 1125: 		&& $submitonly ne 'queued'
 1126: 		&& $submitonly ne 'all') {
 1127: 		foreach (@$partlist) {
 1128: 		    $gradeTable.='<td>&nbsp;</td>';
 1129: 		}
 1130: 	    } elsif ($submitonly eq 'queued') {
 1131: 		$gradeTable.='<td>&nbsp;</td>';
 1132: 	    }
 1133: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1134:     }
 1135: 
 1136:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1137:         '<input type="button" '.
 1138:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
 1139:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1140:     if ($ctr == 0) {
 1141: 	my $num_students=(scalar(keys(%$fullname)));
 1142: 	if ($num_students eq 0) {
 1143: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1144: 	} else {
 1145: 	    my $submissions='submissions';
 1146: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1147: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1148: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1149: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1150: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1151: 		    $num_students).
 1152: 		'</span><br />';
 1153: 	}
 1154:     } elsif ($ctr == 1) {
 1155: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1156:     }
 1157:     $gradeTable.=&show_grading_menu_form($symb);
 1158:     $request->print($gradeTable);
 1159:     return '';
 1160: }
 1161: 
 1162: #---- Called from the listStudents routine
 1163: 
 1164: sub check_script {
 1165:     my ($form, $type)=@_;
 1166:     my $chkallscript='<script type="text/javascript">
 1167:     function checkall() {
 1168:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1169:             ele = document.forms.'.$form.'.elements[i];
 1170:             if (ele.name == "'.$type.'") {
 1171:             document.forms.'.$form.'.elements[i].checked=true;
 1172:                                        }
 1173:         }
 1174:     }
 1175: 
 1176:     function checksec() {
 1177:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1178:             ele = document.forms.'.$form.'.elements[i];
 1179:            string = document.forms.'.$form.'.chksec.value;
 1180:            if
 1181:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1182:               document.forms.'.$form.'.elements[i].checked=true;
 1183:             }
 1184:         }
 1185:     }
 1186: 
 1187: 
 1188:     function uncheckall() {
 1189:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1190:             ele = document.forms.'.$form.'.elements[i];
 1191:             if (ele.name == "'.$type.'") {
 1192:             document.forms.'.$form.'.elements[i].checked=false;
 1193:                                        }
 1194:         }
 1195:     }
 1196: 
 1197: </script>'."\n";
 1198:     return $chkallscript;
 1199: }
 1200: 
 1201: sub check_buttons {
 1202:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1203:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1204:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1205:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1206:     return $buttons;
 1207: }
 1208: 
 1209: #     Displays the submissions for one student or a group of students
 1210: sub processGroup {
 1211:     my ($request)  = shift;
 1212:     my $ctr        = 0;
 1213:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1214:     my $total      = scalar(@stuchecked)-1;
 1215: 
 1216:     foreach my $student (@stuchecked) {
 1217: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1218: 	$env{'form.student'}        = $uname;
 1219: 	$env{'form.userdom'}        = $udom;
 1220: 	$env{'form.fullname'}       = $fullname;
 1221: 	&submission($request,$ctr,$total);
 1222: 	$ctr++;
 1223:     }
 1224:     return '';
 1225: }
 1226: 
 1227: #------------------------------------------------------------------------------------
 1228: #
 1229: #-------------------------- Next few routines handles grading by student, essentially
 1230: #                           handles essay response type problem/part
 1231: #
 1232: #--- Javascript to handle the submission page functionality ---
 1233: sub sub_page_js {
 1234:     my $request = shift;
 1235: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1236:     $request->print(<<SUBJAVASCRIPT);
 1237: <script type="text/javascript" language="javascript">
 1238:     function updateRadio(formname,id,weight) {
 1239: 	var gradeBox = formname["GD_BOX"+id];
 1240: 	var radioButton = formname["RADVAL"+id];
 1241: 	var oldpts = formname["oldpts"+id].value;
 1242: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1243: 	gradeBox.value = pts;
 1244: 	var resetbox = false;
 1245: 	if (isNaN(pts) || pts < 0) {
 1246: 	    alert("$alertmsg"+pts);
 1247: 	    for (var i=0; i<radioButton.length; i++) {
 1248: 		if (radioButton[i].checked) {
 1249: 		    gradeBox.value = i;
 1250: 		    resetbox = true;
 1251: 		}
 1252: 	    }
 1253: 	    if (!resetbox) {
 1254: 		formtextbox.value = "";
 1255: 	    }
 1256: 	    return;
 1257: 	}
 1258: 
 1259: 	if (pts > weight) {
 1260: 	    var resp = confirm("You entered a value ("+pts+
 1261: 			       ") greater than the weight for the part. Accept?");
 1262: 	    if (resp == false) {
 1263: 		gradeBox.value = oldpts;
 1264: 		return;
 1265: 	    }
 1266: 	}
 1267: 
 1268: 	for (var i=0; i<radioButton.length; i++) {
 1269: 	    radioButton[i].checked=false;
 1270: 	    if (pts == i && pts != "") {
 1271: 		radioButton[i].checked=true;
 1272: 	    }
 1273: 	}
 1274: 	updateSelect(formname,id);
 1275: 	formname["stores"+id].value = "0";
 1276:     }
 1277: 
 1278:     function writeBox(formname,id,pts) {
 1279: 	var gradeBox = formname["GD_BOX"+id];
 1280: 	if (checkSolved(formname,id) == 'update') {
 1281: 	    gradeBox.value = pts;
 1282: 	} else {
 1283: 	    var oldpts = formname["oldpts"+id].value;
 1284: 	    gradeBox.value = oldpts;
 1285: 	    var radioButton = formname["RADVAL"+id];
 1286: 	    for (var i=0; i<radioButton.length; i++) {
 1287: 		radioButton[i].checked=false;
 1288: 		if (i == oldpts) {
 1289: 		    radioButton[i].checked=true;
 1290: 		}
 1291: 	    }
 1292: 	}
 1293: 	formname["stores"+id].value = "0";
 1294: 	updateSelect(formname,id);
 1295: 	return;
 1296:     }
 1297: 
 1298:     function clearRadBox(formname,id) {
 1299: 	if (checkSolved(formname,id) == 'noupdate') {
 1300: 	    updateSelect(formname,id);
 1301: 	    return;
 1302: 	}
 1303: 	gradeSelect = formname["GD_SEL"+id];
 1304: 	for (var i=0; i<gradeSelect.length; i++) {
 1305: 	    if (gradeSelect[i].selected) {
 1306: 		var selectx=i;
 1307: 	    }
 1308: 	}
 1309: 	var stores = formname["stores"+id];
 1310: 	if (selectx == stores.value) { return };
 1311: 	var gradeBox = formname["GD_BOX"+id];
 1312: 	gradeBox.value = "";
 1313: 	var radioButton = formname["RADVAL"+id];
 1314: 	for (var i=0; i<radioButton.length; i++) {
 1315: 	    radioButton[i].checked=false;
 1316: 	}
 1317: 	stores.value = selectx;
 1318:     }
 1319: 
 1320:     function checkSolved(formname,id) {
 1321: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1322: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1323: 	    if (!reply) {return "noupdate";}
 1324: 	    formname.overRideScore.value = 'yes';
 1325: 	}
 1326: 	return "update";
 1327:     }
 1328: 
 1329:     function updateSelect(formname,id) {
 1330: 	formname["GD_SEL"+id][0].selected = true;
 1331: 	return;
 1332:     }
 1333: 
 1334: //=========== Check that a point is assigned for all the parts  ============
 1335:     function checksubmit(formname,val,total,parttot) {
 1336: 	formname.gradeOpt.value = val;
 1337: 	if (val == "Save & Next") {
 1338: 	    for (i=0;i<=total;i++) {
 1339: 		for (j=0;j<parttot;j++) {
 1340: 		    var partid = formname["partid"+i+"_"+j].value;
 1341: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1342: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1343: 			if (points == "") {
 1344: 			    var name = formname["name"+i].value;
 1345: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1346: 			    var resp = confirm("You did not assign a score for "+studentID+
 1347: 					       ", part "+partid+". Continue?");
 1348: 			    if (resp == false) {
 1349: 				formname["GD_BOX"+i+"_"+partid].focus();
 1350: 				return false;
 1351: 			    }
 1352: 			}
 1353: 		    }
 1354: 		    
 1355: 		}
 1356: 	    }
 1357: 	    
 1358: 	}
 1359: 	if (val == "Grade Student") {
 1360: 	    formname.showgrading.value = "yes";
 1361: 	    if (formname.Status.value == "") {
 1362: 		formname.Status.value = "Active";
 1363: 	    }
 1364: 	    formname.studentNo.value = total;
 1365: 	}
 1366: 	formname.submit();
 1367:     }
 1368: 
 1369: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1370:     function checkSubmitPage(formname,total) {
 1371: 	noscore = new Array(100);
 1372: 	var ptr = 0;
 1373: 	for (i=1;i<total;i++) {
 1374: 	    var partid = formname["q_"+i].value;
 1375: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1376: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1377: 		var status = formname["solved"+i+"_"+partid].value;
 1378: 		if (points == "" && status != "correct_by_student") {
 1379: 		    noscore[ptr] = i;
 1380: 		    ptr++;
 1381: 		}
 1382: 	    }
 1383: 	}
 1384: 	if (ptr != 0) {
 1385: 	    var sense = ptr == 1 ? ": " : "s: ";
 1386: 	    var prolist = "";
 1387: 	    if (ptr == 1) {
 1388: 		prolist = noscore[0];
 1389: 	    } else {
 1390: 		var i = 0;
 1391: 		while (i < ptr-1) {
 1392: 		    prolist += noscore[i]+", ";
 1393: 		    i++;
 1394: 		}
 1395: 		prolist += "and "+noscore[i];
 1396: 	    }
 1397: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1398: 	    if (resp == false) {
 1399: 		return false;
 1400: 	    }
 1401: 	}
 1402: 
 1403: 	formname.submit();
 1404:     }
 1405: </script>
 1406: SUBJAVASCRIPT
 1407: }
 1408: 
 1409: #--- javascript for essay type problem --
 1410: sub sub_page_kw_js {
 1411:     my $request = shift;
 1412:     my $iconpath = $request->dir_config('lonIconsURL');
 1413:     &commonJSfunctions($request);
 1414: 
 1415:     my $inner_js_msg_central=<<INNERJS;
 1416:     <script text="text/javascript">
 1417:     function checkInput() {
 1418:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1419:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1420:       var usrctr = document.msgcenter.usrctr.value;
 1421:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1422:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1423: 
 1424:       var msgchk = "";
 1425:       if (document.msgcenter.subchk.checked) {
 1426:          msgchk = "msgsub,";
 1427:       }
 1428:       var includemsg = 0;
 1429:       for (var i=1; i<=nmsg; i++) {
 1430:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1431:           var frmmsg = document.msgcenter["msg"+i];
 1432:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1433:           var showflg = opener.document.SCORE["shownOnce"+i];
 1434:           showflg.value = "1";
 1435:           var chkbox = document.msgcenter["msgn"+i];
 1436:           if (chkbox.checked) {
 1437:              msgchk += "savemsg"+i+",";
 1438:              includemsg = 1;
 1439:           }
 1440:       }
 1441:       if (document.msgcenter.newmsgchk.checked) {
 1442:          msgchk += "newmsg"+usrctr;
 1443:          includemsg = 1;
 1444:       }
 1445:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1446:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1447:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1448:       includemsg.value = msgchk;
 1449: 
 1450:       self.close()
 1451: 
 1452:     }
 1453:     </script>
 1454: INNERJS
 1455: 
 1456:     my $inner_js_highlight_central=<<INNERJS;
 1457:  <script type="text/javascript">
 1458:     function updateChoice(flag) {
 1459:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1460:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1461:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1462:       opener.document.SCORE.refresh.value = "on";
 1463:       if (opener.document.SCORE.keywords.value!=""){
 1464:          opener.document.SCORE.submit();
 1465:       }
 1466:       self.close()
 1467:     }
 1468: </script>
 1469: INNERJS
 1470: 
 1471:     my $start_page_msg_central = 
 1472:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1473: 				       {'js_ready'  => 1,
 1474: 					'only_body' => 1,
 1475: 					'bgcolor'   =>'#FFFFFF',});
 1476:     my $end_page_msg_central = 
 1477: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1478: 
 1479: 
 1480:     my $start_page_highlight_central = 
 1481:         &Apache::loncommon::start_page('Highlight Central',
 1482: 				       $inner_js_highlight_central,
 1483: 				       {'js_ready'  => 1,
 1484: 					'only_body' => 1,
 1485: 					'bgcolor'   =>'#FFFFFF',});
 1486:     my $end_page_highlight_central = 
 1487: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1488: 
 1489:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1490:     $docopen=~s/^document\.//;
 1491:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1492:     $request->print(<<SUBJAVASCRIPT);
 1493: <script type="text/javascript" language="javascript">
 1494: 
 1495: //===================== Show list of keywords ====================
 1496:   function keywords(formname) {
 1497:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1498:     if (nret==null) return;
 1499:     formname.keywords.value = nret;
 1500: 
 1501:     if (formname.keywords.value != "") {
 1502: 	formname.refresh.value = "on";
 1503: 	formname.submit();
 1504:     }
 1505:     return;
 1506:   }
 1507: 
 1508: //===================== Script to view submitted by ==================
 1509:   function viewSubmitter(submitter) {
 1510:     document.SCORE.refresh.value = "on";
 1511:     document.SCORE.NCT.value = "1";
 1512:     document.SCORE.unamedom0.value = submitter;
 1513:     document.SCORE.submit();
 1514:     return;
 1515:   }
 1516: 
 1517: //===================== Script to add keyword(s) ==================
 1518:   function getSel() {
 1519:     if (document.getSelection) txt = document.getSelection();
 1520:     else if (document.selection) txt = document.selection.createRange().text;
 1521:     else return;
 1522:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1523:     if (cleantxt=="") {
 1524: 	alert("$alertmsg");
 1525: 	return;
 1526:     }
 1527:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1528:     if (nret==null) return;
 1529:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1530:     if (document.SCORE.keywords.value != "") {
 1531: 	document.SCORE.refresh.value = "on";
 1532: 	document.SCORE.submit();
 1533:     }
 1534:     return;
 1535:   }
 1536: 
 1537: //====================== Script for composing message ==============
 1538:    // preload images
 1539:    img1 = new Image();
 1540:    img1.src = "$iconpath/mailbkgrd.gif";
 1541:    img2 = new Image();
 1542:    img2.src = "$iconpath/mailto.gif";
 1543: 
 1544:   function msgCenter(msgform,usrctr,fullname) {
 1545:     var Nmsg  = msgform.savemsgN.value;
 1546:     savedMsgHeader(Nmsg,usrctr,fullname);
 1547:     var subject = msgform.msgsub.value;
 1548:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1549:     re = /msgsub/;
 1550:     var shwsel = "";
 1551:     if (re.test(msgchk)) { shwsel = "checked" }
 1552:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1553:     displaySubject(checkEntities(subject),shwsel);
 1554:     for (var i=1; i<=Nmsg; i++) {
 1555: 	var testmsg = "savemsg"+i+",";
 1556: 	re = new RegExp(testmsg,"g");
 1557: 	shwsel = "";
 1558: 	if (re.test(msgchk)) { shwsel = "checked" }
 1559: 	var message = document.SCORE["savemsg"+i].value;
 1560: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1561: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1562: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1563:     }
 1564:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1565:     shwsel = "";
 1566:     re = /newmsg/;
 1567:     if (re.test(msgchk)) { shwsel = "checked" }
 1568:     newMsg(newmsg,shwsel);
 1569:     msgTail(); 
 1570:     return;
 1571:   }
 1572: 
 1573:   function checkEntities(strx) {
 1574:     if (strx.length == 0) return strx;
 1575:     var orgStr = ["&", "<", ">", '"']; 
 1576:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1577:     var counter = 0;
 1578:     while (counter < 4) {
 1579: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1580: 	counter++;
 1581:     }
 1582:     return strx;
 1583:   }
 1584: 
 1585:   function strReplace(strx, orgStr, newStr) {
 1586:     return strx.split(orgStr).join(newStr);
 1587:   }
 1588: 
 1589:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1590:     var height = 70*Nmsg+250;
 1591:     var scrollbar = "no";
 1592:     if (height > 600) {
 1593: 	height = 600;
 1594: 	scrollbar = "yes";
 1595:     }
 1596:     var xpos = (screen.width-600)/2;
 1597:     xpos = (xpos < 0) ? '0' : xpos;
 1598:     var ypos = (screen.height-height)/2-30;
 1599:     ypos = (ypos < 0) ? '0' : ypos;
 1600: 
 1601:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1602:     pWin.focus();
 1603:     pDoc = pWin.document;
 1604:     pDoc.$docopen;
 1605:     pDoc.write('$start_page_msg_central');
 1606: 
 1607:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1608:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1609:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1610: 
 1611:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1612:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1613:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1614: }
 1615:     function displaySubject(msg,shwsel) {
 1616:     pDoc = pWin.document;
 1617:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1618:     pDoc.write("<td>Subject<\\/td>");
 1619:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1620:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1621: }
 1622: 
 1623:   function displaySavedMsg(ctr,msg,shwsel) {
 1624:     pDoc = pWin.document;
 1625:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1626:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1627:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1628:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1629: }
 1630: 
 1631:   function newMsg(newmsg,shwsel) {
 1632:     pDoc = pWin.document;
 1633:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1634:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1635:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1636:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1637: }
 1638: 
 1639:   function msgTail() {
 1640:     pDoc = pWin.document;
 1641:     pDoc.write("<\\/table>");
 1642:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1643:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1644:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1645:     pDoc.write("<\\/form>");
 1646:     pDoc.write('$end_page_msg_central');
 1647:     pDoc.close();
 1648: }
 1649: 
 1650: //====================== Script for keyword highlight options ==============
 1651:   function kwhighlight() {
 1652:     var kwclr    = document.SCORE.kwclr.value;
 1653:     var kwsize   = document.SCORE.kwsize.value;
 1654:     var kwstyle  = document.SCORE.kwstyle.value;
 1655:     var redsel = "";
 1656:     var grnsel = "";
 1657:     var blusel = "";
 1658:     if (kwclr=="red")   {var redsel="checked"};
 1659:     if (kwclr=="green") {var grnsel="checked"};
 1660:     if (kwclr=="blue")  {var blusel="checked"};
 1661:     var sznsel = "";
 1662:     var sz1sel = "";
 1663:     var sz2sel = "";
 1664:     if (kwsize=="0")  {var sznsel="checked"};
 1665:     if (kwsize=="+1") {var sz1sel="checked"};
 1666:     if (kwsize=="+2") {var sz2sel="checked"};
 1667:     var synsel = "";
 1668:     var syisel = "";
 1669:     var sybsel = "";
 1670:     if (kwstyle=="")    {var synsel="checked"};
 1671:     if (kwstyle=="<i>") {var syisel="checked"};
 1672:     if (kwstyle=="<b>") {var sybsel="checked"};
 1673:     highlightCentral();
 1674:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1675:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1676:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1677:     highlightend();
 1678:     return;
 1679:   }
 1680: 
 1681:   function highlightCentral() {
 1682: //    if (window.hwdWin) window.hwdWin.close();
 1683:     var xpos = (screen.width-400)/2;
 1684:     xpos = (xpos < 0) ? '0' : xpos;
 1685:     var ypos = (screen.height-330)/2-30;
 1686:     ypos = (ypos < 0) ? '0' : ypos;
 1687: 
 1688:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1689:     hwdWin.focus();
 1690:     var hDoc = hwdWin.document;
 1691:     hDoc.$docopen;
 1692:     hDoc.write('$start_page_highlight_central');
 1693:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1694:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1695: 
 1696:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1697:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1698:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1699:   }
 1700: 
 1701:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1702:     var hDoc = hwdWin.document;
 1703:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1704:     hDoc.write("<td align=\\"left\\">");
 1705:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1706:     hDoc.write("<td align=\\"left\\">");
 1707:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1708:     hDoc.write("<td align=\\"left\\">");
 1709:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1710:     hDoc.write("<\\/tr>");
 1711:   }
 1712: 
 1713:   function highlightend() { 
 1714:     var hDoc = hwdWin.document;
 1715:     hDoc.write("<\\/table>");
 1716:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1717:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1718:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
 1719:     hDoc.write("<\\/form>");
 1720:     hDoc.write('$end_page_highlight_central');
 1721:     hDoc.close();
 1722:   }
 1723: 
 1724: </script>
 1725: SUBJAVASCRIPT
 1726: }
 1727: 
 1728: sub get_increment {
 1729:     my $increment = $env{'form.increment'};
 1730:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1731:         $increment != .1) {
 1732:         $increment = 1;
 1733:     }
 1734:     return $increment;
 1735: }
 1736: 
 1737: sub gradeBox_start {
 1738:     return (
 1739:         &Apache::loncommon::start_data_table()
 1740:        .&Apache::loncommon::start_data_table_header_row()
 1741:        .'<th>'.&mt('Part').'</th>'
 1742:        .'<th>'.&mt('Points').'</th>'
 1743:        .'<th>&nbsp;</th>'
 1744:        .'<th>'.&mt('Assign Grade').'</th>'
 1745:        .'<th>'.&mt('Weight').'</th>'
 1746:        .'<th>'.&mt('Grade Status').'</th>'
 1747:        .&Apache::loncommon::end_data_table_header_row()
 1748:     );
 1749: }
 1750: 
 1751: sub gradeBox_end {
 1752:     return (
 1753:         &Apache::loncommon::end_data_table()
 1754:     );
 1755: }
 1756: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1757: sub gradeBox {
 1758:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1759:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1760: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1761:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1762:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1763:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1764:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1765:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1766: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1767:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1768:     my $display_part= &get_display_part($partid,$symb);
 1769:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1770: 				       [$partid]);
 1771:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1772:     if ($last_resets{$partid}) {
 1773:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1774:     }
 1775:     $result.=&Apache::loncommon::start_data_table_row();
 1776:     my $ctr = 0;
 1777:     my $thisweight = 0;
 1778:     my $increment = &get_increment();
 1779: 
 1780:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1781:     while ($thisweight<=$wgt) {
 1782: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1783:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1784: 	    $thisweight.')" value="'.$thisweight.'" '.
 1785: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1786: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1787:         $thisweight += $increment;
 1788: 	$ctr++;
 1789:     }
 1790:     $radio.='</tr></table>';
 1791: 
 1792:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1793: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1794: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1795: 	$wgt.')" /></td>'."\n";
 1796:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1797: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1798: 	' </td>'."\n";
 1799:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1800: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1801:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1802: 	$line.='<option></option>'.
 1803: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1804:     } else {
 1805: 	$line.='<option selected="selected"></option>'.
 1806: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1807:     }
 1808:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1809: 
 1810: 
 1811: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1812:     $result .= 
 1813: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1814:     $result.=&Apache::loncommon::end_data_table_row();
 1815:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1816: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1817: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1818: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1819:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1820:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1821:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1822:         $aggtries.'" />'."\n";
 1823:     my $res_error;
 1824:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1825:     if ($res_error) {
 1826:         return &navmap_errormsg();
 1827:     }
 1828:     return $result;
 1829: }
 1830: 
 1831: sub handback_box {
 1832:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1833:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1834:     my (@respids);
 1835:      my @part_response_id = &flatten_responseType($responseType);
 1836:     foreach my $part_response_id (@part_response_id) {
 1837:     	my ($part,$resp) = @{ $part_response_id };
 1838:         if ($part eq $partid) {
 1839:             push(@respids,$resp);
 1840:         }
 1841:     }
 1842:     my $result;
 1843:     foreach my $respid (@respids) {
 1844: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1845: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1846: 	next if (!@$files);
 1847: 	my $file_counter = 1;
 1848: 	foreach my $file (@$files) {
 1849: 	    if ($file =~ /\/portfolio\//) {
 1850:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1851:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1852:     	        $file_disp = "$name.$ext";
 1853:     	        $file = $file_path.$file_disp;
 1854:     	        $result.=&mt('Return commented version of [_1] to student.',
 1855:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1856:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1857:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1858:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1859:     	        $file_counter++;
 1860: 	    }
 1861: 	}
 1862:     }
 1863:     return $result;    
 1864: }
 1865: 
 1866: sub show_problem {
 1867:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1868:     my $rendered;
 1869:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1870:     &Apache::lonxml::remember_problem_counter();
 1871:     if ($mode eq 'both' or $mode eq 'text') {
 1872: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1873: 						       $env{'request.course.id'},
 1874: 						       undef,\%form);
 1875:     }
 1876:     if ($removeform) {
 1877: 	$rendered=~s|<form(.*?)>||g;
 1878: 	$rendered=~s|</form>||g;
 1879: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1880:     }
 1881:     my $companswer;
 1882:     if ($mode eq 'both' or $mode eq 'answer') {
 1883: 	&Apache::lonxml::restore_problem_counter();
 1884: 	$companswer=
 1885: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1886: 						    $env{'request.course.id'},
 1887: 						    %form);
 1888:     }
 1889:     if ($removeform) {
 1890: 	$companswer=~s|<form(.*?)>||g;
 1891: 	$companswer=~s|</form>||g;
 1892: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1893:     }
 1894:     $rendered=
 1895:         '<div class="LC_Box">'
 1896:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1897:        .$rendered
 1898:        .'</div>';
 1899:     $companswer=
 1900:         '<div class="LC_Box">'
 1901:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1902:        .$companswer
 1903:        .'</div>';
 1904:     my $result;
 1905:     if ($mode eq 'both') {
 1906:         $result=$rendered.$companswer;
 1907:     } elsif ($mode eq 'text') {
 1908:         $result=$rendered;
 1909:     } elsif ($mode eq 'answer') {
 1910:         $result=$companswer;
 1911:     }
 1912:     return $result;
 1913: }
 1914: 
 1915: sub files_exist {
 1916:     my ($r, $symb) = @_;
 1917:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1918: 
 1919:     foreach my $student (@students) {
 1920:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1921:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1922: 					      $udom,$uname);
 1923:         my ($string,$timestamp)= &get_last_submission(\%record);
 1924:         foreach my $submission (@$string) {
 1925:             my ($partid,$respid) =
 1926: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1927:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1928: 					   \%record);
 1929:             return 1 if (@$files);
 1930:         }
 1931:     }
 1932:     return 0;
 1933: }
 1934: 
 1935: sub download_all_link {
 1936:     my ($r,$symb) = @_;
 1937:     my $all_students = 
 1938: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1939: 
 1940:     my $parts =
 1941: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1942: 
 1943:     my $identifier = &Apache::loncommon::get_cgi_id();
 1944:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1945:                              'cgi.'.$identifier.'.symb' => $symb,
 1946:                              'cgi.'.$identifier.'.parts' => $parts,});
 1947:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1948: 	      &mt('Download All Submitted Documents').'</a>');
 1949:     return
 1950: }
 1951: 
 1952: sub build_section_inputs {
 1953:     my $section_inputs;
 1954:     if ($env{'form.section'} eq '') {
 1955:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1956:     } else {
 1957:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1958:         foreach my $section (@sections) {
 1959:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1960:         }
 1961:     }
 1962:     return $section_inputs;
 1963: }
 1964: 
 1965: # --------------------------- show submissions of a student, option to grade 
 1966: sub submission {
 1967:     my ($request,$counter,$total) = @_;
 1968:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1969:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1970:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1971:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1972:     my $symb = &get_symb($request); 
 1973:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1974: 
 1975:     if (!&canview($usec)) {
 1976: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1977: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1978: 			$env{'request.course.id'}.')</span>');
 1979: 	$request->print(&show_grading_menu_form($symb));
 1980: 	return;
 1981:     }
 1982: 
 1983:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1984:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1985:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1986:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1987:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1988: 	'" src="'.$request->dir_config('lonIconsURL').
 1989: 	'/check.gif" height="16" border="0" />';
 1990: 
 1991:     my %old_essays;
 1992:     # header info
 1993:     if ($counter == 0) {
 1994: 	&sub_page_js($request);
 1995: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1996: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1997: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1998: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1999: 	    &download_all_link($request, $symb);
 2000: 	}
 2001: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2002: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2003: 
 2004: 	# option to display problem, only once else it cause problems 
 2005:         # with the form later since the problem has a form.
 2006: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2007: 	    my $mode;
 2008: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2009: 		$mode='both';
 2010: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2011: 		$mode='text';
 2012: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2013: 		$mode='answer';
 2014: 	    }
 2015: 	    &Apache::lonxml::clear_problem_counter();
 2016: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2017: 	}
 2018: 
 2019: 	# kwclr is the only variable that is guaranteed to be non blank 
 2020:         # if this subroutine has been called once.
 2021: 	my %keyhash = ();
 2022: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2023: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2024: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2025: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2026: 
 2027: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2028: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2029: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2030: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2031: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2032: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2033: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2034: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2035: 	}
 2036: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2037: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2038: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2039: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2040: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2041: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2042: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2043: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2044: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2045: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2046: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2047: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2048: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2049: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2050: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2051: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2052: 			&build_section_inputs().
 2053: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2054: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2055: 			'<input type="hidden" name="NCT"'.
 2056: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2057: 	if ($env{'form.handgrade'} eq 'yes') {
 2058: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2059: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2060: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2061: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2062: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2063: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2064: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2065: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2066: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2067: 	    }
 2068: 	}
 2069: 	
 2070: 	my ($cts,$prnmsg) = (1,'');
 2071: 	while ($cts <= $env{'form.savemsgN'}) {
 2072: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2073: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2074: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2075: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2076: 		'" />'."\n".
 2077: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2078: 	    $cts++;
 2079: 	}
 2080: 	$request->print($prnmsg);
 2081: 
 2082: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2083: #
 2084: # Print out the keyword options line
 2085: #
 2086: 	    $request->print(<<KEYWORDS);
 2087: &nbsp;<b>Keyword Options:</b>&nbsp;
 2088: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2089: <a href="#" onmousedown="javascript:getSel(); return false"
 2090:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2091: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2092: KEYWORDS
 2093: #
 2094: # Load the other essays for similarity check
 2095: #
 2096:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2097: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2098: 	    $apath=&escape($apath);
 2099: 	    $apath=~s/\W/\_/gs;
 2100: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2101:         }
 2102:     }
 2103: 
 2104: # This is where output for one specific student would start
 2105:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
 2106:     $request->print(
 2107:         "\n\n"
 2108:        .'<div class="LC_grade_show_user'.$add_class.'">'
 2109:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
 2110:        ."\n"
 2111:     );
 2112: 
 2113:     # Show additional functions if allowed
 2114:     if ($perm{'vgr'}) {
 2115:         $request->print(
 2116:             &Apache::loncommon::track_student_link(
 2117:                 &mt('View recent activity'),
 2118:                 $uname,$udom,'check')
 2119:            .' '
 2120:         );
 2121:     }
 2122:     if ($perm{'opa'}) {
 2123:         $request->print(
 2124:             &Apache::loncommon::pprmlink(
 2125:                 &mt('Set/Change parameters'),
 2126:                 $uname,$udom,$symb,'check'));
 2127:     }
 2128: 
 2129:     # Show Problem
 2130:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2131: 	my $mode;
 2132: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2133: 	    $mode='both';
 2134: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2135: 	    $mode='text';
 2136: 	} elsif ($env{'form.vAns'} eq 'all') {
 2137: 	    $mode='answer';
 2138: 	}
 2139: 	&Apache::lonxml::clear_problem_counter();
 2140: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2141:     }
 2142: 
 2143:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2144:     my $res_error;
 2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2146:     if ($res_error) {
 2147:         $request->print(&navmap_errormsg());
 2148:         return;
 2149:     }
 2150: 
 2151:     # Display student info
 2152:     $request->print(($counter == 0 ? '' : '<br />'));
 2153: 
 2154:     my $result='<div class="LC_Box">'
 2155:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2156:     $result.='<input type="hidden" name="name'.$counter.
 2157:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2158:     if ($env{'form.handgrade'} eq 'no') {
 2159:         $result.='<p class="LC_info">'
 2160:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2161:                 ."</p>\n";
 2162:     }
 2163: 
 2164:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2165:     my $fullname;
 2166:     my $col_fullnames = [];
 2167:     if ($env{'form.handgrade'} eq 'yes') {
 2168: 	(my $sub_result,$fullname,$col_fullnames)=
 2169: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2170: 				 $counter);
 2171: 	$result.=$sub_result;
 2172:     }
 2173:     $request->print($result."\n");
 2174: 
 2175:     # print student answer/submission
 2176:     # Options are (1) Handgraded submission only
 2177:     #             (2) Last submission, includes submission that is not handgraded 
 2178:     #                  (for multi-response type part)
 2179:     #             (3) Last submission plus the parts info
 2180:     #             (4) The whole record for this student
 2181:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2182: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2183: 	
 2184: 	my $lastsubonly;
 2185: 
 2186:         if ($$timestamp eq '') {
 2187:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2188:         } else {
 2189:             $lastsubonly =
 2190:                 '<div class="LC_grade_submissions_body">'
 2191:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
 2192: 
 2193: 	    my %seenparts;
 2194: 	    my @part_response_id = &flatten_responseType($responseType);
 2195: 	    foreach my $part (@part_response_id) {
 2196: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2197: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2198: 
 2199: 		my ($partid,$respid) = @{ $part };
 2200: 		my $display_part=&get_display_part($partid,$symb);
 2201: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2202: 		    if (exists($seenparts{$partid})) { next; }
 2203: 		    $seenparts{$partid}=1;
 2204: 		    my $submitby='<b>Part:</b> '.$display_part.
 2205: 			' <b>Collaborative submission by:</b> '.
 2206: 			'<a href="javascript:viewSubmitter(\''.
 2207: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2208: 			'\');" target="_self">'.
 2209: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2210: 		    $request->print($submitby);
 2211: 		    next;
 2212: 		}
 2213: 		my $responsetype = $responseType->{$partid}->{$respid};
 2214: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2215:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2216:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2217:                         ' <span class="LC_internal_info">'.
 2218:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2219:                         '</span>&nbsp; &nbsp;'.
 2220: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2221: 		    next;
 2222: 		}
 2223: 		foreach my $submission (@$string) {
 2224: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2225: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2226: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
 2227: 		    # Similarity check
 2228: 		    my $similar='';
 2229:                     my ($type,$trial,$rndseed);
 2230:                     if ($hide eq 'rand') {
 2231:                         $type = 'randomizetry';
 2232:                         $trial = $record{"resource.$partid.tries"};
 2233:                         $rndseed = $record{"resource.$partid.rndseed"};
 2234:                     }
 2235: 		    if($env{'form.checkPlag'}){
 2236: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2237: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2238: 			if ($osim) {
 2239: 			    $osim=int($osim*100.0);
 2240: 			    my %old_course_desc = 
 2241: 				&Apache::lonnet::coursedescription($ocrsid,
 2242: 								   {'one_time' => 1});
 2243: 
 2244:                             if ($hide eq 'anon') {
 2245:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
 2246:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
 2247:                             } else {
 2248: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
 2249: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2250: 				        $osim,
 2251: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2252: 				        $old_course_desc{'description'},
 2253: 				        $old_course_desc{'num'},
 2254: 				        $old_course_desc{'domain'}).
 2255: 				    '</span></h3><blockquote><i>'.
 2256: 				    &keywords_highlight($oessay).
 2257: 				    '</i></blockquote><hr />';
 2258:                             }
 2259: 			}
 2260: 		    }
 2261: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
 2262:                                          undef,$type,$trial,$rndseed);
 2263: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2264: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2265: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2266: 			my $display_part=&get_display_part($partid,$symb);
 2267:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2268:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2269:                             ' <span class="LC_internal_info">'.
 2270:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2271:                             '</b></span>&nbsp; &nbsp;';
 2272: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2273: 			if (@$files) {
 2274:                             if ($hide eq 'anon') {
 2275:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
 2276:                             } else {
 2277:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2278:                                 foreach my $file (@$files) {
 2279:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
 2280:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2281:                                 }
 2282:                             }
 2283: 			    $lastsubonly.='<br />';
 2284: 			}
 2285:                         if ($hide eq 'anon') {
 2286:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
 2287:                         } else {
 2288: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2289: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
 2290: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
 2291:                         }
 2292: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2293: 			$lastsubonly.='</div>';
 2294: 		    }
 2295: 		}
 2296: 	    }
 2297: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2298: 	}
 2299: 	$request->print($lastsubonly);
 2300:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2301: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2302: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2303:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2304: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2305: 								 $env{'request.course.id'},
 2306: 								 $last,'.submission',
 2307: 								 'Apache::grades::keywords_highlight'));
 2308:     }
 2309: 
 2310:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2311: 	.$udom.'" />'."\n");
 2312:     # return if view submission with no grading option
 2313:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2314: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2315: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2316: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2317: 	$toGrade.='</div>'."\n";
 2318: 	if (($env{'form.command'} eq 'submission') || 
 2319: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2320: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2321: 	}
 2322: 	$request->print($toGrade);
 2323: 	return;
 2324:     } else {
 2325: 	$request->print('</div>'."\n");
 2326:     }
 2327: 
 2328:     # essay grading message center
 2329:     if ($env{'form.handgrade'} eq 'yes') {
 2330: 	my $result='<div class="LC_grade_message_center">';
 2331:     
 2332: 	$result.='<div class="LC_grade_message_center_header">'.
 2333: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2334: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2335: 	my $msgfor = $givenn.' '.$lastname;
 2336: 	if (scalar(@$col_fullnames) > 0) {
 2337: 	    my $lastone = pop(@$col_fullnames);
 2338: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2339: 	}
 2340: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2341: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2342: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2343: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2344: 	    ',\''.$msgfor.'\');" target="_self">'.
 2345: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2346: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2347: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2348: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2349: 	    '<br />&nbsp;('.
 2350: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2351: 	$result.='</div></div>';
 2352: 	$request->print($result);
 2353:     }
 2354: 
 2355:     my %seen = ();
 2356:     my @partlist;
 2357:     my @gradePartRespid;
 2358:     my @part_response_id = &flatten_responseType($responseType);
 2359:     $request->print(
 2360:         '<div class="LC_Box">'
 2361:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2362:     );
 2363:     $request->print(&gradeBox_start());
 2364:     foreach my $part_response_id (@part_response_id) {
 2365:     	my ($partid,$respid) = @{ $part_response_id };
 2366: 	my $part_resp = join('_',@{ $part_response_id });
 2367: 	next if ($seen{$partid} > 0);
 2368: 	$seen{$partid}++;
 2369: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2370: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2371: 	push(@partlist,$partid);
 2372: 	push(@gradePartRespid,$partid.'.'.$respid);
 2373: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2374:     }
 2375:     $request->print(&gradeBox_end()); # </div>
 2376:     $request->print('</div>');
 2377: 
 2378:     $request->print('<div class="LC_grade_info_links">');
 2379:     $request->print('</div>');
 2380: 
 2381:     $result='<input type="hidden" name="partlist'.$counter.
 2382: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2383:     $result.='<input type="hidden" name="gradePartRespid'.
 2384: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2385:     my $ctr = 0;
 2386:     while ($ctr < scalar(@partlist)) {
 2387: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2388: 	    $partlist[$ctr].'" />'."\n";
 2389: 	$ctr++;
 2390:     }
 2391:     $request->print($result.''."\n");
 2392: 
 2393: # Done with printing info for one student
 2394: 
 2395:     $request->print('</div>');#LC_grade_show_user
 2396: 
 2397: 
 2398:     # print end of form
 2399:     if ($counter == $total) {
 2400:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
 2401: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2402: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
 2403: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2404: 	my $ntstu ='<select name="NTSTU">'.
 2405: 	    '<option>1</option><option>2</option>'.
 2406: 	    '<option>3</option><option>5</option>'.
 2407: 	    '<option>7</option><option>10</option></select>'."\n";
 2408: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2409: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2410:         $endform.=&mt('[_1]student(s)',$ntstu);
 2411: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2412: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2413: 	    '<input type="button" value="'.&mt('Next').'" '.
 2414: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2415:         $endform.='<span class="LC_warning">'.
 2416:                   &mt('(Next and Previous (student) do not save the scores.)').
 2417:                   '</span>'."\n" ;
 2418:         $endform.="<input type='hidden' value='".&get_increment().
 2419:             "' name='increment' />";
 2420: 	$endform.='</td></tr></table></form>';
 2421: 	$endform.=&show_grading_menu_form($symb);
 2422: 	$request->print($endform);
 2423:     }
 2424:     return '';
 2425: }
 2426: 
 2427: sub check_collaborators {
 2428:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2429:     my ($result,@col_fullnames);
 2430:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2431:     foreach my $part (keys(%$handgrade)) {
 2432: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2433: 					'.maxcollaborators',
 2434: 					$symb,$udom,$uname);
 2435: 	next if ($ncol <= 0);
 2436: 	$part =~ s/\_/\./g;
 2437: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2438: 	my (@good_collaborators, @bad_collaborators);
 2439: 	foreach my $possible_collaborator
 2440: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2441: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2442: 	    next if ($possible_collaborator eq '');
 2443: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2444: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2445: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2446: 	    # Doing this grep allows 'fuzzy' specification
 2447: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2448: 			       keys(%$classlist));
 2449: 	    if (! scalar(@matches)) {
 2450: 		push(@bad_collaborators, $possible_collaborator);
 2451: 	    } else {
 2452: 		push(@good_collaborators, @matches);
 2453: 	    }
 2454: 	}
 2455: 	if (scalar(@good_collaborators) != 0) {
 2456: 	    $result.='<br />'.&mt('Collaborators: ');
 2457: 	    foreach my $name (@good_collaborators) {
 2458: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2459: 		push(@col_fullnames, $givenn.' '.$lastname);
 2460: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2461: 	    }
 2462: 	    $result.='<br />'."\n";
 2463: 	    my ($part)=split(/\./,$part);
 2464: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2465: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2466: 		"\n";
 2467: 	}
 2468: 	if (scalar(@bad_collaborators) > 0) {
 2469: 	    $result.='<div class="LC_warning">';
 2470: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2471: 	    $result .= '</div>';
 2472: 	}         
 2473: 	if (scalar(@bad_collaborators > $ncol)) {
 2474: 	    $result .= '<div class="LC_warning">';
 2475: 	    $result .= &mt('This student has submitted too many '.
 2476: 		'collaborators.  Maximum is [_1].',$ncol);
 2477: 	    $result .= '</div>';
 2478: 	}
 2479:     }
 2480:     return ($result,$fullname,\@col_fullnames);
 2481: }
 2482: 
 2483: #--- Retrieve the last submission for all the parts
 2484: sub get_last_submission {
 2485:     my ($returnhash)=@_;
 2486:     my (@string,$timestamp,%lasthidden);
 2487:     if ($$returnhash{'version'}) {
 2488: 	my %lasthash=();
 2489: 	my ($version);
 2490: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2491: 	    foreach my $key (sort(split(/\:/,
 2492: 					$$returnhash{$version.':keys'}))) {
 2493: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2494: 		$timestamp = 
 2495: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2496: 	    }
 2497: 	}
 2498:         my (%typeparts,%randombytry);
 2499:         my $showsurv = 
 2500:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
 2501:         foreach my $key (sort(keys(%lasthash))) {
 2502:             if ($key =~ /\.type$/) {
 2503:                 if (($lasthash{$key} eq 'anonsurvey') || 
 2504:                     ($lasthash{$key} eq 'anonsurveycred') ||
 2505:                     ($lasthash{$key} eq 'randomizetry')) {
 2506:                     my ($ign,@parts) = split(/\./,$key);
 2507:                     pop(@parts);
 2508:                     my $id = join('.',@parts);
 2509:                     if ($lasthash{$key} eq 'randomizetry') {
 2510:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2511:                     } else {
 2512:                         unless ($showsurv) {
 2513:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2514:                         }
 2515:                     }
 2516:                     delete($lasthash{$key});
 2517:                 }
 2518:             }
 2519:         }
 2520:         my @hidden = keys(%typeparts);
 2521:         my @randomize = keys(%randombytry);
 2522: 	foreach my $key (keys(%lasthash)) {
 2523: 	    next if ($key !~ /\.submission$/);
 2524:             my $hide;
 2525:             if (@hidden) {
 2526:                 foreach my $id (@hidden) {
 2527:                     if ($key =~ /^\Q$id\E/) {
 2528:                         $hide = 'anon';
 2529:                         last;
 2530:                     }
 2531:                 }
 2532:             }
 2533:             unless ($hide) {
 2534:                 if (@randomize) {
 2535:                     foreach my $id (@hidden) {
 2536:                         if ($key =~ /^\Q$id\E/) {
 2537:                             $hide = 'rand';
 2538:                             last;
 2539:                         }
 2540:                     }
 2541:                 }
 2542:             }
 2543: 	    my ($partid,$foo) = split(/submission$/,$key);
 2544: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2545: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2546: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2547: 	}
 2548:     }
 2549:     if (!@string) {
 2550: 	$string[0] =
 2551: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2552:     }
 2553:     return (\@string,\$timestamp);
 2554: }
 2555: 
 2556: #--- High light keywords, with style choosen by user.
 2557: sub keywords_highlight {
 2558:     my $string    = shift;
 2559:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2560:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2561:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2562:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2563:     foreach my $keyword (@keylist) {
 2564: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2565:     }
 2566:     return $string;
 2567: }
 2568: 
 2569: #--- Called from submission routine
 2570: sub processHandGrade {
 2571:     my ($request) = shift;
 2572:     my $symb   = &get_symb($request);
 2573:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2574:     my $button = $env{'form.gradeOpt'};
 2575:     my $ngrade = $env{'form.NCT'};
 2576:     my $ntstu  = $env{'form.NTSTU'};
 2577:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2578:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2579: 
 2580:     if ($button eq 'Save & Next') {
 2581: 	my $ctr = 0;
 2582: 	while ($ctr < $ngrade) {
 2583: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2584: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2585: 	    if ($errorflag eq 'no_score') {
 2586: 		$ctr++;
 2587: 		next;
 2588: 	    }
 2589: 	    if ($errorflag eq 'not_allowed') {
 2590: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2591: 		$ctr++;
 2592: 		next;
 2593: 	    }
 2594: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2595: 	    my ($subject,$message,$msgstatus) = ('','','');
 2596: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2597:             my ($feedurl,$showsymb) =
 2598: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2599: 	    my $messagetail;
 2600: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2601: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2602: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2603: 		$subject.=' ['.$restitle.']';
 2604: 		my (@msgnum) = split(/,/,$includemsg);
 2605: 		foreach (@msgnum) {
 2606: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2607: 		}
 2608: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2609: 		if ($env{'form.withgrades'.$ctr}) {
 2610: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2611: 		    $messagetail = " for <a href=\"".
 2612: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2613: 		}
 2614: 		$msgstatus = 
 2615:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2616: 						     $message.$messagetail,
 2617:                                                      undef,$feedurl,undef,
 2618:                                                      undef,undef,$showsymb,
 2619:                                                      $restitle);
 2620: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2621: 				$msgstatus);
 2622: 	    }
 2623: 	    if ($env{'form.collaborator'.$ctr}) {
 2624: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2625: 		foreach my $collabstr (@collabstrs) {
 2626: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2627: 		    foreach my $collaborator (@collaborators) {
 2628: 			my ($errorflag,$pts,$wgt) = 
 2629: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2630: 					   $env{'form.unamedom'.$ctr},$part);
 2631: 			if ($errorflag eq 'not_allowed') {
 2632: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2633: 			    next;
 2634: 			} elsif ($message ne '') {
 2635: 			    my ($baseurl,$showsymb) = 
 2636: 				&get_feedurl_and_symb($symb,$collaborator,
 2637: 						      $udom);
 2638: 			    if ($env{'form.withgrades'.$ctr}) {
 2639: 				$messagetail = " for <a href=\"".
 2640:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2641: 			    }
 2642: 			    $msgstatus = 
 2643: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2644: 			}
 2645: 		    }
 2646: 		}
 2647: 	    }
 2648: 	    $ctr++;
 2649: 	}
 2650:     }
 2651: 
 2652:     if ($env{'form.handgrade'} eq 'yes') {
 2653: 	# Keywords sorted in alphabatical order
 2654: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2655: 	my %keyhash = ();
 2656: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2657: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2658: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2659: 	$env{'form.keywords'} = join(' ',@keywords);
 2660: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2661: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2662: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2663: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2664: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2665: 
 2666: 	# message center - Order of message gets changed. Blank line is eliminated.
 2667: 	# New messages are saved in env for the next student.
 2668: 	# All messages are saved in nohist_handgrade.db
 2669: 	my ($ctr,$idx) = (1,1);
 2670: 	while ($ctr <= $env{'form.savemsgN'}) {
 2671: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2672: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2673: 		$idx++;
 2674: 	    }
 2675: 	    $ctr++;
 2676: 	}
 2677: 	$ctr = 0;
 2678: 	while ($ctr < $ngrade) {
 2679: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2680: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2681: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2682: 		$idx++;
 2683: 	    }
 2684: 	    $ctr++;
 2685: 	}
 2686: 	$env{'form.savemsgN'} = --$idx;
 2687: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2688: 	my $putresult = &Apache::lonnet::put
 2689: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2690:     }
 2691:     # Called by Save & Refresh from Highlight Attribute Window
 2692:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2693:     if ($env{'form.refresh'} eq 'on') {
 2694: 	my ($ctr,$total) = (0,0);
 2695: 	while ($ctr < $ngrade) {
 2696: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2697: 	    $ctr++;
 2698: 	}
 2699: 	$env{'form.NTSTU'}=$ngrade;
 2700: 	$ctr = 0;
 2701: 	while ($ctr < $total) {
 2702: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2703: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2704: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2705: 	    &submission($request,$ctr,$total-1);
 2706: 	    $ctr++;
 2707: 	}
 2708: 	return '';
 2709:     }
 2710: 
 2711: # Go directly to grade student - from submission or link from chart page
 2712:     if ($button eq 'Grade Student') {
 2713: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2714: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2715: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2716: 	$env{'form.fullname'} = $$fullname{$processUser};
 2717: 	&submission($request,0,0);
 2718: 	return '';
 2719:     }
 2720: 
 2721:     # Get the next/previous one or group of students
 2722:     my $firststu = $env{'form.unamedom0'};
 2723:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2724:     my $ctr = 2;
 2725:     while ($laststu eq '') {
 2726: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2727: 	$ctr++;
 2728: 	$laststu = $firststu if ($ctr > $ngrade);
 2729:     }
 2730: 
 2731:     my (@parsedlist,@nextlist);
 2732:     my ($nextflg) = 0;
 2733:     foreach my $item (sort 
 2734: 	     {
 2735: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2736: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2737: 		 }
 2738: 		 return $a cmp $b;
 2739: 	     } (keys(%$fullname))) {
 2740: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2741: 	    push(@parsedlist,$item);
 2742: 	}
 2743: 	$nextflg = 1 if ($item eq $laststu);
 2744: 	if ($button eq 'Previous') {
 2745: 	    last if ($item eq $firststu);
 2746: 	    push(@parsedlist,$item);
 2747: 	}
 2748:     }
 2749:     $ctr = 0;
 2750:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2751:     my $res_error;
 2752:     my ($partlist) = &response_type($symb,\$res_error);
 2753:     if ($res_error) {
 2754:         $request->print(&navmap_errormsg());
 2755:         return;
 2756:     }
 2757:     foreach my $student (@parsedlist) {
 2758: 	my $submitonly=$env{'form.submitonly'};
 2759: 	my ($uname,$udom) = split(/:/,$student);
 2760: 	
 2761: 	if ($submitonly eq 'queued') {
 2762: 	    my %queue_status = 
 2763: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2764: 							$udom,$uname);
 2765: 	    next if (!defined($queue_status{'gradingqueue'}));
 2766: 	}
 2767: 
 2768: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2769: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2770: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2771: 	    my $submitted = 0;
 2772: 	    my $ungraded = 0;
 2773: 	    my $incorrect = 0;
 2774: 	    foreach my $item (keys(%status)) {
 2775: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2776: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2777: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2778: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2779: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2780: 		    $submitted = 0;
 2781: 		}
 2782: 	    }
 2783: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2784: 				     $submitonly eq 'incorrect' ||
 2785: 				     $submitonly eq 'graded'));
 2786: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2787: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2788: 	}
 2789: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2790: 	last if ($ctr == $ntstu);
 2791: 	$ctr++;
 2792:     }
 2793: 
 2794:     $ctr = 0;
 2795:     my $total = scalar(@nextlist)-1;
 2796: 
 2797:     foreach (sort(@nextlist)) {
 2798: 	my ($uname,$udom,$submitter) = split(/:/);
 2799: 	$env{'form.student'}  = $uname;
 2800: 	$env{'form.userdom'}  = $udom;
 2801: 	$env{'form.fullname'} = $$fullname{$_};
 2802: 	&submission($request,$ctr,$total);
 2803: 	$ctr++;
 2804:     }
 2805:     if ($total < 0) {
 2806: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2807: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2808: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2809: 	$the_end.=&show_grading_menu_form($symb);
 2810: 	$request->print($the_end);
 2811:     }
 2812:     return '';
 2813: }
 2814: 
 2815: #---- Save the score and award for each student, if changed
 2816: sub saveHandGrade {
 2817:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2818:     my @version_parts;
 2819:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2820: 					   $env{'request.course.id'});
 2821:     if (!&canmodify($usec)) { return('not_allowed'); }
 2822:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2823:     my @parts_graded;
 2824:     my %newrecord  = ();
 2825:     my ($pts,$wgt) = ('','');
 2826:     my %aggregate = ();
 2827:     my $aggregateflag = 0;
 2828:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2829:     foreach my $new_part (@parts) {
 2830: 	#collaborator ($submi may vary for different parts
 2831: 	if ($submitter && $new_part ne $part) { next; }
 2832: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2833: 	if ($dropMenu eq 'excused') {
 2834: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2835: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2836: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2837: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2838: 		}
 2839: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2840: 	    }
 2841: 	} elsif ($dropMenu eq 'reset status'
 2842: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2843: 	    foreach my $key (keys(%record)) {
 2844: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2845: 	    }
 2846: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2847: 		"$env{'user.name'}:$env{'user.domain'}";
 2848:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2849: 
 2850:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2851: 					       [$new_part]);
 2852:             my $aggtries =$totaltries;
 2853:             if ($last_resets{$new_part}) {
 2854:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2855: 					   $new_part);
 2856:             }
 2857: 
 2858:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2859:             if ($aggtries > 0) {
 2860:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2861:                 $aggregateflag = 1;
 2862:             }
 2863: 	} elsif ($dropMenu eq '') {
 2864: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2865: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2866: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2867: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2868: 		next;
 2869: 	    }
 2870: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2871: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2872: 	    my $partial= $pts/$wgt;
 2873: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2874: 		#do not update score for part if not changed.
 2875:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2876: 		next;
 2877: 	    } else {
 2878: 	        push(@parts_graded,$new_part);
 2879: 	    }
 2880: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2881: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2882: 	    }
 2883: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2884: 	    if ($partial == 0) {
 2885: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2886: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2887: 		}
 2888: 	    } else {
 2889: 		if ($record{$reckey} ne 'correct_by_override') {
 2890: 		    $newrecord{$reckey} = 'correct_by_override';
 2891: 		}
 2892: 	    }	    
 2893: 	    if ($submitter && 
 2894: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2895: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2896: 	    }
 2897: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2898: 		"$env{'user.name'}:$env{'user.domain'}";
 2899: 	}
 2900: 	# unless problem has been graded, set flag to version the submitted files
 2901: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2902: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2903: 	        $dropMenu eq 'reset status')
 2904: 	   {
 2905: 	    push(@version_parts,$new_part);
 2906: 	}
 2907:     }
 2908:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2909:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2910: 
 2911:     if (%newrecord) {
 2912:         if (@version_parts) {
 2913:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2914:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2915: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2916: 	    foreach my $new_part (@version_parts) {
 2917: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2918: 				$new_part,\%newrecord);
 2919: 	    }
 2920:         }
 2921: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2922: 				$env{'request.course.id'},$domain,$stuname);
 2923: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2924: 				     $cdom,$cnum,$domain,$stuname);
 2925:     }
 2926:     if ($aggregateflag) {
 2927:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2928: 			      $cdom,$cnum);
 2929:     }
 2930:     return ('',$pts,$wgt);
 2931: }
 2932: 
 2933: sub check_and_remove_from_queue {
 2934:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2935:     my @ungraded_parts;
 2936:     foreach my $part (@{$parts}) {
 2937: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2938: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2939: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2940: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2941: 		) {
 2942: 	    push(@ungraded_parts, $part);
 2943: 	}
 2944:     }
 2945:     if ( !@ungraded_parts ) {
 2946: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2947: 					       $cnum,$domain,$stuname);
 2948:     }
 2949: }
 2950: 
 2951: sub handback_files {
 2952:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2953:     my $portfolio_root = '/userfiles/portfolio';
 2954:     my $res_error;
 2955:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2956:     if ($res_error) {
 2957:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2958:         return;
 2959:     }
 2960:     my @part_response_id = &flatten_responseType($responseType);
 2961:     foreach my $part_response_id (@part_response_id) {
 2962:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2963: 	my $part_resp = join('_',@{ $part_response_id });
 2964:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2965:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2966:                 my $file_counter = 1;
 2967: 		my $file_msg;
 2968:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2969:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2970:                     my ($directory,$answer_file) = 
 2971:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2972:                     my ($answer_name,$answer_ver,$answer_ext) =
 2973: 		        &file_name_version_ext($answer_file);
 2974: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2975:                     my $getpropath = 1;
 2976: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2977: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2978:                     # fix file name
 2979:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2980:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2981:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2982:             	                                $save_file_name);
 2983:                     if ($result !~ m|^/uploaded/|) {
 2984:                         $request->print('<br /><span class="LC_error">'.
 2985:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2986:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2987:                                         '</span>');
 2988:                     } else {
 2989:                         # mark the file as read only
 2990:                         my @files = ($save_file_name);
 2991:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2992:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2993: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2994: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2995: 			}
 2996:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2997: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2998: 
 2999:                     }
 3000:                     $request->print("<br />".$fname." will be the uploaded file name");
 3001:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 3002:                     $file_counter++;
 3003:                 }
 3004: 		my $subject = "File Handed Back by Instructor ";
 3005: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 3006: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 3007: 		$message .= ' The returned file(s) are named: '. $file_msg;
 3008: 		$message .= " and can be found in your portfolio space.";
 3009: 		my ($feedurl,$showsymb) = 
 3010: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 3011:                 my $restitle = &Apache::lonnet::gettitle($symb);
 3012: 		my $msgstatus = 
 3013:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 3014: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 3015:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 3016:             }
 3017:         }
 3018:     return;
 3019: }
 3020: 
 3021: sub get_feedurl_and_symb {
 3022:     my ($symb,$uname,$udom) = @_;
 3023:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3024:     $url = &Apache::lonnet::clutter($url);
 3025:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3026: 					$symb,$udom,$uname);
 3027:     if ($encrypturl =~ /^yes$/i) {
 3028: 	&Apache::lonenc::encrypted(\$url,1);
 3029: 	&Apache::lonenc::encrypted(\$symb,1);
 3030:     }
 3031:     return ($url,$symb);
 3032: }
 3033: 
 3034: sub get_submitted_files {
 3035:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3036:     my @files;
 3037:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3038:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3039:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3040:     	    push(@files,$file_url.$file);
 3041:         }
 3042:     }
 3043:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3044:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3045:     }
 3046:     return (\@files);
 3047: }
 3048: 
 3049: # ----------- Provides number of tries since last reset.
 3050: sub get_num_tries {
 3051:     my ($record,$last_reset,$part) = @_;
 3052:     my $timestamp = '';
 3053:     my $num_tries = 0;
 3054:     if ($$record{'version'}) {
 3055:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3056:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3057:                 $timestamp = $$record{$version.':timestamp'};
 3058:                 if ($timestamp > $last_reset) {
 3059:                     $num_tries ++;
 3060:                 } else {
 3061:                     last;
 3062:                 }
 3063:             }
 3064:         }
 3065:     }
 3066:     return $num_tries;
 3067: }
 3068: 
 3069: # ----------- Determine decrements required in aggregate totals 
 3070: sub decrement_aggs {
 3071:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3072:     my %decrement = (
 3073:                         attempts => 0,
 3074:                         users => 0,
 3075:                         correct => 0
 3076:                     );
 3077:     $decrement{'attempts'} = $aggtries;
 3078:     if ($solvedstatus =~ /^correct/) {
 3079:         $decrement{'correct'} = 1;
 3080:     }
 3081:     if ($aggtries == $totaltries) {
 3082:         $decrement{'users'} = 1;
 3083:     }
 3084:     foreach my $type (keys(%decrement)) {
 3085:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3086:     }
 3087:     return;
 3088: }
 3089: 
 3090: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3091: sub get_last_resets {
 3092:     my ($symb,$courseid,$partids) =@_;
 3093:     my %last_resets;
 3094:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3095:     my $cname = $env{'course.'.$courseid.'.num'};
 3096:     my @keys;
 3097:     foreach my $part (@{$partids}) {
 3098: 	push(@keys,"$symb\0$part\0resettime");
 3099:     }
 3100:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3101: 				     $cdom,$cname);
 3102:     foreach my $part (@{$partids}) {
 3103: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3104:     }
 3105:     return %last_resets;
 3106: }
 3107: 
 3108: # ----------- Handles creating versions for portfolio files as answers
 3109: sub version_portfiles {
 3110:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3111:     my $version_parts = join('|',@$v_flag);
 3112:     my @returned_keys;
 3113:     my $parts = join('|', @$parts_graded);
 3114:     my $portfolio_root = '/userfiles/portfolio';
 3115:     foreach my $key (keys(%$record)) {
 3116:         my $new_portfiles;
 3117:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3118:             my @versioned_portfiles;
 3119:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3120:             foreach my $file (@portfiles) {
 3121:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3122:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3123: 		my ($answer_name,$answer_ver,$answer_ext) =
 3124: 		    &file_name_version_ext($answer_file);
 3125:                 my $getpropath = 1;    
 3126:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3127:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3128:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3129:                 if ($new_answer ne 'problem getting file') {
 3130:                     push(@versioned_portfiles, $directory.$new_answer);
 3131:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3132:                         [$directory.$new_answer],
 3133:                         [$symb,$env{'request.course.id'},'graded']);
 3134:                 }
 3135:             }
 3136:             $$record{$key} = join(',',@versioned_portfiles);
 3137:             push(@returned_keys,$key);
 3138:         }
 3139:     } 
 3140:     return (@returned_keys);   
 3141: }
 3142: 
 3143: sub get_next_version {
 3144:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3145:     my $version;
 3146:     foreach my $row (@$dir_list) {
 3147:         my ($file) = split(/\&/,$row,2);
 3148:         my ($file_name,$file_version,$file_ext) =
 3149: 	    &file_name_version_ext($file);
 3150:         if (($file_name eq $answer_name) && 
 3151: 	    ($file_ext eq $answer_ext)) {
 3152:                 # gets here if filename and extension match, regardless of version
 3153:                 if ($file_version ne '') {
 3154:                 # a versioned file is found  so save it for later
 3155:                 if ($file_version > $version) {
 3156: 		    $version = $file_version;
 3157: 	        }
 3158:             }
 3159:         }
 3160:     } 
 3161:     $version ++;
 3162:     return($version);
 3163: }
 3164: 
 3165: sub version_selected_portfile {
 3166:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3167:     my ($answer_name,$answer_ver,$answer_ext) =
 3168:         &file_name_version_ext($file_name);
 3169:     my $new_answer;
 3170:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3171:     if($env{'form.copy'} eq '-1') {
 3172:         $new_answer = 'problem getting file';
 3173:     } else {
 3174:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3175:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3176:                             $stu_name,$domain,'copy',
 3177: 		        '/portfolio'.$directory.$new_answer);
 3178:     }    
 3179:     return ($new_answer);
 3180: }
 3181: 
 3182: sub file_name_version_ext {
 3183:     my ($file)=@_;
 3184:     my @file_parts = split(/\./, $file);
 3185:     my ($name,$version,$ext);
 3186:     if (@file_parts > 1) {
 3187: 	$ext=pop(@file_parts);
 3188: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3189: 	    $version=pop(@file_parts);
 3190: 	}
 3191: 	$name=join('.',@file_parts);
 3192:     } else {
 3193: 	$name=join('.',@file_parts);
 3194:     }
 3195:     return($name,$version,$ext);
 3196: }
 3197: 
 3198: #--------------------------------------------------------------------------------------
 3199: #
 3200: #-------------------------- Next few routines handles grading by section or whole class
 3201: #
 3202: #--- Javascript to handle grading by section or whole class
 3203: sub viewgrades_js {
 3204:     my ($request) = shift;
 3205: 
 3206:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3207:     $request->print(<<VIEWJAVASCRIPT);
 3208: <script type="text/javascript" language="javascript">
 3209:    function writePoint(partid,weight,point) {
 3210: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3211: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3212: 	if (point == "textval") {
 3213: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3214: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3215: 		alert("$alertmsg"+parseFloat(point));
 3216: 		var resetbox = false;
 3217: 		for (var i=0; i<radioButton.length; i++) {
 3218: 		    if (radioButton[i].checked) {
 3219: 			textbox.value = i;
 3220: 			resetbox = true;
 3221: 		    }
 3222: 		}
 3223: 		if (!resetbox) {
 3224: 		    textbox.value = "";
 3225: 		}
 3226: 		return;
 3227: 	    }
 3228: 	    if (parseFloat(point) > parseFloat(weight)) {
 3229: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3230: 				   ") greater than the weight for the part. Accept?");
 3231: 		if (resp == false) {
 3232: 		    textbox.value = "";
 3233: 		    return;
 3234: 		}
 3235: 	    }
 3236: 	    for (var i=0; i<radioButton.length; i++) {
 3237: 		radioButton[i].checked=false;
 3238: 		if (parseFloat(point) == i) {
 3239: 		    radioButton[i].checked=true;
 3240: 		}
 3241: 	    }
 3242: 
 3243: 	} else {
 3244: 	    textbox.value = parseFloat(point);
 3245: 	}
 3246: 	for (i=0;i<document.classgrade.total.value;i++) {
 3247: 	    var user = document.classgrade["ctr"+i].value;
 3248: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3249: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3250: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3251: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3252: 	    if (saveval != "correct") {
 3253: 		scorename.value = point;
 3254: 		if (selname[0].selected != true) {
 3255: 		    selname[0].selected = true;
 3256: 		}
 3257: 	    }
 3258: 	}
 3259: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3260:     }
 3261: 
 3262:     function writeRadText(partid,weight) {
 3263: 	var selval   = document.classgrade["SELVAL_"+partid];
 3264: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3265:         var override = document.classgrade["FORCE_"+partid].checked;
 3266: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3267: 	if (selval[1].selected || selval[2].selected) {
 3268: 	    for (var i=0; i<radioButton.length; i++) {
 3269: 		radioButton[i].checked=false;
 3270: 
 3271: 	    }
 3272: 	    textbox.value = "";
 3273: 
 3274: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3275: 		var user = document.classgrade["ctr"+i].value;
 3276: 		user = user.replace(new RegExp(':', 'g'),"_");
 3277: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3278: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3279: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3280: 		if ((saveval != "correct") || override) {
 3281: 		    scorename.value = "";
 3282: 		    if (selval[1].selected) {
 3283: 			selname[1].selected = true;
 3284: 		    } else {
 3285: 			selname[2].selected = true;
 3286: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3287: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3288: 		    }
 3289: 		}
 3290: 	    }
 3291: 	} else {
 3292: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3293: 		var user = document.classgrade["ctr"+i].value;
 3294: 		user = user.replace(new RegExp(':', 'g'),"_");
 3295: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3296: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3297: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3298: 		if ((saveval != "correct") || override) {
 3299: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3300: 		    selname[0].selected = true;
 3301: 		}
 3302: 	    }
 3303: 	}	    
 3304:     }
 3305: 
 3306:     function changeSelect(partid,user) {
 3307: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3308: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3309: 	var point  = textbox.value;
 3310: 	var weight = document.classgrade["weight_"+partid].value;
 3311: 
 3312: 	if (isNaN(point) || parseFloat(point) < 0) {
 3313: 	    alert("$alertmsg"+parseFloat(point));
 3314: 	    textbox.value = "";
 3315: 	    return;
 3316: 	}
 3317: 	if (parseFloat(point) > parseFloat(weight)) {
 3318: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3319: 			       ") greater than the weight of the part. Accept?");
 3320: 	    if (resp == false) {
 3321: 		textbox.value = "";
 3322: 		return;
 3323: 	    }
 3324: 	}
 3325: 	selval[0].selected = true;
 3326:     }
 3327: 
 3328:     function changeOneScore(partid,user) {
 3329: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3330: 	if (selval[1].selected || selval[2].selected) {
 3331: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3332: 	    if (selval[2].selected) {
 3333: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3334: 	    }
 3335:         }
 3336:     }
 3337: 
 3338:     function resetEntry(numpart) {
 3339: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3340: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3341: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3342: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3343: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3344: 	    for (var i=0; i<radioButton.length; i++) {
 3345: 		radioButton[i].checked=false;
 3346: 
 3347: 	    }
 3348: 	    textbox.value = "";
 3349: 	    selval[0].selected = true;
 3350: 
 3351: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3352: 		var user = document.classgrade["ctr"+i].value;
 3353: 		user = user.replace(new RegExp(':', 'g'),"_");
 3354: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3355: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3356: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3357: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3358: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3359: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3360: 		if (saveselval == "excused") {
 3361: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3362: 		} else {
 3363: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3364: 		}
 3365: 	    }
 3366: 	}
 3367:     }
 3368: 
 3369: </script>
 3370: VIEWJAVASCRIPT
 3371: }
 3372: 
 3373: #--- show scores for a section or whole class w/ option to change/update a score
 3374: sub viewgrades {
 3375:     my ($request) = shift;
 3376:     &viewgrades_js($request);
 3377: 
 3378:     my ($symb) = &get_symb($request);
 3379:     #need to make sure we have the correct data for later EXT calls, 
 3380:     #thus invalidate the cache
 3381:     &Apache::lonnet::devalidatecourseresdata(
 3382:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3383:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3384:     &Apache::lonnet::clear_EXT_cache_status();
 3385: 
 3386:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3387:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3388: 
 3389:     #view individual student submission form - called using Javascript viewOneStudent
 3390:     $result.=&jscriptNform($symb);
 3391: 
 3392:     #beginning of class grading form
 3393:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3394:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3395: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3396: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3397: 	&build_section_inputs().
 3398: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3399: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3400: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3401: 
 3402:     my ($common_header,$specific_header);
 3403:     if ($env{'form.section'} eq 'all') {
 3404: 	$common_header = &mt('Assign Common Grade to Class');
 3405:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3406:     } elsif ($env{'form.section'} eq 'none') {
 3407:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3408: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3409:     } else {
 3410:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3411:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3412: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3413:     }
 3414:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3415:     #radio buttons/text box for assigning points for a section or class.
 3416:     #handles different parts of a problem
 3417:     my $res_error;
 3418:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3419:     if ($res_error) {
 3420:         return &navmap_errormsg();
 3421:     }
 3422:     my %weight = ();
 3423:     my $ctsparts = 0;
 3424:     my %seen = ();
 3425:     my @part_response_id = &flatten_responseType($responseType);
 3426:     foreach my $part_response_id (@part_response_id) {
 3427:     	my ($partid,$respid) = @{ $part_response_id };
 3428: 	my $part_resp = join('_',@{ $part_response_id });
 3429: 	next if $seen{$partid};
 3430: 	$seen{$partid}++;
 3431: 	my $handgrade=$$handgrade{$part_resp};
 3432: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3433: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3434: 
 3435: 	my $display_part=&get_display_part($partid,$symb);
 3436: 	my $radio.='<table border="0"><tr>';  
 3437: 	my $ctr = 0;
 3438: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3439: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3440: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3441: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3442: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3443: 	    $ctr++;
 3444: 	}
 3445: 	$radio.='</tr></table>';
 3446: 	my $line = '<input type="text" name="TEXTVAL_'.
 3447: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3448: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3449: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3450: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3451: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3452: 		$weight{$partid}.')"> '.
 3453: 	    '<option selected="selected"> </option>'.
 3454: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3455: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3456: 	    '</select></td>'.
 3457:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3458: 	$line.='<input type="hidden" name="partid_'.
 3459: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3460: 	$line.='<input type="hidden" name="weight_'.
 3461: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3462: 
 3463: 	$result.=
 3464: 	    &Apache::loncommon::start_data_table_row()."\n".
 3465: 	    '<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>'.
 3466: 	    &Apache::loncommon::end_data_table_row()."\n";
 3467: 	$ctsparts++;
 3468:     }
 3469:     $result.=&Apache::loncommon::end_data_table()."\n".
 3470: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3471:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3472: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3473: 
 3474:     #table listing all the students in a section/class
 3475:     #header of table
 3476:     $result.= '<h3>'.$specific_header.'</h3>'.
 3477:               &Apache::loncommon::start_data_table().
 3478: 	      &Apache::loncommon::start_data_table_header_row().
 3479: 	      '<th>'.&mt('No.').'</th>'.
 3480: 	      '<th>'.&nameUserString('header')."</th>\n";
 3481:     my $partserror;
 3482:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3483:     if ($partserror) {
 3484:         return &navmap_errormsg();
 3485:     }
 3486:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3487:     my @partids = ();
 3488:     foreach my $part (@parts) {
 3489: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3490:         my $narrowtext = &mt('Tries');
 3491: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3492: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3493: 	my ($partid) = &split_part_type($part);
 3494:         push(@partids,$partid);
 3495: 	my $display_part=&get_display_part($partid,$symb);
 3496: 	if ($display =~ /^Partial Credit Factor/) {
 3497: 	    $result.='<th>'.
 3498: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3499: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3500: 	    next;
 3501: 	    
 3502: 	} else {
 3503: 	    if ($display =~ /Problem Status/) {
 3504: 		my $grade_status_mt = &mt('Grade Status');
 3505: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3506: 	    }
 3507: 	    my $part_mt = &mt('Part:');
 3508: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3509: 	}
 3510: 
 3511: 	$result.='<th>'.$display.'</th>'."\n";
 3512:     }
 3513:     $result.=&Apache::loncommon::end_data_table_header_row();
 3514: 
 3515:     my %last_resets = 
 3516: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3517: 
 3518:     #get info for each student
 3519:     #list all the students - with points and grade status
 3520:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3521:     my $ctr = 0;
 3522:     foreach (sort 
 3523: 	     {
 3524: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3525: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3526: 		 }
 3527: 		 return $a cmp $b;
 3528: 	     } (keys(%$fullname))) {
 3529: 	$ctr++;
 3530: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3531: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3532:     }
 3533:     $result.=&Apache::loncommon::end_data_table();
 3534:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3535:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3536: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3537:     if (scalar(%$fullname) eq 0) {
 3538: 	my $colspan=3+scalar(@parts);
 3539: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3540:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3541: 	$result='<span class="LC_warning">'.
 3542: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3543: 	        $section_display, $stu_status).
 3544: 	    '</span>';
 3545:     }
 3546:     $result.=&show_grading_menu_form($symb);
 3547:     return $result;
 3548: }
 3549: 
 3550: #--- call by previous routine to display each student
 3551: sub viewstudentgrade {
 3552:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3553:     my ($uname,$udom) = split(/:/,$student);
 3554:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3555:     my %aggregates = (); 
 3556:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3557: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3558: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3559: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3560: 	'\');" target="_self">'.$fullname.'</a> '.
 3561: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3562:     $student=~s/:/_/; # colon doen't work in javascript for names
 3563:     foreach my $apart (@$parts) {
 3564: 	my ($part,$type) = &split_part_type($apart);
 3565: 	my $score=$record{"resource.$part.$type"};
 3566:         $result.='<td align="center">';
 3567:         my ($aggtries,$totaltries);
 3568:         unless (exists($aggregates{$part})) {
 3569: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3570: 
 3571: 	    $aggtries = $totaltries;
 3572:             if ($$last_resets{$part}) {  
 3573:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3574: 					   $part);
 3575:             }
 3576:             $result.='<input type="hidden" name="'.
 3577:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3578:             $result.='<input type="hidden" name="'.
 3579:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3580:             $aggregates{$part} = 1;
 3581:         }
 3582: 	if ($type eq 'awarded') {
 3583: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3584: 	    $result.='<input type="hidden" name="'.
 3585: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3586: 	    $result.='<input type="text" name="'.
 3587: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3588:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3589: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3590: 	} elsif ($type eq 'solved') {
 3591: 	    my ($status,$foo)=split(/_/,$score,2);
 3592: 	    $status = 'nothing' if ($status eq '');
 3593: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3594: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3595: 	    $result.='&nbsp;<select name="'.
 3596: 		'GD_'.$student.'_'.$part.'_solved" '.
 3597:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3598: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3599: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3600: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3601: 	    $result.="</select>&nbsp;</td>\n";
 3602: 	} else {
 3603: 	    $result.='<input type="hidden" name="'.
 3604: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3605: 		    "\n";
 3606: 	    $result.='<input type="text" name="'.
 3607: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3608: 		'value="'.$score.'" size="4" /></td>'."\n";
 3609: 	}
 3610:     }
 3611:     $result.=&Apache::loncommon::end_data_table_row();
 3612:     return $result;
 3613: }
 3614: 
 3615: #--- change scores for all the students in a section/class
 3616: #    record does not get update if unchanged
 3617: sub editgrades {
 3618:     my ($request) = @_;
 3619: 
 3620:     my $symb=&get_symb($request);
 3621:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3622:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3623:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3624:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3625: 
 3626:     my $result= &Apache::loncommon::start_data_table().
 3627: 	&Apache::loncommon::start_data_table_header_row().
 3628: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3629: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3630:     my %scoreptr = (
 3631: 		    'correct'  =>'correct_by_override',
 3632: 		    'incorrect'=>'incorrect_by_override',
 3633: 		    'excused'  =>'excused',
 3634: 		    'ungraded' =>'ungraded_attempted',
 3635:                     'credited' =>'credit_attempted',
 3636: 		    'nothing'  => '',
 3637: 		    );
 3638:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3639: 
 3640:     my (@partid);
 3641:     my %weight = ();
 3642:     my %columns = ();
 3643:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3644: 
 3645:     my $partserror;
 3646:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3647:     if ($partserror) {
 3648:         return &navmap_errormsg();
 3649:     }
 3650:     my $header;
 3651:     while ($ctr < $env{'form.totalparts'}) {
 3652: 	my $partid = $env{'form.partid_'.$ctr};
 3653: 	push(@partid,$partid);
 3654: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3655: 	$ctr++;
 3656:     }
 3657:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3658:     foreach my $partid (@partid) {
 3659: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3660: 	    '<th align="center">'.&mt('New Score').'</th>';
 3661: 	$columns{$partid}=2;
 3662: 	foreach my $stores (@parts) {
 3663: 	    my ($part,$type) = &split_part_type($stores);
 3664: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3665: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3666: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3667: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3668:             my $narrowtext = &mt('Tries');
 3669: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3670: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3671: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3672: 	    $columns{$partid}+=2;
 3673: 	}
 3674:     }
 3675:     foreach my $partid (@partid) {
 3676: 	my $display_part=&get_display_part($partid,$symb);
 3677: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3678: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3679: 	    '</th>';
 3680: 
 3681:     }
 3682:     $result .= &Apache::loncommon::end_data_table_header_row().
 3683: 	&Apache::loncommon::start_data_table_header_row().
 3684: 	$header.
 3685: 	&Apache::loncommon::end_data_table_header_row();
 3686:     my @noupdate;
 3687:     my ($updateCtr,$noupdateCtr) = (1,1);
 3688:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3689: 	my $line;
 3690: 	my $user = $env{'form.ctr'.$i};
 3691: 	my ($uname,$udom)=split(/:/,$user);
 3692: 	my %newrecord;
 3693: 	my $updateflag = 0;
 3694: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3695: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3696: 	if (!&canmodify($usec)) {
 3697: 	    my $numcols=scalar(@partid)*4+2;
 3698: 	    push(@noupdate,
 3699: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3700: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3701: 	    next;
 3702: 	}
 3703:         my %aggregate = ();
 3704:         my $aggregateflag = 0;
 3705: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3706: 	foreach (@partid) {
 3707: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3708: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3709: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3710: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3711: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3712: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3713: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3714: 	    my $score;
 3715: 	    if ($partial eq '') {
 3716: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3717: 	    } elsif ($partial > 0) {
 3718: 		$score = 'correct_by_override';
 3719: 	    } elsif ($partial == 0) {
 3720: 		$score = 'incorrect_by_override';
 3721: 	    }
 3722: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3723: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3724: 
 3725: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3726: 		"$env{'user.name'}:$env{'user.domain'}";
 3727: 	    if ($dropMenu eq 'reset status' &&
 3728: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3729: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3730: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3731: 		$newrecord{'resource.'.$_.'.award'} = '';
 3732: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3733: 		$updateflag = 1;
 3734:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3735:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3736:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3737:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3738:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3739:                     $aggregateflag = 1;
 3740:                 }
 3741: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3742: 		$updateflag = 1;
 3743: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3744: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3745: 		$rec_update++;
 3746: 	    }
 3747: 
 3748: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3749: 		'<td align="center">'.$awarded.
 3750: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3751: 
 3752: 
 3753: 	    my $partid=$_;
 3754: 	    foreach my $stores (@parts) {
 3755: 		my ($part,$type) = &split_part_type($stores);
 3756: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3757: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3758: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3759: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3760: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3761: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3762: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3763: 		    $updateflag=1;
 3764: 		}
 3765: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3766: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3767: 	    }
 3768: 	}
 3769: 	$line.="\n";
 3770: 
 3771: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3772: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3773: 
 3774: 	if ($updateflag) {
 3775: 	    $count++;
 3776: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3777: 				    $udom,$uname);
 3778: 
 3779: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3780: 					      $cnum,$udom,$uname)) {
 3781: 		# need to figure out if should be in queue.
 3782: 		my %record =  
 3783: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3784: 					     $udom,$uname);
 3785: 		my $all_graded = 1;
 3786: 		my $none_graded = 1;
 3787: 		foreach my $part (@parts) {
 3788: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3789: 			$all_graded = 0;
 3790: 		    } else {
 3791: 			$none_graded = 0;
 3792: 		    }
 3793: 		}
 3794: 
 3795: 		if ($all_graded || $none_graded) {
 3796: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3797: 							   $symb,$cdom,$cnum,
 3798: 							   $udom,$uname);
 3799: 		}
 3800: 	    }
 3801: 
 3802: 	    $result.=&Apache::loncommon::start_data_table_row().
 3803: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3804: 		&Apache::loncommon::end_data_table_row();
 3805: 	    $updateCtr++;
 3806: 	} else {
 3807: 	    push(@noupdate,
 3808: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3809: 	    $noupdateCtr++;
 3810: 	}
 3811:         if ($aggregateflag) {
 3812:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3813: 				  $cdom,$cnum);
 3814:         }
 3815:     }
 3816:     if (@noupdate) {
 3817: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3818: 	my $numcols=scalar(@partid)*4+2;
 3819: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3820: 	    '<td align="center" colspan="'.$numcols.'">'.
 3821: 	    &mt('No Changes Occurred For the Students Below').
 3822: 	    '</td>'.
 3823: 	    &Apache::loncommon::end_data_table_row();
 3824: 	foreach my $line (@noupdate) {
 3825: 	    $result.=
 3826: 		&Apache::loncommon::start_data_table_row().
 3827: 		$line.
 3828: 		&Apache::loncommon::end_data_table_row();
 3829: 	}
 3830:     }
 3831:     $result .= &Apache::loncommon::end_data_table().
 3832: 	&show_grading_menu_form($symb);
 3833:     my $msg = '<p><b>'.
 3834: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3835: 	    $rec_update,$count).'</b><br />'.
 3836: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3837: 	'</b></p>';
 3838:     return $title.$msg.$result;
 3839: }
 3840: 
 3841: sub split_part_type {
 3842:     my ($partstr) = @_;
 3843:     my ($temp,@allparts)=split(/_/,$partstr);
 3844:     my $type=pop(@allparts);
 3845:     my $part=join('_',@allparts);
 3846:     return ($part,$type);
 3847: }
 3848: 
 3849: #------------- end of section for handling grading by section/class ---------
 3850: #
 3851: #----------------------------------------------------------------------------
 3852: 
 3853: 
 3854: #----------------------------------------------------------------------------
 3855: #
 3856: #-------------------------- Next few routines handles grading by csv upload
 3857: #
 3858: #--- Javascript to handle csv upload
 3859: sub csvupload_javascript_reverse_associate {
 3860:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3861:     my $error2=&mt('You need to specify at least one grading field');
 3862:   return(<<ENDPICK);
 3863:   function verify(vf) {
 3864:     var foundsomething=0;
 3865:     var founduname=0;
 3866:     var foundID=0;
 3867:     for (i=0;i<=vf.nfields.value;i++) {
 3868:       tw=eval('vf.f'+i+'.selectedIndex');
 3869:       if (i==0 && tw!=0) { foundID=1; }
 3870:       if (i==1 && tw!=0) { founduname=1; }
 3871:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3872:     }
 3873:     if (founduname==0 && foundID==0) {
 3874: 	alert('$error1');
 3875: 	return;
 3876:     }
 3877:     if (foundsomething==0) {
 3878: 	alert('$error2');
 3879: 	return;
 3880:     }
 3881:     vf.submit();
 3882:   }
 3883:   function flip(vf,tf) {
 3884:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3885:     var i;
 3886:     for (i=0;i<=vf.nfields.value;i++) {
 3887:       //can not pick the same destination field for both name and domain
 3888:       if (((i ==0)||(i ==1)) && 
 3889:           ((tf==0)||(tf==1)) && 
 3890:           (i!=tf) &&
 3891:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3892:         eval('vf.f'+i+'.selectedIndex=0;')
 3893:       }
 3894:     }
 3895:   }
 3896: ENDPICK
 3897: }
 3898: 
 3899: sub csvupload_javascript_forward_associate {
 3900:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3901:     my $error2=&mt('You need to specify at least one grading field');
 3902:   return(<<ENDPICK);
 3903:   function verify(vf) {
 3904:     var foundsomething=0;
 3905:     var founduname=0;
 3906:     var foundID=0;
 3907:     for (i=0;i<=vf.nfields.value;i++) {
 3908:       tw=eval('vf.f'+i+'.selectedIndex');
 3909:       if (tw==1) { foundID=1; }
 3910:       if (tw==2) { founduname=1; }
 3911:       if (tw>3) { foundsomething=1; }
 3912:     }
 3913:     if (founduname==0 && foundID==0) {
 3914: 	alert('$error1');
 3915: 	return;
 3916:     }
 3917:     if (foundsomething==0) {
 3918: 	alert('$error2');
 3919: 	return;
 3920:     }
 3921:     vf.submit();
 3922:   }
 3923:   function flip(vf,tf) {
 3924:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3925:     var i;
 3926:     //can not pick the same destination field twice
 3927:     for (i=0;i<=vf.nfields.value;i++) {
 3928:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3929:         eval('vf.f'+i+'.selectedIndex=0;')
 3930:       }
 3931:     }
 3932:   }
 3933: ENDPICK
 3934: }
 3935: 
 3936: sub csvuploadmap_header {
 3937:     my ($request,$symb,$datatoken,$distotal)= @_;
 3938:     my $javascript;
 3939:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3940: 	$javascript=&csvupload_javascript_reverse_associate();
 3941:     } else {
 3942: 	$javascript=&csvupload_javascript_forward_associate();
 3943:     }
 3944: 
 3945:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3946:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3947:     my $ignore=&mt('Ignore First Line');
 3948:     $symb = &Apache::lonenc::check_encrypt($symb);
 3949:     $request->print(<<ENDPICK);
 3950: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3951: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3952: $result
 3953: <hr />
 3954: <h3>Identify fields</h3>
 3955: Total number of records found in file: $distotal <hr />
 3956: Enter as many fields as you can. The system will inform you and bring you back
 3957: to this page if the data selected is insufficient to run your class.<hr />
 3958: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3959: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3960: <input type="hidden" name="associate"  value="" />
 3961: <input type="hidden" name="phase"      value="three" />
 3962: <input type="hidden" name="datatoken"  value="$datatoken" />
 3963: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3964: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3965: <input type="hidden" name="upfile_associate" 
 3966:                                        value="$env{'form.upfile_associate'}" />
 3967: <input type="hidden" name="symb"       value="$symb" />
 3968: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3969: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3970: <input type="hidden" name="command"    value="csvuploadoptions" />
 3971: <hr />
 3972: <script type="text/javascript" language="Javascript">
 3973: $javascript
 3974: </script>
 3975: ENDPICK
 3976:     return '';
 3977: 
 3978: }
 3979: 
 3980: sub csvupload_fields {
 3981:     my ($symb,$errorref) = @_;
 3982:     my (@parts) = &getpartlist($symb,$errorref);
 3983:     if (ref($errorref)) {
 3984:         if ($$errorref) {
 3985:             return;
 3986:         }
 3987:     }
 3988: 
 3989:     my @fields=(['ID','Student/Employee ID'],
 3990: 		['username','Student Username'],
 3991: 		['domain','Student Domain']);
 3992:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3993:     foreach my $part (sort(@parts)) {
 3994: 	my @datum;
 3995: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3996: 	my $name=$part;
 3997: 	if  (!$display) { $display = $name; }
 3998: 	@datum=($name,$display);
 3999: 	if ($name=~/^stores_(.*)_awarded/) {
 4000: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4001: 	}
 4002: 	push(@fields,\@datum);
 4003:     }
 4004:     return (@fields);
 4005: }
 4006: 
 4007: sub csvuploadmap_footer {
 4008:     my ($request,$i,$keyfields) =@_;
 4009:     $request->print(<<ENDPICK);
 4010: </table>
 4011: <input type="hidden" name="nfields" value="$i" />
 4012: <input type="hidden" name="keyfields" value="$keyfields" />
 4013: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4014: </form>
 4015: ENDPICK
 4016: }
 4017: 
 4018: sub checkforfile_js {
 4019:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4020:     my $result =<<CSVFORMJS;
 4021: <script type="text/javascript" language="javascript">
 4022:     function checkUpload(formname) {
 4023: 	if (formname.upfile.value == "") {
 4024: 	    alert("$alertmsg");
 4025: 	    return false;
 4026: 	}
 4027: 	formname.submit();
 4028:     }
 4029:     </script>
 4030: CSVFORMJS
 4031:     return $result;
 4032: }
 4033: 
 4034: sub upcsvScores_form {
 4035:     my ($request) = shift;
 4036:     my ($symb)=&get_symb($request);
 4037:     if (!$symb) {return '';}
 4038:     my $result=&checkforfile_js();
 4039:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4040:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4041:     $result.=$table;
 4042:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4043:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4044:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4045: 	'</b></td></tr>'."\n";
 4046:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 4047:     my $upload=&mt("Upload Scores");
 4048:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4049:     my $ignore=&mt('Ignore First Line');
 4050:     $symb = &Apache::lonenc::check_encrypt($symb);
 4051:     $result.=<<ENDUPFORM;
 4052: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4053: <input type="hidden" name="symb" value="$symb" />
 4054: <input type="hidden" name="command" value="csvuploadmap" />
 4055: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4056: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4057: $upfile_select
 4058: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4059: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4060: </form>
 4061: ENDUPFORM
 4062:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4063:                            &mt("How do I create a CSV file from a spreadsheet"))
 4064:     .'</td></tr></table>'."\n";
 4065:     $result.='</td></tr></table><br /><br />'."\n";
 4066:     $result.=&show_grading_menu_form($symb);
 4067:     return $result;
 4068: }
 4069: 
 4070: 
 4071: sub csvuploadmap {
 4072:     my ($request)= @_;
 4073:     my ($symb)=&get_symb($request);
 4074:     if (!$symb) {return '';}
 4075: 
 4076:     my $datatoken;
 4077:     if (!$env{'form.datatoken'}) {
 4078: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4079:     } else {
 4080: 	$datatoken=$env{'form.datatoken'};
 4081: 	&Apache::loncommon::load_tmp_file($request);
 4082:     }
 4083:     my @records=&Apache::loncommon::upfile_record_sep();
 4084:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4085:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4086:     my ($i,$keyfields);
 4087:     if (@records) {
 4088:         my $fieldserror;
 4089: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4090:         if ($fieldserror) {
 4091:             $request->print(&navmap_errormsg());
 4092:             return;
 4093:         }
 4094: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4095: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4096: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4097: 							  \@fields);
 4098: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4099: 	    chop($keyfields);
 4100: 	} else {
 4101: 	    unshift(@fields,['none','']);
 4102: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4103: 							    \@fields);
 4104:             foreach my $rec (@records) {
 4105:                 my %temp = &Apache::loncommon::record_sep($rec);
 4106:                 if (%temp) {
 4107:                     $keyfields=join(',',sort(keys(%temp)));
 4108:                     last;
 4109:                 }
 4110:             }
 4111: 	}
 4112:     }
 4113:     &csvuploadmap_footer($request,$i,$keyfields);
 4114:     $request->print(&show_grading_menu_form($symb));
 4115: 
 4116:     return '';
 4117: }
 4118: 
 4119: sub csvuploadoptions {
 4120:     my ($request)= @_;
 4121:     my ($symb)=&get_symb($request);
 4122:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4123:     my $ignore=&mt('Ignore First Line');
 4124:     $request->print(<<ENDPICK);
 4125: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4126: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4127: <input type="hidden" name="command"    value="csvuploadassign" />
 4128: <!--
 4129: <p>
 4130: <label>
 4131:    <input type="checkbox" name="show_full_results" />
 4132:    Show a table of all changes
 4133: </label>
 4134: </p>
 4135: -->
 4136: <p>
 4137: <label>
 4138:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4139:    Overwrite any existing score
 4140: </label>
 4141: </p>
 4142: ENDPICK
 4143:     my %fields=&get_fields();
 4144:     if (!defined($fields{'domain'})) {
 4145: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4146: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4147:     }
 4148:     foreach my $key (sort(keys(%env))) {
 4149: 	if ($key !~ /^form\.(.*)$/) { next; }
 4150: 	my $cleankey=$1;
 4151: 	if ($cleankey eq 'command') { next; }
 4152: 	$request->print('<input type="hidden" name="'.$cleankey.
 4153: 			'"  value="'.$env{$key}.'" />'."\n");
 4154:     }
 4155:     # FIXME do a check for any duplicated user ids...
 4156:     # FIXME do a check for any invalid user ids?...
 4157:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4158: <hr /></form>'."\n");
 4159:     $request->print(&show_grading_menu_form($symb));
 4160:     return '';
 4161: }
 4162: 
 4163: sub get_fields {
 4164:     my %fields;
 4165:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4166:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4167: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4168: 	    if ($env{'form.f'.$i} ne 'none') {
 4169: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4170: 	    }
 4171: 	} else {
 4172: 	    if ($env{'form.f'.$i} ne 'none') {
 4173: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4174: 	    }
 4175: 	}
 4176:     }
 4177:     return %fields;
 4178: }
 4179: 
 4180: sub csvuploadassign {
 4181:     my ($request)= @_;
 4182:     my ($symb)=&get_symb($request);
 4183:     if (!$symb) {return '';}
 4184:     my $error_msg = '';
 4185:     &Apache::loncommon::load_tmp_file($request);
 4186:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4187:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4188:     my %fields=&get_fields();
 4189:     $request->print('<h3>Assigning Grades</h3>');
 4190:     my $courseid=$env{'request.course.id'};
 4191:     my ($classlist) = &getclasslist('all',0);
 4192:     my @notallowed;
 4193:     my @skipped;
 4194:     my $countdone=0;
 4195:     foreach my $grade (@gradedata) {
 4196: 	my %entries=&Apache::loncommon::record_sep($grade);
 4197: 	my $domain;
 4198: 	if ($entries{$fields{'domain'}}) {
 4199: 	    $domain=$entries{$fields{'domain'}};
 4200: 	} else {
 4201: 	    $domain=$env{'form.default_domain'};
 4202: 	}
 4203: 	$domain=~s/\s//g;
 4204: 	my $username=$entries{$fields{'username'}};
 4205: 	$username=~s/\s//g;
 4206: 	if (!$username) {
 4207: 	    my $id=$entries{$fields{'ID'}};
 4208: 	    $id=~s/\s//g;
 4209: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4210: 	    $username=$ids{$id};
 4211: 	}
 4212: 	if (!exists($$classlist{"$username:$domain"})) {
 4213: 	    my $id=$entries{$fields{'ID'}};
 4214: 	    $id=~s/\s//g;
 4215: 	    if ($id) {
 4216: 		push(@skipped,"$id:$domain");
 4217: 	    } else {
 4218: 		push(@skipped,"$username:$domain");
 4219: 	    }
 4220: 	    next;
 4221: 	}
 4222: 	my $usec=$classlist->{"$username:$domain"}[5];
 4223: 	if (!&canmodify($usec)) {
 4224: 	    push(@notallowed,"$username:$domain");
 4225: 	    next;
 4226: 	}
 4227: 	my %points;
 4228: 	my %grades;
 4229: 	foreach my $dest (keys(%fields)) {
 4230: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4231: 		$dest eq 'domain') { next; }
 4232: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4233: 	    if ($dest=~/stores_(.*)_points/) {
 4234: 		my $part=$1;
 4235: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4236: 					      $symb,$domain,$username);
 4237:                 if ($wgt) {
 4238:                     $entries{$fields{$dest}}=~s/\s//g;
 4239:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4240:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4241:                                           : 'correct_by_override';
 4242:                     $grades{"resource.$part.awarded"}=$pcr;
 4243:                     $grades{"resource.$part.solved"}=$award;
 4244:                     $points{$part}=1;
 4245:                 } else {
 4246:                     $error_msg = "<br />" .
 4247:                         &mt("Some point values were assigned"
 4248:                             ." for problems with a weight "
 4249:                             ."of zero. These values were "
 4250:                             ."ignored.");
 4251:                 }
 4252: 	    } else {
 4253: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4254: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4255: 		my $store_key=$dest;
 4256: 		$store_key=~s/^stores/resource/;
 4257: 		$store_key=~s/_/\./g;
 4258: 		$grades{$store_key}=$entries{$fields{$dest}};
 4259: 	    }
 4260: 	}
 4261: 	if (! %grades) { 
 4262:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4263:         } else {
 4264: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4265: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4266: 					   $env{'request.course.id'},
 4267: 					   $domain,$username);
 4268: 	   if ($result eq 'ok') {
 4269: 	      $request->print('.');
 4270: 	   } else {
 4271: 	      $request->print("<p><span class=\"LC_error\">".
 4272:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4273:                                   "$username:$domain",$result)."</span></p>");
 4274: 	   }
 4275: 	   $request->rflush();
 4276: 	   $countdone++;
 4277:         }
 4278:     }
 4279:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4280:     if (@skipped) {
 4281: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4282:         $request->print(join(', ',@skipped));
 4283:     }
 4284:     if (@notallowed) {
 4285: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4286: 	$request->print(join(', ',@notallowed));
 4287:     }
 4288:     $request->print("<br />\n");
 4289:     $request->print(&show_grading_menu_form($symb));
 4290:     return $error_msg;
 4291: }
 4292: #------------- end of section for handling csv file upload ---------
 4293: #
 4294: #-------------------------------------------------------------------
 4295: #
 4296: #-------------- Next few routines handle grading by page/sequence
 4297: #
 4298: #--- Select a page/sequence and a student to grade
 4299: sub pickStudentPage {
 4300:     my ($request) = shift;
 4301: 
 4302:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4303:     $request->print(<<LISTJAVASCRIPT);
 4304: <script type="text/javascript" language="javascript">
 4305: 
 4306: function checkPickOne(formname) {
 4307:     if (radioSelection(formname.student) == null) {
 4308: 	alert("$alertmsg");
 4309: 	return;
 4310:     }
 4311:     ptr = pullDownSelection(formname.selectpage);
 4312:     formname.page.value = formname["page"+ptr].value;
 4313:     formname.title.value = formname["title"+ptr].value;
 4314:     formname.submit();
 4315: }
 4316: 
 4317: </script>
 4318: LISTJAVASCRIPT
 4319:     &commonJSfunctions($request);
 4320:     my ($symb) = &get_symb($request);
 4321:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4322:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4323:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4324: 
 4325:     my $result='<h3><span class="LC_info">&nbsp;'.
 4326: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4327: 
 4328:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4329:     my $map_error;
 4330:     my ($titles,$symbx) = &getSymbMap($map_error);
 4331:     if ($map_error) {
 4332:         $request->print(&navmap_errormsg());
 4333:         return; 
 4334:     }
 4335:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4336: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4337: #    my $type=($curpage =~ /\.(page|sequence)/);
 4338:     my $select = '<select name="selectpage">'."\n";
 4339:     my $ctr=0;
 4340:     foreach (@$titles) {
 4341: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4342: 	$select.='<option value="'.$ctr.'" '.
 4343: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4344: 	    '>'.$showtitle.'</option>'."\n";
 4345: 	$ctr++;
 4346:     }
 4347:     $select.= '</select>';
 4348:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4349: 
 4350:     $ctr=0;
 4351:     foreach (@$titles) {
 4352: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4353: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4354: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4355: 	$ctr++;
 4356:     }
 4357:     $result.='<input type="hidden" name="page" />'."\n".
 4358: 	'<input type="hidden" name="title" />'."\n";
 4359: 
 4360:     my $options =
 4361: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4362: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4363:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4364: 
 4365:     $options =
 4366: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4367: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4368: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4369:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4370:     
 4371:     $result.=&build_section_inputs();
 4372:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4373:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4374: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4375: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4376: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4377: 
 4378:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4379: 
 4380:     $result.='&nbsp;<input type="button" '.
 4381:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4382: 
 4383:     $request->print($result);
 4384: 
 4385:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4386: 	&Apache::loncommon::start_data_table().
 4387: 	&Apache::loncommon::start_data_table_header_row().
 4388: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4389: 	'<th>'.&nameUserString('header').'</th>'.
 4390: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4391: 	'<th>'.&nameUserString('header').'</th>'.
 4392: 	&Apache::loncommon::end_data_table_header_row();
 4393:  
 4394:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4395:     my $ptr = 1;
 4396:     foreach my $student (sort 
 4397: 			 {
 4398: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4399: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4400: 			     }
 4401: 			     return $a cmp $b;
 4402: 			 } (keys(%$fullname))) {
 4403: 	my ($uname,$udom) = split(/:/,$student);
 4404: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4405:                                   : '</td>');
 4406: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4407: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4408: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4409: 	$studentTable.=
 4410: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4411:                          : '');
 4412: 	$ptr++;
 4413:     }
 4414:     if ($ptr%2 == 0) {
 4415: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4416: 	    &Apache::loncommon::end_data_table_row();
 4417:     }
 4418:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4419:     $studentTable.='<input type="button" '.
 4420:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4421: 
 4422:     $studentTable.=&show_grading_menu_form($symb);
 4423:     $request->print($studentTable);
 4424: 
 4425:     return '';
 4426: }
 4427: 
 4428: sub getSymbMap {
 4429:     my ($map_error) = @_;
 4430:     my $navmap = Apache::lonnavmaps::navmap->new();
 4431:     unless (ref($navmap)) {
 4432:         if (ref($map_error)) {
 4433:             $$map_error = 'navmap';
 4434:         }
 4435:         return;
 4436:     }
 4437:     my %symbx = ();
 4438:     my @titles = ();
 4439:     my $minder = 0;
 4440: 
 4441:     # Gather every sequence that has problems.
 4442:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4443: 					       1,0,1);
 4444:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4445: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4446: 	    my $title = $minder.'.'.
 4447: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4448: 	    push(@titles, $title); # minder in case two titles are identical
 4449: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4450: 	    $minder++;
 4451: 	}
 4452:     }
 4453:     return \@titles,\%symbx;
 4454: }
 4455: 
 4456: #
 4457: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4458: sub displayPage {
 4459:     my ($request) = shift;
 4460: 
 4461:     my ($symb) = &get_symb($request);
 4462:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4463:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4464:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4465:     my $pageTitle = $env{'form.page'};
 4466:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4467:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4468:     my $usec=$classlist->{$env{'form.student'}}[5];
 4469: 
 4470:     #need to make sure we have the correct data for later EXT calls, 
 4471:     #thus invalidate the cache
 4472:     &Apache::lonnet::devalidatecourseresdata(
 4473:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4474:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4475:     &Apache::lonnet::clear_EXT_cache_status();
 4476: 
 4477:     if (!&canview($usec)) {
 4478: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4479: 	$request->print(&show_grading_menu_form($symb));
 4480: 	return;
 4481:     }
 4482:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4483:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4484: 	'</h3>'."\n";
 4485:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4486:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4487: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4488:     } else {
 4489: 	delete($env{'form.CODE'});
 4490:     }
 4491:     &sub_page_js($request);
 4492:     $request->print($result);
 4493: 
 4494:     my $navmap = Apache::lonnavmaps::navmap->new();
 4495:     unless (ref($navmap)) {
 4496:         $request->print(&navmap_errormsg());
 4497:         $request->print(&show_grading_menu_form($symb));
 4498:         return;
 4499:     }
 4500:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4501:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4502:     if (!$map) {
 4503: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4504: 	$request->print(&show_grading_menu_form($symb));
 4505: 	return; 
 4506:     }
 4507:     my $iterator = $navmap->getIterator($map->map_start(),
 4508: 					$map->map_finish());
 4509: 
 4510:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4511: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4512: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4513: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4514: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4515: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4516: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4517: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4518: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4519: 
 4520:     if (defined($env{'form.CODE'})) {
 4521: 	$studentTable.=
 4522: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4523:     }
 4524:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4525: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4526: 
 4527:     $studentTable.='&nbsp;<span class="LC_info">'.
 4528:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4529:         '</span>'."\n".
 4530: 	&Apache::loncommon::start_data_table().
 4531: 	&Apache::loncommon::start_data_table_header_row().
 4532: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4533: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4534: 	&Apache::loncommon::end_data_table_header_row();
 4535: 
 4536:     &Apache::lonxml::clear_problem_counter();
 4537:     my ($depth,$question,$prob) = (1,1,1);
 4538:     $iterator->next(); # skip the first BEGIN_MAP
 4539:     my $curRes = $iterator->next(); # for "current resource"
 4540:     while ($depth > 0) {
 4541:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4542:         if($curRes == $iterator->END_MAP) { $depth--; }
 4543: 
 4544:         if (ref($curRes) && $curRes->is_problem()) {
 4545: 	    my $parts = $curRes->parts();
 4546:             my $title = $curRes->compTitle();
 4547: 	    my $symbx = $curRes->symb();
 4548: 	    $studentTable.=
 4549: 		&Apache::loncommon::start_data_table_row().
 4550: 		'<td align="center" valign="top" >'.$prob.
 4551: 		(scalar(@{$parts}) == 1 ? '' 
 4552: 		                        : '<br />('.&mt('[_1]parts)',
 4553: 							scalar(@{$parts}).'&nbsp;')
 4554: 		 ).
 4555: 		 '</td>';
 4556: 	    $studentTable.='<td valign="top">';
 4557: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4558: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4559: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4560: 					     undef,'both',\%form);
 4561: 	    } else {
 4562: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4563: 		$companswer =~ s|<form(.*?)>||g;
 4564: 		$companswer =~ s|</form>||g;
 4565: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4566: #		    $companswer =~ s/$1/ /ms;
 4567: #		    $request->print('match='.$1."<br />\n");
 4568: #		}
 4569: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4570: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4571: 	    }
 4572: 
 4573: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4574: 
 4575: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4576: 		if ($record{'version'} eq '') {
 4577: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4578: 		} else {
 4579: 		    my %responseType = ();
 4580: 		    foreach my $partid (@{$parts}) {
 4581: 			my @responseIds =$curRes->responseIds($partid);
 4582: 			my @responseType =$curRes->responseType($partid);
 4583: 			my %responseIds;
 4584: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4585: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4586: 			}
 4587: 			$responseType{$partid} = \%responseIds;
 4588: 		    }
 4589: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4590: 
 4591: 		}
 4592: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4593: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4594: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4595: 									$env{'request.course.id'},
 4596: 									'','.submission');
 4597:  
 4598: 	    }
 4599: 	    if (&canmodify($usec)) {
 4600:             $studentTable.=&gradeBox_start();
 4601: 		foreach my $partid (@{$parts}) {
 4602: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4603: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4604: 		    $question++;
 4605: 		}
 4606:             $studentTable.=&gradeBox_end();
 4607: 		$prob++;
 4608: 	    }
 4609: 	    $studentTable.='</td></tr>';
 4610: 
 4611: 	}
 4612:         $curRes = $iterator->next();
 4613:     }
 4614: 
 4615:     $studentTable.=
 4616:         '</table>'."\n".
 4617:         '<input type="button" value="'.&mt('Save').'" '.
 4618:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4619:         '</form>'."\n";
 4620:     $studentTable.=&show_grading_menu_form($symb);
 4621:     $request->print($studentTable);
 4622: 
 4623:     return '';
 4624: }
 4625: 
 4626: sub displaySubByDates {
 4627:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4628:     my $isCODE=0;
 4629:     my $isTask = ($symb =~/\.task$/);
 4630:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4631:     my $studentTable=&Apache::loncommon::start_data_table().
 4632: 	&Apache::loncommon::start_data_table_header_row().
 4633: 	'<th>'.&mt('Date/Time').'</th>'.
 4634: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4635: 	'<th>'.&mt('Submission').'</th>'.
 4636: 	'<th>'.&mt('Status').'</th>'.
 4637: 	&Apache::loncommon::end_data_table_header_row();
 4638:     my ($version);
 4639:     my %mark;
 4640:     my %orders;
 4641:     $mark{'correct_by_student'} = $checkIcon;
 4642:     if (!exists($$record{'1:timestamp'})) {
 4643: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4644:     }
 4645: 
 4646:     my $interaction;
 4647:     my $no_increment = 1;
 4648:     my %lastrndseed;
 4649:     for ($version=1;$version<=$$record{'version'};$version++) {
 4650: 	my $timestamp = 
 4651: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4652: 	if (exists($$record{$version.':resource.0.version'})) {
 4653: 	    $interaction = $$record{$version.':resource.0.version'};
 4654: 	}
 4655: 
 4656: 	my $where = ($isTask ? "$version:resource.$interaction"
 4657: 		             : "$version:resource");
 4658: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4659: 	    '<td>'.$timestamp.'</td>';
 4660: 	if ($isCODE) {
 4661: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4662: 	}
 4663: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4664: 	my @displaySub = ();
 4665: 	foreach my $partid (@{$parts}) {
 4666:             my ($hidden,$type);
 4667:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4668:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4669:                 $hidden = 1;
 4670:             }
 4671: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4672: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4673: 	    
 4674: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4675: 	    my $display_part=&get_display_part($partid,$symb);
 4676: 	    foreach my $matchKey (@matchKey) {
 4677: 		if (exists($$record{$version.':'.$matchKey}) &&
 4678: 		    $$record{$version.':'.$matchKey} ne '') {
 4679:                     
 4680: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4681: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4682:                     $displaySub[0].='<span class="LC_nobreak"';
 4683:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4684:                                    .' <span class="LC_internal_info">'
 4685:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4686:                                    .'</span>'
 4687:                                    .' <b>';
 4688:                     if ($hidden) {
 4689:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4690:                     } else {
 4691:                         my ($trial,$rndseed,$newvariation);
 4692:                         if ($type eq 'randomizetry') {
 4693:                             $trial = $$record{"$where.$partid.tries"};
 4694:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4695:                         }
 4696: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4697: 			    $displaySub[0].=&mt('Trial not counted');
 4698: 		        } else {
 4699: 			    $displaySub[0].=&mt('Trial: [_1]',
 4700: 					    $$record{"$where.$partid.tries"});
 4701:                             if ($rndseed || $lastrndseed{$partid}) {
 4702:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4703:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4704:                                 }
 4705:                             }
 4706: 		        }
 4707: 		        my $responseType=($isTask ? 'Task'
 4708:                                               : $responseType->{$partid}->{$responseId});
 4709: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4710: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4711: 			    $orders{$partid}->{$responseId}=
 4712: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4713:                                            $no_increment,$type,$trial,$rndseed);
 4714: 		        }
 4715: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4716: 		        $displaySub[0].='&nbsp; '.
 4717: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4718:                     }
 4719: 		}
 4720: 	    }
 4721: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4722: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4723: 				    $$record{"$where.$partid.checkedin"},
 4724: 				    $$record{"$where.$partid.checkedin.slot"}).
 4725: 					'<br />';
 4726: 	    }
 4727: 	    if (exists $$record{"$where.$partid.award"}) {
 4728: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4729: 		    lc($$record{"$where.$partid.award"}).' '.
 4730: 		    $mark{$$record{"$where.$partid.solved"}}.
 4731: 		    '<br />';
 4732: 	    }
 4733: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4734: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4735: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4736: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4737: 		$displaySub[2].=
 4738: 		    $$record{"$version:resource.$partid.regrader"}.
 4739: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4740: 	    }
 4741: 	}
 4742: 	# needed because old essay regrader has not parts info
 4743: 	if (exists $$record{"$version:resource.regrader"}) {
 4744: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4745: 	}
 4746: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4747: 	if ($displaySub[2]) {
 4748: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4749: 	}
 4750: 	$studentTable.='&nbsp;</td>'.
 4751: 	    &Apache::loncommon::end_data_table_row();
 4752:     }
 4753:     $studentTable.=&Apache::loncommon::end_data_table();
 4754:     return $studentTable;
 4755: }
 4756: 
 4757: sub updateGradeByPage {
 4758:     my ($request) = shift;
 4759: 
 4760:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4761:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4762:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4763:     my $pageTitle = $env{'form.page'};
 4764:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4765:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4766:     my $usec=$classlist->{$env{'form.student'}}[5];
 4767:     if (!&canmodify($usec)) {
 4768: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4769: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4770: 	return;
 4771:     }
 4772:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4773:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4774: 	'</h3>'."\n";
 4775: 
 4776:     $request->print($result);
 4777: 
 4778: 
 4779:     my $navmap = Apache::lonnavmaps::navmap->new();
 4780:     unless (ref($navmap)) {
 4781:         $request->print(&navmap_errormsg());
 4782:         return;
 4783:     }
 4784:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4785:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4786:     if (!$map) {
 4787: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4788: 	my ($symb)=&get_symb($request);
 4789: 	$request->print(&show_grading_menu_form($symb));
 4790: 	return; 
 4791:     }
 4792:     my $iterator = $navmap->getIterator($map->map_start(),
 4793: 					$map->map_finish());
 4794: 
 4795:     my $studentTable=
 4796: 	&Apache::loncommon::start_data_table().
 4797: 	&Apache::loncommon::start_data_table_header_row().
 4798: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4799: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4800: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4801: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4802: 	&Apache::loncommon::end_data_table_header_row();
 4803: 
 4804:     $iterator->next(); # skip the first BEGIN_MAP
 4805:     my $curRes = $iterator->next(); # for "current resource"
 4806:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4807:     while ($depth > 0) {
 4808:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4809:         if($curRes == $iterator->END_MAP) { $depth--; }
 4810: 
 4811:         if (ref($curRes) && $curRes->is_problem()) {
 4812: 	    my $parts = $curRes->parts();
 4813:             my $title = $curRes->compTitle();
 4814: 	    my $symbx = $curRes->symb();
 4815: 	    $studentTable.=
 4816: 		&Apache::loncommon::start_data_table_row().
 4817: 		'<td align="center" valign="top" >'.$prob.
 4818: 		(scalar(@{$parts}) == 1 ? '' 
 4819:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4820: 		.')').'</td>';
 4821: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4822: 
 4823: 	    my %newrecord=();
 4824: 	    my @displayPts=();
 4825:             my %aggregate = ();
 4826:             my $aggregateflag = 0;
 4827: 	    foreach my $partid (@{$parts}) {
 4828: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4829: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4830: 
 4831: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4832: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4833: 		my $partial = $newpts/$wgt;
 4834: 		my $score;
 4835: 		if ($partial > 0) {
 4836: 		    $score = 'correct_by_override';
 4837: 		} elsif ($newpts ne '') { #empty is taken as 0
 4838: 		    $score = 'incorrect_by_override';
 4839: 		}
 4840: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4841: 		if ($dropMenu eq 'excused') {
 4842: 		    $partial = '';
 4843: 		    $score = 'excused';
 4844: 		} elsif ($dropMenu eq 'reset status'
 4845: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4846: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4847: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4848: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4849: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4850: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4851: 		    $changeflag++;
 4852: 		    $newpts = '';
 4853:                     
 4854:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4855:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4856:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4857:                     if ($aggtries > 0) {
 4858:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4859:                         $aggregateflag = 1;
 4860:                     }
 4861: 		}
 4862: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4863: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4864: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4865: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4866: 		    '&nbsp;<br />';
 4867: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4868: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4869: 		    '&nbsp;<br />';
 4870: 		$question++;
 4871: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4872: 
 4873: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4874: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4875: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4876: 		    if (scalar(keys(%newrecord)) > 0);
 4877: 
 4878: 		$changeflag++;
 4879: 	    }
 4880: 	    if (scalar(keys(%newrecord)) > 0) {
 4881: 		my %record = 
 4882: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4883: 					     $udom,$uname);
 4884: 
 4885: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4886: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4887: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4888: 		    $newrecord{'resource.CODE'} = '';
 4889: 		}
 4890: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4891: 					$udom,$uname);
 4892: 		%record = &Apache::lonnet::restore($symbx,
 4893: 						   $env{'request.course.id'},
 4894: 						   $udom,$uname);
 4895: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4896: 					     $cdom,$cnum,$udom,$uname);
 4897: 	    }
 4898: 	    
 4899:             if ($aggregateflag) {
 4900:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4901:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4902:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4903:             }
 4904: 
 4905: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4906: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4907: 		&Apache::loncommon::end_data_table_row();
 4908: 
 4909: 	    $prob++;
 4910: 	}
 4911:         $curRes = $iterator->next();
 4912:     }
 4913: 
 4914:     $studentTable.=&Apache::loncommon::end_data_table();
 4915:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4916:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4917: 		  &mt('The scores were changed for [quant,_1,problem].',
 4918: 		  $changeflag));
 4919:     $request->print($grademsg.$studentTable);
 4920: 
 4921:     return '';
 4922: }
 4923: 
 4924: #-------- end of section for handling grading by page/sequence ---------
 4925: #
 4926: #-------------------------------------------------------------------
 4927: 
 4928: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4929: #
 4930: #------ start of section for handling grading by page/sequence ---------
 4931: 
 4932: =pod
 4933: 
 4934: =head1 Bubble sheet grading routines
 4935: 
 4936:   For this documentation:
 4937: 
 4938:    'scanline' refers to the full line of characters
 4939:    from the file that we are parsing that represents one entire sheet
 4940: 
 4941:    'bubble line' refers to the data
 4942:    representing the line of bubbles that are on the physical bubble sheet
 4943: 
 4944: 
 4945: The overall process is that a scanned in bubble sheet data is uploaded
 4946: into a course. When a user wants to grade, they select a
 4947: sequence/folder of resources, a file of bubble sheet info, and pick
 4948: one of the predefined configurations for what each scanline looks
 4949: like.
 4950: 
 4951: Next each scanline is checked for any errors of either 'missing
 4952: bubbles' (it's an error because it may have been mis-scanned
 4953: because too light bubbling), 'double bubble' (each bubble line should
 4954: have no more that one letter picked), invalid or duplicated CODE,
 4955: invalid student/employee ID
 4956: 
 4957: If the CODE option is used that determines the randomization of the
 4958: homework problems, either way the student/employee ID is looked up into a
 4959: username:domain.
 4960: 
 4961: During the validation phase the instructor can choose to skip scanlines. 
 4962: 
 4963: After the validation phase, there are now 3 bubble sheet files
 4964: 
 4965:   scantron_original_filename (unmodified original file)
 4966:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4967:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4968: 
 4969: Also there is a separate hash nohist_scantrondata that contains extra
 4970: correction information that isn't representable in the bubble sheet
 4971: file (see &scantron_getfile() for more information)
 4972: 
 4973: After all scanlines are either valid, marked as valid or skipped, then
 4974: foreach line foreach problem in the picked sequence, an ssi request is
 4975: made that simulates a user submitting their selected letter(s) against
 4976: the homework problem.
 4977: 
 4978: =over 4
 4979: 
 4980: 
 4981: 
 4982: =item defaultFormData
 4983: 
 4984:   Returns html hidden inputs used to hold context/default values.
 4985: 
 4986:  Arguments:
 4987:   $symb - $symb of the current resource 
 4988: 
 4989: =cut
 4990: 
 4991: sub defaultFormData {
 4992:     my ($symb)=@_;
 4993:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4994:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4995:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4996: }
 4997: 
 4998: 
 4999: =pod 
 5000: 
 5001: =item getSequenceDropDown
 5002: 
 5003:    Return html dropdown of possible sequences to grade
 5004:  
 5005:  Arguments:
 5006:    $symb - $symb of the current resource
 5007:    $map_error - ref to scalar which will container error if
 5008:                 $navmap object is unavailable in &getSymbMap().
 5009: 
 5010: =cut
 5011: 
 5012: sub getSequenceDropDown {
 5013:     my ($symb,$map_error)=@_;
 5014:     my $result='<select name="selectpage">'."\n";
 5015:     my ($titles,$symbx) = &getSymbMap($map_error);
 5016:     if (ref($map_error)) {
 5017:         return if ($$map_error);
 5018:     }
 5019:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5020:     my $ctr=0;
 5021:     foreach (@$titles) {
 5022: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5023: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5024: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5025: 	    '>'.$showtitle.'</option>'."\n";
 5026: 	$ctr++;
 5027:     }
 5028:     $result.= '</select>';
 5029:     return $result;
 5030: }
 5031: 
 5032: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5033:                                    # key is zero-based index - 0, 1, 2 ...
 5034: 
 5035: my %first_bubble_line;             # First bubble line no. for each bubble.
 5036: 
 5037: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5038:                                    # matchresponse or rankresponse, where 
 5039:                                    # an individual response can have multiple 
 5040:                                    # lines
 5041: 
 5042: my %responsetype_per_response;     # responsetype for each response
 5043: 
 5044: # Save and restore the bubble lines array to the form env.
 5045: 
 5046: 
 5047: sub save_bubble_lines {
 5048:     foreach my $line (keys(%bubble_lines_per_response)) {
 5049: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5050: 	$env{"form.scantron.first_bubble_line.$line"} =
 5051: 	    $first_bubble_line{$line};
 5052:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5053:             $subdivided_bubble_lines{$line};
 5054:         $env{"form.scantron.responsetype.$line"} =
 5055:             $responsetype_per_response{$line};
 5056:     }
 5057: }
 5058: 
 5059: 
 5060: sub restore_bubble_lines {
 5061:     my $line = 0;
 5062:     %bubble_lines_per_response = ();
 5063:     while ($env{"form.scantron.bubblelines.$line"}) {
 5064: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5065: 	$bubble_lines_per_response{$line} = $value;
 5066: 	$first_bubble_line{$line}  =
 5067: 	    $env{"form.scantron.first_bubble_line.$line"};
 5068:         $subdivided_bubble_lines{$line} =
 5069:             $env{"form.scantron.sub_bubblelines.$line"};
 5070:         $responsetype_per_response{$line} =
 5071:             $env{"form.scantron.responsetype.$line"};
 5072: 	$line++;
 5073:     }
 5074: }
 5075: 
 5076: #  Given the parsed scanline, get the response for 
 5077: #  'answer' number n:
 5078: 
 5079: sub get_response_bubbles {
 5080:     my ($parsed_line, $response)  = @_;
 5081: 
 5082:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5083:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5084:     
 5085:     my $selected = "";
 5086: 
 5087:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5088: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5089: 	$bubble_line++;
 5090:     }
 5091:     return $selected;
 5092: }
 5093: 
 5094: =pod 
 5095: 
 5096: =item scantron_filenames
 5097: 
 5098:    Returns a list of the scantron files in the current course 
 5099: 
 5100: =cut
 5101: 
 5102: sub scantron_filenames {
 5103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5104:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5105:     my $getpropath = 1;
 5106:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5107:                                        $getpropath);
 5108:     my @possiblenames;
 5109:     foreach my $filename (sort(@files)) {
 5110: 	($filename)=split(/&/,$filename);
 5111: 	if ($filename!~/^scantron_orig_/) { next ; }
 5112: 	$filename=~s/^scantron_orig_//;
 5113: 	push(@possiblenames,$filename);
 5114:     }
 5115:     return @possiblenames;
 5116: }
 5117: 
 5118: =pod 
 5119: 
 5120: =item scantron_uploads
 5121: 
 5122:    Returns  html drop-down list of scantron files in current course.
 5123: 
 5124:  Arguments:
 5125:    $file2grade - filename to set as selected in the dropdown
 5126: 
 5127: =cut
 5128: 
 5129: sub scantron_uploads {
 5130:     my ($file2grade) = @_;
 5131:     my $result=	'<select name="scantron_selectfile">';
 5132:     $result.="<option></option>";
 5133:     foreach my $filename (sort(&scantron_filenames())) {
 5134: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5135:     }
 5136:     $result.="</select>";
 5137:     return $result;
 5138: }
 5139: 
 5140: =pod 
 5141: 
 5142: =item scantron_scantab
 5143: 
 5144:   Returns html drop down of the scantron formats in the scantronformat.tab
 5145:   file.
 5146: 
 5147: =cut
 5148: 
 5149: sub scantron_scantab {
 5150:     my $result='<select name="scantron_format">'."\n";
 5151:     $result.='<option></option>'."\n";
 5152:     my @lines = &get_scantronformat_file();
 5153:     if (@lines > 0) {
 5154:         foreach my $line (@lines) {
 5155:             next if (($line =~ /^\#/) || ($line eq ''));
 5156: 	    my ($name,$descrip)=split(/:/,$line);
 5157: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5158:         }
 5159:     }
 5160:     $result.='</select>'."\n";
 5161:     return $result;
 5162: }
 5163: 
 5164: =pod
 5165: 
 5166: =item get_scantronformat_file
 5167: 
 5168:   Returns an array containing lines from the scantron format file for
 5169:   the domain of the course.
 5170: 
 5171:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5172:   lines are from this file.
 5173: 
 5174:   Otherwise, if a default.tab has been published in RES space by the 
 5175:   domainconfig user, lines are from this file.
 5176: 
 5177:   Otherwise, fall back to getting lines from the legacy file on the
 5178:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5179: 
 5180: =cut
 5181: 
 5182: sub get_scantronformat_file {
 5183:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5184:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5185:     my $gottab = 0;
 5186:     my @lines;
 5187:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5188:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5189:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5190:             if ($formatfile ne '-1') {
 5191:                 @lines = split("\n",$formatfile,-1);
 5192:                 $gottab = 1;
 5193:             }
 5194:         }
 5195:     }
 5196:     if (!$gottab) {
 5197:         my $confname = $cdom.'-domainconfig';
 5198:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5199:         my $formatfile =  &Apache::lonnet::getfile($default);
 5200:         if ($formatfile ne '-1') {
 5201:             @lines = split("\n",$formatfile,-1);
 5202:             $gottab = 1;
 5203:         }
 5204:     }
 5205:     if (!$gottab) {
 5206:         my @domains = &Apache::lonnet::current_machine_domains();
 5207:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5208:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5209:             @lines = <$fh>;
 5210:             close($fh);
 5211:         } else {
 5212:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5213:             @lines = <$fh>;
 5214:             close($fh);
 5215:         }
 5216:     }
 5217:     return @lines;
 5218: }
 5219: 
 5220: =pod 
 5221: 
 5222: =item scantron_CODElist
 5223: 
 5224:   Returns html drop down of the saved CODE lists from current course,
 5225:   generated from earlier printings.
 5226: 
 5227: =cut
 5228: 
 5229: sub scantron_CODElist {
 5230:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5231:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5232:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5233:     my $namechoice='<option></option>';
 5234:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5235: 	if ($name =~ /^error: 2 /) { next; }
 5236: 	if ($name =~ /^type\0/) { next; }
 5237: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5238:     }
 5239:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5240:     return $namechoice;
 5241: }
 5242: 
 5243: =pod 
 5244: 
 5245: =item scantron_CODEunique
 5246: 
 5247:   Returns the html for "Each CODE to be used once" radio.
 5248: 
 5249: =cut
 5250: 
 5251: sub scantron_CODEunique {
 5252:     my $result='<span class="LC_nobreak">
 5253:                  <label><input type="radio" name="scantron_CODEunique"
 5254:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5255:                 </span>
 5256:                 <span class="LC_nobreak">
 5257:                  <label><input type="radio" name="scantron_CODEunique"
 5258:                         value="no" />'.&mt('No').' </label>
 5259:                 </span>';
 5260:     return $result;
 5261: }
 5262: 
 5263: =pod 
 5264: 
 5265: =item scantron_selectphase
 5266: 
 5267:   Generates the initial screen to start the bubble sheet process.
 5268:   Allows for - starting a grading run.
 5269:              - downloading existing scan data (original, corrected
 5270:                                                 or skipped info)
 5271: 
 5272:              - uploading new scan data
 5273: 
 5274:  Arguments:
 5275:   $r          - The Apache request object
 5276:   $file2grade - name of the file that contain the scanned data to score
 5277: 
 5278: =cut
 5279: 
 5280: sub scantron_selectphase {
 5281:     my ($r,$file2grade) = @_;
 5282:     my ($symb)=&get_symb($r);
 5283:     if (!$symb) {return '';}
 5284:     my $map_error;
 5285:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5286:     if ($map_error) {
 5287:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5288:         return;
 5289:     }
 5290:     my $default_form_data=&defaultFormData($symb);
 5291:     my $grading_menu_button=&show_grading_menu_form($symb);
 5292:     my $file_selector=&scantron_uploads($file2grade);
 5293:     my $format_selector=&scantron_scantab();
 5294:     my $CODE_selector=&scantron_CODElist();
 5295:     my $CODE_unique=&scantron_CODEunique();
 5296:     my $result;
 5297: 
 5298:     $ssi_error = 0;
 5299: 
 5300:     # Chunk of form to prompt for a file to grade and how:
 5301: 
 5302:     $result.= '
 5303:     <br />
 5304:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5305:     <input type="hidden" name="command" value="scantron_warning" />
 5306:     '.$default_form_data.'
 5307:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5308:        '.&Apache::loncommon::start_data_table_header_row().'
 5309:             <th colspan="2">
 5310:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5311:             </th>
 5312:        '.&Apache::loncommon::end_data_table_header_row().'
 5313:        '.&Apache::loncommon::start_data_table_row().'
 5314:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5315:        '.&Apache::loncommon::end_data_table_row().'
 5316:        '.&Apache::loncommon::start_data_table_row().'
 5317:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5318:        '.&Apache::loncommon::end_data_table_row().'
 5319:        '.&Apache::loncommon::start_data_table_row().'
 5320:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5321:        '.&Apache::loncommon::end_data_table_row().'
 5322:        '.&Apache::loncommon::start_data_table_row().'
 5323:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5324:        '.&Apache::loncommon::end_data_table_row().'
 5325:        '.&Apache::loncommon::start_data_table_row().'
 5326:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5327:        '.&Apache::loncommon::end_data_table_row().'
 5328:        '.&Apache::loncommon::start_data_table_row().'
 5329: 	    <td> '.&mt('Options:').' </td>
 5330:             <td>
 5331: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5332:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5333:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5334: 	    </td>
 5335:        '.&Apache::loncommon::end_data_table_row().'
 5336:        '.&Apache::loncommon::start_data_table_row().'
 5337:             <td colspan="2">
 5338:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5339:             </td>
 5340:        '.&Apache::loncommon::end_data_table_row().'
 5341:     '.&Apache::loncommon::end_data_table().'
 5342:     </form>
 5343: ';
 5344:    
 5345:     $r->print($result);
 5346: 
 5347:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5348:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5349: 
 5350: 	# Chunk of form to prompt for a scantron file upload.
 5351: 
 5352:         $r->print('
 5353:     <br />
 5354:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5355:        '.&Apache::loncommon::start_data_table_header_row().'
 5356:             <th>
 5357:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5358:             </th>
 5359:        '.&Apache::loncommon::end_data_table_header_row().'
 5360:        '.&Apache::loncommon::start_data_table_row().'
 5361:             <td>
 5362: ');
 5363:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5364:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5365:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5366:     $r->print('
 5367:               <script type="text/javascript" language="javascript">
 5368:     function checkUpload(formname) {
 5369: 	if (formname.upfile.value == "") {
 5370: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5371: 	    return false;
 5372: 	}
 5373: 	formname.submit();
 5374:     }
 5375:               </script>
 5376: 
 5377:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5378:                 '.$default_form_data.'
 5379:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5380:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5381:                 <input name="command" value="scantronupload_save" type="hidden" />
 5382:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5383:                 <br />
 5384:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5385:               </form>
 5386: ');
 5387: 
 5388:         $r->print('
 5389:             </td>
 5390:        '.&Apache::loncommon::end_data_table_row().'
 5391:        '.&Apache::loncommon::end_data_table().'
 5392: ');
 5393:     }
 5394: 
 5395:     # Chunk of the form that prompts to view a scoring office file,
 5396:     # corrected file, skipped records in a file.
 5397: 
 5398:     $r->print('
 5399:    <br />
 5400:    <form action="/adm/grades" name="scantron_download">
 5401:      '.$default_form_data.'
 5402:      <input type="hidden" name="command" value="scantron_download" />
 5403:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5404:        '.&Apache::loncommon::start_data_table_header_row().'
 5405:               <th>
 5406:                 &nbsp;'.&mt('Download a scoring office file').'
 5407:               </th>
 5408:        '.&Apache::loncommon::end_data_table_header_row().'
 5409:        '.&Apache::loncommon::start_data_table_row().'
 5410:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5411:                 <br />
 5412:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5413:        '.&Apache::loncommon::end_data_table_row().'
 5414:      '.&Apache::loncommon::end_data_table().'
 5415:    </form>
 5416:    <br />
 5417: ');
 5418: 
 5419:     &Apache::lonpickcode::code_list($r,2);
 5420: 
 5421:     $r->print('<br /><form method="post" name="checkscantron">'.
 5422:              $default_form_data."\n".
 5423:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5424:              &Apache::loncommon::start_data_table_header_row()."\n".
 5425:              '<th colspan="2">
 5426:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5427:              '</th>'."\n".
 5428:               &Apache::loncommon::end_data_table_header_row()."\n".
 5429:               &Apache::loncommon::start_data_table_row()."\n".
 5430:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5431:               '<td> '.$sequence_selector.' </td>'.
 5432:               &Apache::loncommon::end_data_table_row()."\n".
 5433:               &Apache::loncommon::start_data_table_row()."\n".
 5434:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5435:               '<td> '.$file_selector.' </td>'."\n".
 5436:               &Apache::loncommon::end_data_table_row()."\n".
 5437:               &Apache::loncommon::start_data_table_row()."\n".
 5438:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5439:               '<td> '.$format_selector.' </td>'."\n".
 5440:               &Apache::loncommon::end_data_table_row()."\n".
 5441:               &Apache::loncommon::start_data_table_row()."\n".
 5442:               '<td> '.&mt('Options').' </td>'."\n".
 5443:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5444:               &Apache::loncommon::end_data_table_row()."\n".
 5445:               &Apache::loncommon::start_data_table_row()."\n".
 5446:               '<td colspan="2">'."\n".
 5447:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5448:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5449:               '</td>'."\n".
 5450:               &Apache::loncommon::end_data_table_row()."\n".
 5451:               &Apache::loncommon::end_data_table()."\n".
 5452:               '</form><br />');
 5453:     $r->print($grading_menu_button);
 5454:     return;
 5455: }
 5456: 
 5457: =pod
 5458: 
 5459: =item get_scantron_config
 5460: 
 5461:    Parse and return the scantron configuration line selected as a
 5462:    hash of configuration file fields.
 5463: 
 5464:  Arguments:
 5465:     which - the name of the configuration to parse from the file.
 5466: 
 5467: 
 5468:  Returns:
 5469:             If the named configuration is not in the file, an empty
 5470:             hash is returned.
 5471:     a hash with the fields
 5472:       name         - internal name for the this configuration setup
 5473:       description  - text to display to operator that describes this config
 5474:       CODElocation - if 0 or the string 'none'
 5475:                           - no CODE exists for this config
 5476:                      if -1 || the string 'letter'
 5477:                           - a CODE exists for this config and is
 5478:                             a string of letters
 5479:                      Unsupported value (but planned for future support)
 5480:                           if a positive integer
 5481:                                - The CODE exists as the first n items from
 5482:                                  the question section of the form
 5483:                           if the string 'number'
 5484:                                - The CODE exists for this config and is
 5485:                                  a string of numbers
 5486:       CODEstart   - (only matter if a CODE exists) column in the line where
 5487:                      the CODE starts
 5488:       CODElength  - length of the CODE
 5489:       IDstart     - column where the student/employee ID starts
 5490:       IDlength    - length of the student/employee ID info
 5491:       Qstart      - column where the information from the bubbled
 5492:                     'questions' start
 5493:       Qlength     - number of columns comprising a single bubble line from
 5494:                     the sheet. (usually either 1 or 10)
 5495:       Qon         - either a single character representing the character used
 5496:                     to signal a bubble was chosen in the positional setup, or
 5497:                     the string 'letter' if the letter of the chosen bubble is
 5498:                     in the final, or 'number' if a number representing the
 5499:                     chosen bubble is in the file (1->A 0->J)
 5500:       Qoff        - the character used to represent that a bubble was
 5501:                     left blank
 5502:       PaperID     - if the scanning process generates a unique number for each
 5503:                     sheet scanned the column that this ID number starts in
 5504:       PaperIDlength - number of columns that comprise the unique ID number
 5505:                       for the sheet of paper
 5506:       FirstName   - column that the first name starts in
 5507:       FirstNameLength - number of columns that the first name spans
 5508:  
 5509:       LastName    - column that the last name starts in
 5510:       LastNameLength - number of columns that the last name spans
 5511: 
 5512: =cut
 5513: 
 5514: sub get_scantron_config {
 5515:     my ($which) = @_;
 5516:     my @lines = &get_scantronformat_file();
 5517:     my %config;
 5518:     #FIXME probably should move to XML it has already gotten a bit much now
 5519:     foreach my $line (@lines) {
 5520: 	my ($name,$descrip)=split(/:/,$line);
 5521: 	if ($name ne $which ) { next; }
 5522: 	chomp($line);
 5523: 	my @config=split(/:/,$line);
 5524: 	$config{'name'}=$config[0];
 5525: 	$config{'description'}=$config[1];
 5526: 	$config{'CODElocation'}=$config[2];
 5527: 	$config{'CODEstart'}=$config[3];
 5528: 	$config{'CODElength'}=$config[4];
 5529: 	$config{'IDstart'}=$config[5];
 5530: 	$config{'IDlength'}=$config[6];
 5531: 	$config{'Qstart'}=$config[7];
 5532:  	$config{'Qlength'}=$config[8];
 5533: 	$config{'Qoff'}=$config[9];
 5534: 	$config{'Qon'}=$config[10];
 5535: 	$config{'PaperID'}=$config[11];
 5536: 	$config{'PaperIDlength'}=$config[12];
 5537: 	$config{'FirstName'}=$config[13];
 5538: 	$config{'FirstNamelength'}=$config[14];
 5539: 	$config{'LastName'}=$config[15];
 5540: 	$config{'LastNamelength'}=$config[16];
 5541: 	last;
 5542:     }
 5543:     return %config;
 5544: }
 5545: 
 5546: =pod 
 5547: 
 5548: =item username_to_idmap
 5549: 
 5550:     creates a hash keyed by student/employee ID with values of the corresponding
 5551:     student username:domain.
 5552: 
 5553:   Arguments:
 5554: 
 5555:     $classlist - reference to the class list hash. This is a hash
 5556:                  keyed by student name:domain  whose elements are references
 5557:                  to arrays containing various chunks of information
 5558:                  about the student. (See loncoursedata for more info).
 5559: 
 5560:   Returns
 5561:     %idmap - the constructed hash
 5562: 
 5563: =cut
 5564: 
 5565: sub username_to_idmap {
 5566:     my ($classlist)= @_;
 5567:     my %idmap;
 5568:     foreach my $student (keys(%$classlist)) {
 5569: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5570: 	    $student;
 5571:     }
 5572:     return %idmap;
 5573: }
 5574: 
 5575: =pod
 5576: 
 5577: =item scantron_fixup_scanline
 5578: 
 5579:    Process a requested correction to a scanline.
 5580: 
 5581:   Arguments:
 5582:     $scantron_config   - hash from &get_scantron_config()
 5583:     $scan_data         - hash of correction information 
 5584:                           (see &scantron_getfile())
 5585:     $line              - existing scanline
 5586:     $whichline         - line number of the passed in scanline
 5587:     $field             - type of change to process 
 5588:                          (either 
 5589:                           'ID'     -> correct the student/employee ID
 5590:                           'CODE'   -> correct the CODE
 5591:                           'answer' -> fixup the submitted answers)
 5592:     
 5593:    $args               - hash of additional info,
 5594:                           - 'ID' 
 5595:                                'newid' -> studentID to use in replacement
 5596:                                           of existing one
 5597:                           - 'CODE' 
 5598:                                'CODE_ignore_dup' - set to true if duplicates
 5599:                                                    should be ignored.
 5600: 	                       'CODE' - is new code or 'use_unfound'
 5601:                                         if the existing unfound code should
 5602:                                         be used as is
 5603:                           - 'answer'
 5604:                                'response' - new answer or 'none' if blank
 5605:                                'question' - the bubble line to change
 5606:                                'questionnum' - the question identifier,
 5607:                                                may include subquestion. 
 5608: 
 5609:   Returns:
 5610:     $line - the modified scanline
 5611: 
 5612:   Side effects: 
 5613:     $scan_data - may be updated
 5614: 
 5615: =cut
 5616: 
 5617: 
 5618: sub scantron_fixup_scanline {
 5619:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5620:     if ($field eq 'ID') {
 5621: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5622: 	    return ($line,1,'New value too large');
 5623: 	}
 5624: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5625: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5626: 				     $args->{'newid'});
 5627: 	}
 5628: 	substr($line,$$scantron_config{'IDstart'}-1,
 5629: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5630: 	if ($args->{'newid'}=~/^\s*$/) {
 5631: 	    &scan_data($scan_data,"$whichline.user",
 5632: 		       $args->{'username'}.':'.$args->{'domain'});
 5633: 	}
 5634:     } elsif ($field eq 'CODE') {
 5635: 	if ($args->{'CODE_ignore_dup'}) {
 5636: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5637: 	}
 5638: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5639: 	if ($args->{'CODE'} ne 'use_unfound') {
 5640: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5641: 		return ($line,1,'New CODE value too large');
 5642: 	    }
 5643: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5644: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5645: 	    }
 5646: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5647: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5648: 	}
 5649:     } elsif ($field eq 'answer') {
 5650: 	my $length=$scantron_config->{'Qlength'};
 5651: 	my $off=$scantron_config->{'Qoff'};
 5652: 	my $on=$scantron_config->{'Qon'};
 5653: 	my $answer=${off}x$length;
 5654: 	if ($args->{'response'} eq 'none') {
 5655: 	    &scan_data($scan_data,
 5656: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5657: 	} else {
 5658: 	    if ($on eq 'letter') {
 5659: 		my @alphabet=('A'..'Z');
 5660: 		$answer=$alphabet[$args->{'response'}];
 5661: 	    } elsif ($on eq 'number') {
 5662: 		$answer=$args->{'response'}+1;
 5663: 		if ($answer == 10) { $answer = '0'; }
 5664: 	    } else {
 5665: 		substr($answer,$args->{'response'},1)=$on;
 5666: 	    }
 5667: 	    &scan_data($scan_data,
 5668: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5669: 	}
 5670: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5671: 	substr($line,$where-1,$length)=$answer;
 5672:     }
 5673:     return $line;
 5674: }
 5675: 
 5676: =pod
 5677: 
 5678: =item scan_data
 5679: 
 5680:     Edit or look up  an item in the scan_data hash.
 5681: 
 5682:   Arguments:
 5683:     $scan_data  - The hash (see scantron_getfile)
 5684:     $key        - shorthand of the key to edit (actual key is
 5685:                   scantronfilename_key).
 5686:     $data        - New value of the hash entry.
 5687:     $delete      - If true, the entry is removed from the hash.
 5688: 
 5689:   Returns:
 5690:     The new value of the hash table field (undefined if deleted).
 5691: 
 5692: =cut
 5693: 
 5694: 
 5695: sub scan_data {
 5696:     my ($scan_data,$key,$value,$delete)=@_;
 5697:     my $filename=$env{'form.scantron_selectfile'};
 5698:     if (defined($value)) {
 5699: 	$scan_data->{$filename.'_'.$key} = $value;
 5700:     }
 5701:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5702:     return $scan_data->{$filename.'_'.$key};
 5703: }
 5704: 
 5705: # ----- These first few routines are general use routines.----
 5706: 
 5707: # Return the number of occurences of a pattern in a string.
 5708: 
 5709: sub occurence_count {
 5710:     my ($string, $pattern) = @_;
 5711: 
 5712:     my @matches = ($string =~ /$pattern/g);
 5713: 
 5714:     return scalar(@matches);
 5715: }
 5716: 
 5717: 
 5718: # Take a string known to have digits and convert all the
 5719: # digits into letters in the range J,A..I.
 5720: 
 5721: sub digits_to_letters {
 5722:     my ($input) = @_;
 5723: 
 5724:     my @alphabet = ('J', 'A'..'I');
 5725: 
 5726:     my @input    = split(//, $input);
 5727:     my $output ='';
 5728:     for (my $i = 0; $i < scalar(@input); $i++) {
 5729: 	if ($input[$i] =~ /\d/) {
 5730: 	    $output .= $alphabet[$input[$i]];
 5731: 	} else {
 5732: 	    $output .= $input[$i];
 5733: 	}
 5734:     }
 5735:     return $output;
 5736: }
 5737: 
 5738: =pod 
 5739: 
 5740: =item scantron_parse_scanline
 5741: 
 5742:   Decodes a scanline from the selected scantron file
 5743: 
 5744:  Arguments:
 5745:     line             - The text of the scantron file line to process
 5746:     whichline        - Line number
 5747:     scantron_config  - Hash describing the format of the scantron lines.
 5748:     scan_data        - Hash of extra information about the scanline
 5749:                        (see scantron_getfile for more information)
 5750:     just_header      - True if should not process question answers but only
 5751:                        the stuff to the left of the answers.
 5752:  Returns:
 5753:    Hash containing the result of parsing the scanline
 5754: 
 5755:    Keys are all proceeded by the string 'scantron.'
 5756: 
 5757:        CODE    - the CODE in use for this scanline
 5758:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5759:                  by the operator
 5760:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5761:                             CODEs were selected, but the usage has been
 5762:                             forced by the operator
 5763:        ID  - student/employee ID
 5764:        PaperID - if used, the ID number printed on the sheet when the 
 5765:                  paper was scanned
 5766:        FirstName - first name from the sheet
 5767:        LastName  - last name from the sheet
 5768: 
 5769:      if just_header was not true these key may also exist
 5770: 
 5771:        missingerror - a list of bubble ranges that are considered to be answers
 5772:                       to a single question that don't have any bubbles filled in.
 5773:                       Of the form questionnumber:firstbubblenumber:count.
 5774:        doubleerror  - a list of bubble ranges that are considered to be answers
 5775:                       to a single question that have more than one bubble filled in.
 5776:                       Of the form questionnumber::firstbubblenumber:count
 5777:    
 5778:                 In the above, count is the number of bubble responses in the
 5779:                 input line needed to represent the possible answers to the question.
 5780:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5781:                 per line would have count = 2.
 5782: 
 5783:        maxquest     - the number of the last bubble line that was parsed
 5784: 
 5785:        (<number> starts at 1)
 5786:        <number>.answer - zero or more letters representing the selected
 5787:                          letters from the scanline for the bubble line 
 5788:                          <number>.
 5789:                          if blank there was either no bubble or there where
 5790:                          multiple bubbles, (consult the keys missingerror and
 5791:                          doubleerror if this is an error condition)
 5792: 
 5793: =cut
 5794: 
 5795: sub scantron_parse_scanline {
 5796:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5797: 
 5798:     my %record;
 5799:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5800:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5801:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5802:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5803: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5804: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5805: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5806: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5807: 	    $record{'scantron.CODE'}=substr($data,
 5808: 					    $$scantron_config{'CODEstart'}-1,
 5809: 					    $$scantron_config{'CODElength'});
 5810: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5811: 		$record{'scantron.useCODE'}=1;
 5812: 	    }
 5813: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5814: 		$record{'scantron.CODE_ignore_dup'}=1;
 5815: 	    }
 5816: 	} else {
 5817: 	    #FIXME interpret first N questions
 5818: 	}
 5819:     }
 5820:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5821: 				  $$scantron_config{'IDlength'});
 5822:     $record{'scantron.PaperID'}=
 5823: 	substr($data,$$scantron_config{'PaperID'}-1,
 5824: 	       $$scantron_config{'PaperIDlength'});
 5825:     $record{'scantron.FirstName'}=
 5826: 	substr($data,$$scantron_config{'FirstName'}-1,
 5827: 	       $$scantron_config{'FirstNamelength'});
 5828:     $record{'scantron.LastName'}=
 5829: 	substr($data,$$scantron_config{'LastName'}-1,
 5830: 	       $$scantron_config{'LastNamelength'});
 5831:     if ($just_header) { return \%record; }
 5832: 
 5833:     my @alphabet=('A'..'Z');
 5834:     my $questnum=0;
 5835:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5836: 
 5837:     chomp($questions);		# Get rid of any trailing \n.
 5838:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5839:     while (length($questions)) {
 5840: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5841:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5842:                              || 1;
 5843:         $questnum++;
 5844:         my $quest_id = $questnum;
 5845:         my $currentquest = substr($questions,0,$answer_length);
 5846:         $questions       = substr($questions,$answer_length);
 5847:         if (length($currentquest) < $answer_length) { next; }
 5848: 
 5849:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5850:             my $subquestnum = 1;
 5851:             my $subquestions = $currentquest;
 5852:             my @subanswers_needed = 
 5853:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5854:             foreach my $subans (@subanswers_needed) {
 5855:                 my $subans_length =
 5856:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5857:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5858:                 $subquestions   = substr($subquestions,$subans_length);
 5859:                 $quest_id = "$questnum.$subquestnum";
 5860:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5861:                     ($$scantron_config{'Qon'} eq 'number')) {
 5862:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5863:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5864:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5865:                 } else {
 5866:                     $ansnum = &scantron_validator_positional($ansnum,
 5867:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5868:                 }
 5869:                 $subquestnum ++;
 5870:             }
 5871:         } else {
 5872:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5873:                 ($$scantron_config{'Qon'} eq 'number')) {
 5874:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5875:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5876:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5877:             } else {
 5878:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5879:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5880:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5881:             }
 5882:         }
 5883:     }
 5884:     $record{'scantron.maxquest'}=$questnum;
 5885:     return \%record;
 5886: }
 5887: 
 5888: sub scantron_validator_lettnum {
 5889:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5890:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5891: 
 5892:     # Qon 'letter' implies for each slot in currquest we have:
 5893:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5894:     #    about anything else (esp. a value of Qoff) for missing
 5895:     #    bubbles.
 5896:     #
 5897:     # Qon 'number' implies each slot gives a digit that indexes the
 5898:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5899:     #    and * or ? for double bubbles on a single line.
 5900:     #
 5901: 
 5902:     my $matchon;
 5903:     if ($$scantron_config{'Qon'} eq 'letter') {
 5904:         $matchon = '[A-Z]';
 5905:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5906:         $matchon = '\d';
 5907:     }
 5908:     my $occurrences = 0;
 5909:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5910:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5911:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5912:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5913:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5914:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5915:         my @singlelines = split('',$currquest);
 5916:         foreach my $entry (@singlelines) {
 5917:             $occurrences = &occurence_count($entry,$matchon);
 5918:             if ($occurrences > 1) {
 5919:                 last;
 5920:             }
 5921:         } 
 5922:     } else {
 5923:         $occurrences = &occurence_count($currquest,$matchon); 
 5924:     }
 5925:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5926:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5927:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5928:             my $bubble = substr($currquest,$ans,1);
 5929:             if ($bubble =~ /$matchon/ ) {
 5930:                 if ($$scantron_config{'Qon'} eq 'number') {
 5931:                     if ($bubble == 0) {
 5932:                         $bubble = 10; 
 5933:                     }
 5934:                     $record->{"scantron.$ansnum.answer"} = 
 5935:                         $alphabet->[$bubble-1];
 5936:                 } else {
 5937:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5938:                 }
 5939:             } else {
 5940:                 $record->{"scantron.$ansnum.answer"}='';
 5941:             }
 5942:             $ansnum++;
 5943:         }
 5944:     } elsif (!defined($currquest)
 5945:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5946:             || (&occurence_count($currquest,$matchon) == 0)) {
 5947:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5948:             $record->{"scantron.$ansnum.answer"}='';
 5949:             $ansnum++;
 5950:         }
 5951:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5952:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5953:         }
 5954:     } else {
 5955:         if ($$scantron_config{'Qon'} eq 'number') {
 5956:             $currquest = &digits_to_letters($currquest);            
 5957:         }
 5958:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5959:             my $bubble = substr($currquest,$ans,1);
 5960:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5961:             $ansnum++;
 5962:         }
 5963:     }
 5964:     return $ansnum;
 5965: }
 5966: 
 5967: sub scantron_validator_positional {
 5968:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5969:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5970: 
 5971:     # Otherwise there's a positional notation;
 5972:     # each bubble line requires Qlength items, and there are filled in
 5973:     # bubbles for each case where there 'Qon' characters.
 5974:     #
 5975: 
 5976:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5977: 
 5978:     # If the split only gives us one element.. the full length of the
 5979:     # answer string, no bubbles are filled in:
 5980: 
 5981:     if ($answers_needed eq '') {
 5982:         return;
 5983:     }
 5984: 
 5985:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5986:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5987:             $record->{"scantron.$ansnum.answer"}='';
 5988:             $ansnum++;
 5989:         }
 5990:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5991:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5992:         }
 5993:     } elsif (scalar(@array) == 2) {
 5994:         my $location = length($array[0]);
 5995:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5996:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5997:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5998:             if ($ans eq $line_num) {
 5999:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6000:             } else {
 6001:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6002:             }
 6003:             $ansnum++;
 6004:          }
 6005:     } else {
 6006:         #  If there's more than one instance of a bubble character
 6007:         #  That's a double bubble; with positional notation we can
 6008:         #  record all the bubbles filled in as well as the
 6009:         #  fact this response consists of multiple bubbles.
 6010:         #
 6011:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6012:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6013:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6014:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6015:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6016:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6017:             my $doubleerror = 0;
 6018:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6019:                    (!$doubleerror)) {
 6020:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6021:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6022:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6023:                if (length(@currarray) > 2) {
 6024:                    $doubleerror = 1;
 6025:                } 
 6026:             }
 6027:             if ($doubleerror) {
 6028:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6029:             }
 6030:         } else {
 6031:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6032:         }
 6033:         my $item = $ansnum;
 6034:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6035:             $record->{"scantron.$item.answer"} = '';
 6036:             $item ++;
 6037:         }
 6038: 
 6039:         my @ans=@array;
 6040:         my $i=0;
 6041:         my $increment = 0;
 6042:         while ($#ans) {
 6043:             $i+=length($ans[0]) + $increment;
 6044:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6045:             my $bubble = $i%$$scantron_config{'Qlength'};
 6046:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6047:             shift(@ans);
 6048:             $increment = 1;
 6049:         }
 6050:         $ansnum += $answers_needed;
 6051:     }
 6052:     return $ansnum;
 6053: }
 6054: 
 6055: =pod
 6056: 
 6057: =item scantron_add_delay
 6058: 
 6059:    Adds an error message that occurred during the grading phase to a
 6060:    queue of messages to be shown after grading pass is complete
 6061: 
 6062:  Arguments:
 6063:    $delayqueue  - arrary ref of hash ref of error messages
 6064:    $scanline    - the scanline that caused the error
 6065:    $errormesage - the error message
 6066:    $errorcode   - a numeric code for the error
 6067: 
 6068:  Side Effects:
 6069:    updates the $delayqueue to have a new hash ref of the error
 6070: 
 6071: =cut
 6072: 
 6073: sub scantron_add_delay {
 6074:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6075:     push(@$delayqueue,
 6076: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6077: 	  'ecode' => $errorcode }
 6078: 	 );
 6079: }
 6080: 
 6081: =pod
 6082: 
 6083: =item scantron_find_student
 6084: 
 6085:    Finds the username for the current scanline
 6086: 
 6087:   Arguments:
 6088:    $scantron_record - hash result from scantron_parse_scanline
 6089:    $scan_data       - hash of correction information 
 6090:                       (see &scantron_getfile() form more information)
 6091:    $idmap           - hash from &username_to_idmap()
 6092:    $line            - number of current scanline
 6093:  
 6094:   Returns:
 6095:    Either 'username:domain' or undef if unknown
 6096: 
 6097: =cut
 6098: 
 6099: sub scantron_find_student {
 6100:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6101:     my $scanID=$$scantron_record{'scantron.ID'};
 6102:     if ($scanID =~ /^\s*$/) {
 6103:  	return &scan_data($scan_data,"$line.user");
 6104:     }
 6105:     foreach my $id (keys(%$idmap)) {
 6106:  	if (lc($id) eq lc($scanID)) {
 6107:  	    return $$idmap{$id};
 6108:  	}
 6109:     }
 6110:     return undef;
 6111: }
 6112: 
 6113: =pod
 6114: 
 6115: =item scantron_filter
 6116: 
 6117:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6118:    hidden resources was selected
 6119: 
 6120: =cut
 6121: 
 6122: sub scantron_filter {
 6123:     my ($curres)=@_;
 6124: 
 6125:     if (ref($curres) && $curres->is_problem()) {
 6126: 	# if the user has asked to not have either hidden
 6127: 	# or 'randomout' controlled resources to be graded
 6128: 	# don't include them
 6129: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6130: 	    && $curres->randomout) {
 6131: 	    return 0;
 6132: 	}
 6133: 	return 1;
 6134:     }
 6135:     return 0;
 6136: }
 6137: 
 6138: =pod
 6139: 
 6140: =item scantron_process_corrections
 6141: 
 6142:    Gets correction information out of submitted form data and corrects
 6143:    the scanline
 6144: 
 6145: =cut
 6146: 
 6147: sub scantron_process_corrections {
 6148:     my ($r) = @_;
 6149:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6150:     my ($scanlines,$scan_data)=&scantron_getfile();
 6151:     my $classlist=&Apache::loncoursedata::get_classlist();
 6152:     my $which=$env{'form.scantron_line'};
 6153:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6154:     my ($skip,$err,$errmsg);
 6155:     if ($env{'form.scantron_skip_record'}) {
 6156: 	$skip=1;
 6157:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6158: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6159: 	    $env{'form.scantron_domain'};
 6160: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6161: 	($line,$err,$errmsg)=
 6162: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6163: 				     'ID',{'newid'=>$newid,
 6164: 				    'username'=>$env{'form.scantron_username'},
 6165: 				    'domain'=>$env{'form.scantron_domain'}});
 6166:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6167: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6168: 	my $newCODE;
 6169: 	my %args;
 6170: 	if      ($resolution eq 'use_unfound') {
 6171: 	    $newCODE='use_unfound';
 6172: 	} elsif ($resolution eq 'use_found') {
 6173: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6174: 	} elsif ($resolution eq 'use_typed') {
 6175: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6176: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6177: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6178: 	}
 6179: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6180: 	    $args{'CODE_ignore_dup'}=1;
 6181: 	}
 6182: 	$args{'CODE'}=$newCODE;
 6183: 	($line,$err,$errmsg)=
 6184: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6185: 				     'CODE',\%args);
 6186:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6187: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6188: 	    ($line,$err,$errmsg)=
 6189: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6190: 					 $which,'answer',
 6191: 					 { 'question'=>$question,
 6192: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6193:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6194: 	    if ($err) { last; }
 6195: 	}
 6196:     }
 6197:     if ($err) {
 6198: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6199:     } else {
 6200: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6201: 	&scantron_putfile($scanlines,$scan_data);
 6202:     }
 6203: }
 6204: 
 6205: =pod
 6206: 
 6207: =item reset_skipping_status
 6208: 
 6209:    Forgets the current set of remember skipped scanlines (and thus
 6210:    reverts back to considering all lines in the
 6211:    scantron_skipped_<filename> file)
 6212: 
 6213: =cut
 6214: 
 6215: sub reset_skipping_status {
 6216:     my ($scanlines,$scan_data)=&scantron_getfile();
 6217:     &scan_data($scan_data,'remember_skipping',undef,1);
 6218:     &scantron_putfile(undef,$scan_data);
 6219: }
 6220: 
 6221: =pod
 6222: 
 6223: =item start_skipping
 6224: 
 6225:    Marks a scanline to be skipped. 
 6226: 
 6227: =cut
 6228: 
 6229: sub start_skipping {
 6230:     my ($scan_data,$i)=@_;
 6231:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6232:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6233: 	$remembered{$i}=2;
 6234:     } else {
 6235: 	$remembered{$i}=1;
 6236:     }
 6237:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6238: }
 6239: 
 6240: =pod
 6241: 
 6242: =item should_be_skipped
 6243: 
 6244:    Checks whether a scanline should be skipped.
 6245: 
 6246: =cut
 6247: 
 6248: sub should_be_skipped {
 6249:     my ($scanlines,$scan_data,$i)=@_;
 6250:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6251: 	# not redoing old skips
 6252: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6253: 	return 0;
 6254:     }
 6255:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6256: 
 6257:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6258: 	return 0;
 6259:     }
 6260:     return 1;
 6261: }
 6262: 
 6263: =pod
 6264: 
 6265: =item remember_current_skipped
 6266: 
 6267:    Discovers what scanlines are in the scantron_skipped_<filename>
 6268:    file and remembers them into scan_data for later use.
 6269: 
 6270: =cut
 6271: 
 6272: sub remember_current_skipped {
 6273:     my ($scanlines,$scan_data)=&scantron_getfile();
 6274:     my %to_remember;
 6275:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6276: 	if ($scanlines->{'skipped'}[$i]) {
 6277: 	    $to_remember{$i}=1;
 6278: 	}
 6279:     }
 6280: 
 6281:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6282:     &scantron_putfile(undef,$scan_data);
 6283: }
 6284: 
 6285: =pod
 6286: 
 6287: =item check_for_error
 6288: 
 6289:     Checks if there was an error when attempting to remove a specific
 6290:     scantron_.. bubble sheet data file. Prints out an error if
 6291:     something went wrong.
 6292: 
 6293: =cut
 6294: 
 6295: sub check_for_error {
 6296:     my ($r,$result)=@_;
 6297:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6298: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6299:     }
 6300: }
 6301: 
 6302: =pod
 6303: 
 6304: =item scantron_warning_screen
 6305: 
 6306:    Interstitial screen to make sure the operator has selected the
 6307:    correct options before we start the validation phase.
 6308: 
 6309: =cut
 6310: 
 6311: sub scantron_warning_screen {
 6312:     my ($button_text)=@_;
 6313:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6314:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6315:     my $CODElist;
 6316:     if ($scantron_config{'CODElocation'} &&
 6317: 	$scantron_config{'CODEstart'} &&
 6318: 	$scantron_config{'CODElength'}) {
 6319: 	$CODElist=$env{'form.scantron_CODElist'};
 6320: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6321: 	$CODElist=
 6322: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6323: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6324:     }
 6325:     return ('
 6326: <p>
 6327: <span class="LC_warning">
 6328: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6329: </p>
 6330: <table>
 6331: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6332: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6333: '.$CODElist.'
 6334: </table>
 6335: <br />
 6336: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6337: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6338: 
 6339: <br />
 6340: ');
 6341: }
 6342: 
 6343: =pod
 6344: 
 6345: =item scantron_do_warning
 6346: 
 6347:    Check if the operator has picked something for all required
 6348:    fields. Error out if something is missing.
 6349: 
 6350: =cut
 6351: 
 6352: sub scantron_do_warning {
 6353:     my ($r)=@_;
 6354:     my ($symb)=&get_symb($r);
 6355:     if (!$symb) {return '';}
 6356:     my $default_form_data=&defaultFormData($symb);
 6357:     $r->print(&scantron_form_start().$default_form_data);
 6358:     if ( $env{'form.selectpage'} eq '' ||
 6359: 	 $env{'form.scantron_selectfile'} eq '' ||
 6360: 	 $env{'form.scantron_format'} eq '' ) {
 6361: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6362: 	if ( $env{'form.selectpage'} eq '') {
 6363: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6364: 	} 
 6365: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6366: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6367: 	} 
 6368: 	if ( $env{'form.scantron_format'} eq '') {
 6369: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6370: 	} 
 6371:     } else {
 6372: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6373: 	$r->print('
 6374: '.$warning.'
 6375: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6376: <input type="hidden" name="command" value="scantron_validate" />
 6377: ');
 6378:     }
 6379:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6380:     return '';
 6381: }
 6382: 
 6383: =pod
 6384: 
 6385: =item scantron_form_start
 6386: 
 6387:     html hidden input for remembering all selected grading options
 6388: 
 6389: =cut
 6390: 
 6391: sub scantron_form_start {
 6392:     my ($max_bubble)=@_;
 6393:     my $result= <<SCANTRONFORM;
 6394: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6395:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6396:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6397:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6398:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6399:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6400:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6401:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6402:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6403:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6404: SCANTRONFORM
 6405: 
 6406:   my $line = 0;
 6407:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6408:        my $chunk =
 6409: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6410:        $chunk .=
 6411: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6412:        $chunk .= 
 6413:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6414:        $chunk .=
 6415:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6416:        $result .= $chunk;
 6417:        $line++;
 6418:    }
 6419:     return $result;
 6420: }
 6421: 
 6422: =pod
 6423: 
 6424: =item scantron_validate_file
 6425: 
 6426:     Dispatch routine for doing validation of a bubble sheet data file.
 6427: 
 6428:     Also processes any necessary information resets that need to
 6429:     occur before validation begins (ignore previous corrections,
 6430:     restarting the skipped records processing)
 6431: 
 6432: =cut
 6433: 
 6434: sub scantron_validate_file {
 6435:     my ($r) = @_;
 6436:     my ($symb)=&get_symb($r);
 6437:     if (!$symb) {return '';}
 6438:     my $default_form_data=&defaultFormData($symb);
 6439:     
 6440:     # do the detection of only doing skipped records first befroe we delete
 6441:     # them when doing the corrections reset
 6442:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6443: 	&reset_skipping_status();
 6444:     }
 6445:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6446: 	&remember_current_skipped();
 6447: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6448:     }
 6449: 
 6450:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6451: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6452: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6453: 	&check_for_error($r,&scantron_remove_scan_data());
 6454: 	$env{'form.scantron_options_ignore'}='done';
 6455:     }
 6456: 
 6457:     if ($env{'form.scantron_corrections'}) {
 6458: 	&scantron_process_corrections($r);
 6459:     }
 6460:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6461:     #get the student pick code ready
 6462:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6463:     my $nav_error;
 6464:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6465:     if ($nav_error) {
 6466:         $r->print(&navmap_errormsg());
 6467:         return '';
 6468:     }
 6469:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6470:     $r->print($result);
 6471:     
 6472:     my @validate_phases=( 'sequence',
 6473: 			  'ID',
 6474: 			  'CODE',
 6475: 			  'doublebubble',
 6476: 			  'missingbubbles');
 6477:     if (!$env{'form.validatepass'}) {
 6478: 	$env{'form.validatepass'} = 0;
 6479:     }
 6480:     my $currentphase=$env{'form.validatepass'};
 6481: 
 6482: 
 6483:     my $stop=0;
 6484:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6485: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6486: 	$r->rflush();
 6487: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6488: 	{
 6489: 	    no strict 'refs';
 6490: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6491: 	}
 6492:     }
 6493:     if (!$stop) {
 6494: 	my $warning=&scantron_warning_screen('Start Grading');
 6495: 	$r->print(&mt('Validation process complete.').'<br />'.
 6496:                   $warning.
 6497:                   &mt('Perform verification for each student after storage of submissions?').
 6498:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6499:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6500:                   ('&nbsp;'x3).'<label>'.
 6501:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6502:                   '</label></span><br />'.
 6503:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6504:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6505:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6506:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6507:     } else {
 6508: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6509: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6510:     }
 6511:     if ($stop) {
 6512: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6513: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6514: 	    $r->print(' '.&mt('this error').' <br />');
 6515: 
 6516: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6517: 	} else {
 6518:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6519: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6520:             } else {
 6521:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6522:             }
 6523: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6524: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6525: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6526: 	}
 6527:     }
 6528:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6529:     return '';
 6530: }
 6531: 
 6532: 
 6533: =pod
 6534: 
 6535: =item scantron_remove_file
 6536: 
 6537:    Removes the requested bubble sheet data file, makes sure that
 6538:    scantron_original_<filename> is never removed
 6539: 
 6540: 
 6541: =cut
 6542: 
 6543: sub scantron_remove_file {
 6544:     my ($which)=@_;
 6545:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6546:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6547:     my $file='scantron_';
 6548:     if ($which eq 'corrected' || $which eq 'skipped') {
 6549: 	$file.=$which.'_';
 6550:     } else {
 6551: 	return 'refused';
 6552:     }
 6553:     $file.=$env{'form.scantron_selectfile'};
 6554:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6555: }
 6556: 
 6557: 
 6558: =pod
 6559: 
 6560: =item scantron_remove_scan_data
 6561: 
 6562:    Removes all scan_data correction for the requested bubble sheet
 6563:    data file.  (In the case that both the are doing skipped records we need
 6564:    to remember the old skipped lines for the time being so that element
 6565:    persists for a while.)
 6566: 
 6567: =cut
 6568: 
 6569: sub scantron_remove_scan_data {
 6570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6572:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6573:     my @todelete;
 6574:     my $filename=$env{'form.scantron_selectfile'};
 6575:     foreach my $key (@keys) {
 6576: 	if ($key=~/^\Q$filename\E_/) {
 6577: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6578: 		$key=~/remember_skipping/) {
 6579: 		next;
 6580: 	    }
 6581: 	    push(@todelete,$key);
 6582: 	}
 6583:     }
 6584:     my $result;
 6585:     if (@todelete) {
 6586: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6587: 				       \@todelete,$cdom,$cname);
 6588:     } else {
 6589: 	$result = 'ok';
 6590:     }
 6591:     return $result;
 6592: }
 6593: 
 6594: 
 6595: =pod
 6596: 
 6597: =item scantron_getfile
 6598: 
 6599:     Fetches the requested bubble sheet data file (all 3 versions), and
 6600:     the scan_data hash
 6601:   
 6602:   Arguments:
 6603:     None
 6604: 
 6605:   Returns:
 6606:     2 hash references
 6607: 
 6608:      - first one has 
 6609:          orig      -
 6610:          corrected -
 6611:          skipped   -  each of which points to an array ref of the specified
 6612:                       file broken up into individual lines
 6613:          count     - number of scanlines
 6614:  
 6615:      - second is the scan_data hash possible keys are
 6616:        ($number refers to scanline numbered $number and thus the key affects
 6617:         only that scanline
 6618:         $bubline refers to the specific bubble line element and the aspects
 6619:         refers to that specific bubble line element)
 6620: 
 6621:        $number.user - username:domain to use
 6622:        $number.CODE_ignore_dup 
 6623:                     - ignore the duplicate CODE error 
 6624:        $number.useCODE
 6625:                     - use the CODE in the scanline as is
 6626:        $number.no_bubble.$bubline
 6627:                     - it is valid that there is no bubbled in bubble
 6628:                       at $number $bubline
 6629:        remember_skipping
 6630:                     - a frozen hash containing keys of $number and values
 6631:                       of either 
 6632:                         1 - we are on a 'do skipped records pass' and plan
 6633:                             on processing this line
 6634:                         2 - we are on a 'do skipped records pass' and this
 6635:                             scanline has been marked to skip yet again
 6636: 
 6637: =cut
 6638: 
 6639: sub scantron_getfile {
 6640:     #FIXME really would prefer a scantron directory
 6641:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6642:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6643:     my $lines;
 6644:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6645: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6646:     my %scanlines;
 6647:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6648:     my $temp=$scanlines{'orig'};
 6649:     $scanlines{'count'}=$#$temp;
 6650: 
 6651:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6652: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6653:     if ($lines eq '-1') {
 6654: 	$scanlines{'corrected'}=[];
 6655:     } else {
 6656: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6657:     }
 6658:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6659: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6660:     if ($lines eq '-1') {
 6661: 	$scanlines{'skipped'}=[];
 6662:     } else {
 6663: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6664:     }
 6665:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6666:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6667:     my %scan_data = @tmp;
 6668:     return (\%scanlines,\%scan_data);
 6669: }
 6670: 
 6671: =pod
 6672: 
 6673: =item lonnet_putfile
 6674: 
 6675:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6676: 
 6677:  Arguments:
 6678:    $contents - data to store
 6679:    $filename - filename to store $contents into
 6680: 
 6681:  Returns:
 6682:    result value from &Apache::lonnet::finishuserfileupload
 6683: 
 6684: =cut
 6685: 
 6686: sub lonnet_putfile {
 6687:     my ($contents,$filename)=@_;
 6688:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6689:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6690:     $env{'form.sillywaytopassafilearound'}=$contents;
 6691:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6692: 
 6693: }
 6694: 
 6695: =pod
 6696: 
 6697: =item scantron_putfile
 6698: 
 6699:     Stores the current version of the bubble sheet data files, and the
 6700:     scan_data hash. (Does not modify the original version only the
 6701:     corrected and skipped versions.
 6702: 
 6703:  Arguments:
 6704:     $scanlines - hash ref that looks like the first return value from
 6705:                  &scantron_getfile()
 6706:     $scan_data - hash ref that looks like the second return value from
 6707:                  &scantron_getfile()
 6708: 
 6709: =cut
 6710: 
 6711: sub scantron_putfile {
 6712:     my ($scanlines,$scan_data) = @_;
 6713:     #FIXME really would prefer a scantron directory
 6714:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6715:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6716:     if ($scanlines) {
 6717: 	my $prefix='scantron_';
 6718: # no need to update orig, shouldn't change
 6719: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6720: #		    $env{'form.scantron_selectfile'});
 6721: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6722: 			$prefix.'corrected_'.
 6723: 			$env{'form.scantron_selectfile'});
 6724: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6725: 			$prefix.'skipped_'.
 6726: 			$env{'form.scantron_selectfile'});
 6727:     }
 6728:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6729: }
 6730: 
 6731: =pod
 6732: 
 6733: =item scantron_get_line
 6734: 
 6735:    Returns the correct version of the scanline
 6736: 
 6737:  Arguments:
 6738:     $scanlines - hash ref that looks like the first return value from
 6739:                  &scantron_getfile()
 6740:     $scan_data - hash ref that looks like the second return value from
 6741:                  &scantron_getfile()
 6742:     $i         - number of the requested line (starts at 0)
 6743: 
 6744:  Returns:
 6745:    A scanline, (either the original or the corrected one if it
 6746:    exists), or undef if the requested scanline should be
 6747:    skipped. (Either because it's an skipped scanline, or it's an
 6748:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6749:    pass.
 6750: 
 6751: =cut
 6752: 
 6753: sub scantron_get_line {
 6754:     my ($scanlines,$scan_data,$i)=@_;
 6755:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6756:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6757:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6758:     return $scanlines->{'orig'}[$i]; 
 6759: }
 6760: 
 6761: =pod
 6762: 
 6763: =item scantron_todo_count
 6764: 
 6765:     Counts the number of scanlines that need processing.
 6766: 
 6767:  Arguments:
 6768:     $scanlines - hash ref that looks like the first return value from
 6769:                  &scantron_getfile()
 6770:     $scan_data - hash ref that looks like the second return value from
 6771:                  &scantron_getfile()
 6772: 
 6773:  Returns:
 6774:     $count - number of scanlines to process
 6775: 
 6776: =cut
 6777: 
 6778: sub get_todo_count {
 6779:     my ($scanlines,$scan_data)=@_;
 6780:     my $count=0;
 6781:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6782: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6783: 	if ($line=~/^[\s\cz]*$/) { next; }
 6784: 	$count++;
 6785:     }
 6786:     return $count;
 6787: }
 6788: 
 6789: =pod
 6790: 
 6791: =item scantron_put_line
 6792: 
 6793:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6794:     data file.
 6795: 
 6796:  Arguments:
 6797:     $scanlines - hash ref that looks like the first return value from
 6798:                  &scantron_getfile()
 6799:     $scan_data - hash ref that looks like the second return value from
 6800:                  &scantron_getfile()
 6801:     $i         - line number to update
 6802:     $newline   - contents of the updated scanline
 6803:     $skip      - if true make the line for skipping and update the
 6804:                  'skipped' file
 6805: 
 6806: =cut
 6807: 
 6808: sub scantron_put_line {
 6809:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6810:     if ($skip) {
 6811: 	$scanlines->{'skipped'}[$i]=$newline;
 6812: 	&start_skipping($scan_data,$i);
 6813: 	return;
 6814:     }
 6815:     $scanlines->{'corrected'}[$i]=$newline;
 6816: }
 6817: 
 6818: =pod
 6819: 
 6820: =item scantron_clear_skip
 6821: 
 6822:    Remove a line from the 'skipped' file
 6823: 
 6824:  Arguments:
 6825:     $scanlines - hash ref that looks like the first return value from
 6826:                  &scantron_getfile()
 6827:     $scan_data - hash ref that looks like the second return value from
 6828:                  &scantron_getfile()
 6829:     $i         - line number to update
 6830: 
 6831: =cut
 6832: 
 6833: sub scantron_clear_skip {
 6834:     my ($scanlines,$scan_data,$i)=@_;
 6835:     if (exists($scanlines->{'skipped'}[$i])) {
 6836: 	undef($scanlines->{'skipped'}[$i]);
 6837: 	return 1;
 6838:     }
 6839:     return 0;
 6840: }
 6841: 
 6842: =pod
 6843: 
 6844: =item scantron_filter_not_exam
 6845: 
 6846:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6847:    filter out resources that are not marked as 'exam' mode
 6848: 
 6849: =cut
 6850: 
 6851: sub scantron_filter_not_exam {
 6852:     my ($curres)=@_;
 6853:     
 6854:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6855: 	# if the user has asked to not have either hidden
 6856: 	# or 'randomout' controlled resources to be graded
 6857: 	# don't include them
 6858: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6859: 	    && $curres->randomout) {
 6860: 	    return 0;
 6861: 	}
 6862: 	return 1;
 6863:     }
 6864:     return 0;
 6865: }
 6866: 
 6867: =pod
 6868: 
 6869: =item scantron_validate_sequence
 6870: 
 6871:     Validates the selected sequence, checking for resource that are
 6872:     not set to exam mode.
 6873: 
 6874: =cut
 6875: 
 6876: sub scantron_validate_sequence {
 6877:     my ($r,$currentphase) = @_;
 6878: 
 6879:     my $navmap=Apache::lonnavmaps::navmap->new();
 6880:     unless (ref($navmap)) {
 6881:         $r->print(&navmap_errormsg());
 6882:         return (1,$currentphase);
 6883:     }
 6884:     my (undef,undef,$sequence)=
 6885: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6886: 
 6887:     my $map=$navmap->getResourceByUrl($sequence);
 6888: 
 6889:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6890:                                     value="ignore" />');
 6891:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6892: 	my @resources=
 6893: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6894: 	if (@resources) {
 6895: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6896: 	    return (1,$currentphase);
 6897: 	}
 6898:     }
 6899: 
 6900:     return (0,$currentphase+1);
 6901: }
 6902: 
 6903: 
 6904: 
 6905: sub scantron_validate_ID {
 6906:     my ($r,$currentphase) = @_;
 6907:     
 6908:     #get student info
 6909:     my $classlist=&Apache::loncoursedata::get_classlist();
 6910:     my %idmap=&username_to_idmap($classlist);
 6911: 
 6912:     #get scantron line setup
 6913:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6914:     my ($scanlines,$scan_data)=&scantron_getfile();
 6915: 
 6916:     my $nav_error;
 6917:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6918:     if ($nav_error) {
 6919:         $r->print(&navmap_errormsg());
 6920:         return(1,$currentphase);
 6921:     }
 6922: 
 6923:     my %found=('ids'=>{},'usernames'=>{});
 6924:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6925: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6926: 	if ($line=~/^[\s\cz]*$/) { next; }
 6927: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6928: 						 $scan_data);
 6929: 	my $id=$$scan_record{'scantron.ID'};
 6930: 	my $found;
 6931: 	foreach my $checkid (keys(%idmap)) {
 6932: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6933: 	}
 6934: 	if ($found) {
 6935: 	    my $username=$idmap{$found};
 6936: 	    if ($found{'ids'}{$found}) {
 6937: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6938: 					 $line,'duplicateID',$found);
 6939: 		return(1,$currentphase);
 6940: 	    } elsif ($found{'usernames'}{$username}) {
 6941: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6942: 					 $line,'duplicateID',$username);
 6943: 		return(1,$currentphase);
 6944: 	    }
 6945: 	    #FIXME store away line we previously saw the ID on to use above
 6946: 	    $found{'ids'}{$found}++;
 6947: 	    $found{'usernames'}{$username}++;
 6948: 	} else {
 6949: 	    if ($id =~ /^\s*$/) {
 6950: 		my $username=&scan_data($scan_data,"$i.user");
 6951: 		if (defined($username) && $found{'usernames'}{$username}) {
 6952: 		    &scantron_get_correction($r,$i,$scan_record,
 6953: 					     \%scantron_config,
 6954: 					     $line,'duplicateID',$username);
 6955: 		    return(1,$currentphase);
 6956: 		} elsif (!defined($username)) {
 6957: 		    &scantron_get_correction($r,$i,$scan_record,
 6958: 					     \%scantron_config,
 6959: 					     $line,'incorrectID');
 6960: 		    return(1,$currentphase);
 6961: 		}
 6962: 		$found{'usernames'}{$username}++;
 6963: 	    } else {
 6964: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6965: 					 $line,'incorrectID');
 6966: 		return(1,$currentphase);
 6967: 	    }
 6968: 	}
 6969:     }
 6970: 
 6971:     return (0,$currentphase+1);
 6972: }
 6973: 
 6974: 
 6975: sub scantron_get_correction {
 6976:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6977: #FIXME in the case of a duplicated ID the previous line, probably need
 6978: #to show both the current line and the previous one and allow skipping
 6979: #the previous one or the current one
 6980: 
 6981:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6982: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6983: 			    " for PaperID <tt>[_1]</tt>",
 6984: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6985:     } else {
 6986: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6987: 			    " in scanline [_1] <pre>[_2]</pre>",
 6988: 			    $i,$line)."</p> \n");
 6989:     }
 6990:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6991: 			  "The name on the paper is [_2],[_3]",
 6992: 			  $$scan_record{'scantron.ID'},
 6993: 			  $$scan_record{'scantron.LastName'},
 6994: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6995: 
 6996:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6997:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6998:                            # Array populated for doublebubble or
 6999:     my @lines_to_correct;  # missingbubble errors to build javascript
 7000:                            # to validate radio button checking   
 7001: 
 7002:     if ($error =~ /ID$/) {
 7003: 	if ($error eq 'incorrectID') {
 7004: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 7005: 		      "</p>\n");
 7006: 	} elsif ($error eq 'duplicateID') {
 7007: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7008: 	}
 7009: 	$r->print($message);
 7010: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7011: 	$r->print("\n<ul><li> ");
 7012: 	#FIXME it would be nice if this sent back the user ID and
 7013: 	#could do partial userID matches
 7014: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7015: 				       'scantron_username','scantron_domain'));
 7016: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7017: 	$r->print("\n@".
 7018: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7019: 
 7020: 	$r->print('</li>');
 7021:     } elsif ($error =~ /CODE$/) {
 7022: 	if ($error eq 'incorrectCODE') {
 7023: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7024: 	} elsif ($error eq 'duplicateCODE') {
 7025: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 7026: 	}
 7027: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 7028: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 7029: 	$r->print($message);
 7030: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7031: 	$r->print("\n<br /> ");
 7032: 	my $i=0;
 7033: 	if ($error eq 'incorrectCODE' 
 7034: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7035: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7036: 	    if ($closest > 0) {
 7037: 		foreach my $testcode (@{$closest}) {
 7038: 		    my $checked='';
 7039: 		    if (!$i) { $checked=' checked="checked"'; }
 7040: 		    $r->print("
 7041:    <label>
 7042:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7043:        ".&mt("Use the similar CODE [_1] instead.",
 7044: 	    "<b><tt>".$testcode."</tt></b>")."
 7045:     </label>
 7046:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7047: 		    $r->print("\n<br />");
 7048: 		    $i++;
 7049: 		}
 7050: 	    }
 7051: 	}
 7052: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7053: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7054: 	    $r->print("
 7055:     <label>
 7056:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7057:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 7058: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7059:     </label>");
 7060: 	    $r->print("\n<br />");
 7061: 	}
 7062: 
 7063: 	$r->print(<<ENDSCRIPT);
 7064: <script type="text/javascript">
 7065: function change_radio(field) {
 7066:     var slct=document.scantronupload.scantron_CODE_resolution;
 7067:     var i;
 7068:     for (i=0;i<slct.length;i++) {
 7069:         if (slct[i].value==field) { slct[i].checked=true; }
 7070:     }
 7071: }
 7072: </script>
 7073: ENDSCRIPT
 7074: 	my $href="/adm/pickcode?".
 7075: 	   "form=".&escape("scantronupload").
 7076: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7077: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7078: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7079: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7080: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7081: 	    $r->print("
 7082:     <label>
 7083:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7084:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7085: 	     "<a target='_blank' href='$href'>","</a>")."
 7086:     </label> 
 7087:     ".&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\')" />'));
 7088: 	    $r->print("\n<br />");
 7089: 	}
 7090: 	$r->print("
 7091:     <label>
 7092:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7093:        ".&mt("Use [_1] as the CODE.",
 7094: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7095: 	$r->print("\n<br /><br />");
 7096:     } elsif ($error eq 'doublebubble') {
 7097: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7098: 
 7099: 	# The form field scantron_questions is acutally a list of line numbers.
 7100: 	# represented by this form so:
 7101: 
 7102: 	my $line_list = &questions_to_line_list($arg);
 7103: 
 7104: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7105: 		  $line_list.'" />');
 7106: 	$r->print($message);
 7107: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7108: 	foreach my $question (@{$arg}) {
 7109: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7110:                                                    $scan_record, $error);
 7111:             push(@lines_to_correct,@linenums);
 7112: 	}
 7113:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7114:     } elsif ($error eq 'missingbubble') {
 7115: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7116: 	$r->print($message);
 7117: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7118: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7119: 
 7120: 	# The form field scantron_questions is actually a list of line numbers not
 7121: 	# a list of question numbers. Therefore:
 7122: 	#
 7123: 	
 7124: 	my $line_list = &questions_to_line_list($arg);
 7125: 
 7126: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7127: 		  $line_list.'" />');
 7128: 	foreach my $question (@{$arg}) {
 7129: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7130:                                                    $scan_record, $error);
 7131:             push(@lines_to_correct,@linenums);
 7132: 	}
 7133:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7134:     } else {
 7135: 	$r->print("\n<ul>");
 7136:     }
 7137:     $r->print("\n</li></ul>");
 7138: }
 7139: 
 7140: sub verify_bubbles_checked {
 7141:     my (@ansnums) = @_;
 7142:     my $ansnumstr = join('","',@ansnums);
 7143:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7144:     my $output = (<<ENDSCRIPT);
 7145: <script type="text/javascript">
 7146: function verify_bubble_radio(form) {
 7147:     var ansnumArray = new Array ("$ansnumstr");
 7148:     var need_bubble_count = 0;
 7149:     for (var i=0; i<ansnumArray.length; i++) {
 7150:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7151:             var bubble_picked = 0; 
 7152:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7153:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7154:                     bubble_picked = 1;
 7155:                 }
 7156:             }
 7157:             if (bubble_picked == 0) {
 7158:                 need_bubble_count ++;
 7159:             }
 7160:         }
 7161:     }
 7162:     if (need_bubble_count) {
 7163:         alert("$warning");
 7164:         return;
 7165:     }
 7166:     form.submit(); 
 7167: }
 7168: </script>
 7169: ENDSCRIPT
 7170:     return $output;
 7171: }
 7172: 
 7173: =pod
 7174: 
 7175: =item  questions_to_line_list
 7176: 
 7177: Converts a list of questions into a string of comma separated
 7178: line numbers in the answer sheet used by the questions.  This is
 7179: used to fill in the scantron_questions form field.
 7180: 
 7181:   Arguments:
 7182:      questions    - Reference to an array of questions.
 7183: 
 7184: =cut
 7185: 
 7186: 
 7187: sub questions_to_line_list {
 7188:     my ($questions) = @_;
 7189:     my @lines;
 7190: 
 7191:     foreach my $item (@{$questions}) {
 7192:         my $question = $item;
 7193:         my ($first,$count,$last);
 7194:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7195:             $question = $1;
 7196:             my $subquestion = $2;
 7197:             $first = $first_bubble_line{$question-1} + 1;
 7198:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7199:             my $subcount = 1;
 7200:             while ($subcount<$subquestion) {
 7201:                 $first += $subans[$subcount-1];
 7202:                 $subcount ++;
 7203:             }
 7204:             $count = $subans[$subquestion-1];
 7205:         } else {
 7206: 	    $first   = $first_bubble_line{$question-1} + 1;
 7207: 	    $count   = $bubble_lines_per_response{$question-1};
 7208:         }
 7209:         $last = $first+$count-1;
 7210:         push(@lines, ($first..$last));
 7211:     }
 7212:     return join(',', @lines);
 7213: }
 7214: 
 7215: =pod 
 7216: 
 7217: =item prompt_for_corrections
 7218: 
 7219: Prompts for a potentially multiline correction to the
 7220: user's bubbling (factors out common code from scantron_get_correction
 7221: for multi and missing bubble cases).
 7222: 
 7223:  Arguments:
 7224:    $r           - Apache request object.
 7225:    $question    - The question number to prompt for.
 7226:    $scan_config - The scantron file configuration hash.
 7227:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7228:    $error       - Type of error
 7229: 
 7230:  Implicit inputs:
 7231:    %bubble_lines_per_response   - Starting line numbers for each question.
 7232:                                   Numbered from 0 (but question numbers are from
 7233:                                   1.
 7234:    %first_bubble_line           - Starting bubble line for each question.
 7235:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7236:                                   type problems render as separate sub-questions, 
 7237:                                   in exam mode. This hash contains a 
 7238:                                   comma-separated list of the lines per 
 7239:                                   sub-question.
 7240:    %responsetype_per_response   - essayresponse, formularesponse,
 7241:                                   stringresponse, imageresponse, reactionresponse,
 7242:                                   and organicresponse type problem parts can have
 7243:                                   multiple lines per response if the weight
 7244:                                   assigned exceeds 10.  In this case, only
 7245:                                   one bubble per line is permitted, but more 
 7246:                                   than one line might contain bubbles, e.g.
 7247:                                   bubbling of: line 1 - J, line 2 - J, 
 7248:                                   line 3 - B would assign 22 points.  
 7249: 
 7250: =cut
 7251: 
 7252: sub prompt_for_corrections {
 7253:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7254:     my ($current_line,$lines);
 7255:     my @linenums;
 7256:     my $questionnum = $question;
 7257:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7258:         $question = $1;
 7259:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7260:         my $subquestion = $2;
 7261:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7262:         my $subcount = 1;
 7263:         while ($subcount<$subquestion) {
 7264:             $current_line += $subans[$subcount-1];
 7265:             $subcount ++;
 7266:         }
 7267:         $lines = $subans[$subquestion-1];
 7268:     } else {
 7269:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7270:         $lines        = $bubble_lines_per_response{$question-1};
 7271:     }
 7272:     if ($lines > 1) {
 7273:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7274:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7275:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7276:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7277:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7278:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7279:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7280:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7281:         } else {
 7282:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7283:         }
 7284:     }
 7285:     for (my $i =0; $i < $lines; $i++) {
 7286:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7287: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7288: 	        		  $questionnum,$error,split('', $selected));
 7289:         push(@linenums,$current_line);
 7290: 	$current_line++;
 7291:     }
 7292:     if ($lines > 1) {
 7293: 	$r->print("<hr /><br />");
 7294:     }
 7295:     return @linenums;
 7296: }
 7297: 
 7298: =pod
 7299: 
 7300: =item scantron_bubble_selector
 7301:   
 7302:    Generates the html radiobuttons to correct a single bubble line
 7303:    possibly showing the existing the selected bubbles if known
 7304: 
 7305:  Arguments:
 7306:     $r           - Apache request object
 7307:     $scan_config - hash from &get_scantron_config()
 7308:     $line        - Number of the line being displayed.
 7309:     $questionnum - Question number (may include subquestion)
 7310:     $error       - Type of error.
 7311:     @selected    - Array of bubbles picked on this line.
 7312: 
 7313: =cut
 7314: 
 7315: sub scantron_bubble_selector {
 7316:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7317:     my $max=$$scan_config{'Qlength'};
 7318: 
 7319:     my $scmode=$$scan_config{'Qon'};
 7320:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7321: 
 7322:     my @alphabet=('A'..'Z');
 7323:     $r->print(&Apache::loncommon::start_data_table().
 7324:               &Apache::loncommon::start_data_table_row());
 7325:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7326:     for (my $i=0;$i<$max+1;$i++) {
 7327: 	$r->print("\n".'<td align="center">');
 7328: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7329: 	else { $r->print('&nbsp;'); }
 7330: 	$r->print('</td>');
 7331:     }
 7332:     $r->print(&Apache::loncommon::end_data_table_row().
 7333:               &Apache::loncommon::start_data_table_row());
 7334:     for (my $i=0;$i<$max;$i++) {
 7335: 	$r->print("\n".
 7336: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7337: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7338:     }
 7339:     my $nobub_checked = ' ';
 7340:     if ($error eq 'missingbubble') {
 7341:         $nobub_checked = ' checked = "checked" ';
 7342:     }
 7343:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7344: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7345:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7346:               $line.'" value="'.$questionnum.'" /></td>');
 7347:     $r->print(&Apache::loncommon::end_data_table_row().
 7348:               &Apache::loncommon::end_data_table());
 7349: }
 7350: 
 7351: =pod
 7352: 
 7353: =item num_matches
 7354: 
 7355:    Counts the number of characters that are the same between the two arguments.
 7356: 
 7357:  Arguments:
 7358:    $orig - CODE from the scanline
 7359:    $code - CODE to match against
 7360: 
 7361:  Returns:
 7362:    $count - integer count of the number of same characters between the
 7363:             two arguments
 7364: 
 7365: =cut
 7366: 
 7367: sub num_matches {
 7368:     my ($orig,$code) = @_;
 7369:     my @code=split(//,$code);
 7370:     my @orig=split(//,$orig);
 7371:     my $same=0;
 7372:     for (my $i=0;$i<scalar(@code);$i++) {
 7373: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7374:     }
 7375:     return $same;
 7376: }
 7377: 
 7378: =pod
 7379: 
 7380: =item scantron_get_closely_matching_CODEs
 7381: 
 7382:    Cycles through all CODEs and finds the set that has the greatest
 7383:    number of same characters as the provided CODE
 7384: 
 7385:  Arguments:
 7386:    $allcodes - hash ref returned by &get_codes()
 7387:    $CODE     - CODE from the current scanline
 7388: 
 7389:  Returns:
 7390:    2 element list
 7391:     - first elements is number of how closely matching the best fit is 
 7392:       (5 means best set has 5 matching characters)
 7393:     - second element is an arrary ref containing the set of valid CODEs
 7394:       that best fit the passed in CODE
 7395: 
 7396: =cut
 7397: 
 7398: sub scantron_get_closely_matching_CODEs {
 7399:     my ($allcodes,$CODE)=@_;
 7400:     my @CODEs;
 7401:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7402: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7403:     }
 7404: 
 7405:     return ($#CODEs,$CODEs[-1]);
 7406: }
 7407: 
 7408: =pod
 7409: 
 7410: =item get_codes
 7411: 
 7412:    Builds a hash which has keys of all of the valid CODEs from the selected
 7413:    set of remembered CODEs.
 7414: 
 7415:  Arguments:
 7416:   $old_name - name of the set of remembered CODEs
 7417:   $cdom     - domain of the course
 7418:   $cnum     - internal course name
 7419: 
 7420:  Returns:
 7421:   %allcodes - keys are the valid CODEs, values are all 1
 7422: 
 7423: =cut
 7424: 
 7425: sub get_codes {
 7426:     my ($old_name, $cdom, $cnum) = @_;
 7427:     if (!$old_name) {
 7428: 	$old_name=$env{'form.scantron_CODElist'};
 7429:     }
 7430:     if (!$cdom) {
 7431: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7432:     }
 7433:     if (!$cnum) {
 7434: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7435:     }
 7436:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7437: 				    $cdom,$cnum);
 7438:     my %allcodes;
 7439:     if ($result{"type\0$old_name"} eq 'number') {
 7440: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7441:     } else {
 7442: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7443:     }
 7444:     return %allcodes;
 7445: }
 7446: 
 7447: =pod
 7448: 
 7449: =item scantron_validate_CODE
 7450: 
 7451:    Validates all scanlines in the selected file to not have any
 7452:    invalid or underspecified CODEs and that none of the codes are
 7453:    duplicated if this was requested.
 7454: 
 7455: =cut
 7456: 
 7457: sub scantron_validate_CODE {
 7458:     my ($r,$currentphase) = @_;
 7459:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7460:     if ($scantron_config{'CODElocation'} &&
 7461: 	$scantron_config{'CODEstart'} &&
 7462: 	$scantron_config{'CODElength'}) {
 7463: 	if (!defined($env{'form.scantron_CODElist'})) {
 7464: 	    &FIXME_blow_up()
 7465: 	}
 7466:     } else {
 7467: 	return (0,$currentphase+1);
 7468:     }
 7469:     
 7470:     my %usedCODEs;
 7471: 
 7472:     my %allcodes=&get_codes();
 7473: 
 7474:     my $nav_error;
 7475:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7476:     if ($nav_error) {
 7477:         $r->print(&navmap_errormsg());
 7478:         return(1,$currentphase);
 7479:     }
 7480: 
 7481:     my ($scanlines,$scan_data)=&scantron_getfile();
 7482:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7483: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7484: 	if ($line=~/^[\s\cz]*$/) { next; }
 7485: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7486: 						 $scan_data);
 7487: 	my $CODE=$$scan_record{'scantron.CODE'};
 7488: 	my $error=0;
 7489: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7490: 	    &scantron_get_correction($r,$i,$scan_record,
 7491: 				     \%scantron_config,
 7492: 				     $line,'incorrectCODE',\%allcodes);
 7493: 	    return(1,$currentphase);
 7494: 	}
 7495: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7496: 	    && !$$scan_record{'scantron.useCODE'}) {
 7497: 	    &scantron_get_correction($r,$i,$scan_record,
 7498: 				     \%scantron_config,
 7499: 				     $line,'incorrectCODE',\%allcodes);
 7500: 	    return(1,$currentphase);
 7501: 	}
 7502: 	if (exists($usedCODEs{$CODE}) 
 7503: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7504: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7505: 	    &scantron_get_correction($r,$i,$scan_record,
 7506: 				     \%scantron_config,
 7507: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7508: 	    return(1,$currentphase);
 7509: 	}
 7510: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7511:     }
 7512:     return (0,$currentphase+1);
 7513: }
 7514: 
 7515: =pod
 7516: 
 7517: =item scantron_validate_doublebubble
 7518: 
 7519:    Validates all scanlines in the selected file to not have any
 7520:    bubble lines with multiple bubbles marked.
 7521: 
 7522: =cut
 7523: 
 7524: sub scantron_validate_doublebubble {
 7525:     my ($r,$currentphase) = @_;
 7526:     #get student info
 7527:     my $classlist=&Apache::loncoursedata::get_classlist();
 7528:     my %idmap=&username_to_idmap($classlist);
 7529: 
 7530:     #get scantron line setup
 7531:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7532:     my ($scanlines,$scan_data)=&scantron_getfile();
 7533:     my $nav_error;
 7534:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7535:     if ($nav_error) {
 7536:         $r->print(&navmap_errormsg());
 7537:         return(1,$currentphase);
 7538:     }
 7539: 
 7540:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7541: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7542: 	if ($line=~/^[\s\cz]*$/) { next; }
 7543: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7544: 						 $scan_data);
 7545: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7546: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7547: 				 'doublebubble',
 7548: 				 $$scan_record{'scantron.doubleerror'});
 7549:     	return (1,$currentphase);
 7550:     }
 7551:     return (0,$currentphase+1);
 7552: }
 7553: 
 7554: 
 7555: sub scantron_get_maxbubble {
 7556:     my ($nav_error) = @_;
 7557:     if (defined($env{'form.scantron_maxbubble'}) &&
 7558: 	$env{'form.scantron_maxbubble'}) {
 7559: 	&restore_bubble_lines();
 7560: 	return $env{'form.scantron_maxbubble'};
 7561:     }
 7562: 
 7563:     my (undef, undef, $sequence) =
 7564: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7565: 
 7566:     my $navmap=Apache::lonnavmaps::navmap->new();
 7567:     unless (ref($navmap)) {
 7568:         if (ref($nav_error)) {
 7569:             $$nav_error = 1;
 7570:         }
 7571:         return;
 7572:     }
 7573:     my $map=$navmap->getResourceByUrl($sequence);
 7574:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7575: 
 7576:     &Apache::lonxml::clear_problem_counter();
 7577: 
 7578:     my $uname       = $env{'user.name'};
 7579:     my $udom        = $env{'user.domain'};
 7580:     my $cid         = $env{'request.course.id'};
 7581:     my $total_lines = 0;
 7582:     %bubble_lines_per_response = ();
 7583:     %first_bubble_line         = ();
 7584:     %subdivided_bubble_lines   = ();
 7585:     %responsetype_per_response = ();
 7586: 
 7587:     my $response_number = 0;
 7588:     my $bubble_line     = 0;
 7589:     foreach my $resource (@resources) {
 7590:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7591:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7592: 	    foreach my $part_id (@{$parts}) {
 7593:                 my $lines;
 7594: 
 7595: 	        # TODO - make this a persistent hash not an array.
 7596: 
 7597:                 # optionresponse, matchresponse and rankresponse type items 
 7598:                 # render as separate sub-questions in exam mode.
 7599:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7600:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7601:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7602:                     my ($numbub,$numshown);
 7603:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7604:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7605:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7606:                         }
 7607:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7608:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7609:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7610:                         }
 7611:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7612:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7613:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7614:                         }
 7615:                     }
 7616:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7617:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7618:                     }
 7619:                     my $bubbles_per_line = 10;
 7620:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7621:                     if (($numbub % $bubbles_per_line) != 0) {
 7622:                         $inner_bubble_lines++;
 7623:                     }
 7624:                     for (my $i=0; $i<$numshown; $i++) {
 7625:                         $subdivided_bubble_lines{$response_number} .= 
 7626:                             $inner_bubble_lines.',';
 7627:                     }
 7628:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7629:                     $lines = $numshown * $inner_bubble_lines;
 7630:                 } else {
 7631:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7632:                 } 
 7633: 
 7634:                 $first_bubble_line{$response_number} = $bubble_line;
 7635: 	        $bubble_lines_per_response{$response_number} = $lines;
 7636:                 $responsetype_per_response{$response_number} = 
 7637:                     $analysis->{$part_id.'.type'};
 7638: 	        $response_number++;
 7639: 
 7640: 	        $bubble_line +=  $lines;
 7641: 	        $total_lines +=  $lines;
 7642: 	    }
 7643:         }
 7644:     }
 7645:     &Apache::lonnet::delenv('scantron.');
 7646: 
 7647:     &save_bubble_lines();
 7648:     $env{'form.scantron_maxbubble'} =
 7649: 	$total_lines;
 7650:     return $env{'form.scantron_maxbubble'};
 7651: }
 7652: 
 7653: sub scantron_validate_missingbubbles {
 7654:     my ($r,$currentphase) = @_;
 7655:     #get student info
 7656:     my $classlist=&Apache::loncoursedata::get_classlist();
 7657:     my %idmap=&username_to_idmap($classlist);
 7658: 
 7659:     #get scantron line setup
 7660:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7661:     my ($scanlines,$scan_data)=&scantron_getfile();
 7662:     my $nav_error;
 7663:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7664:     if ($nav_error) {
 7665:         return(1,$currentphase);
 7666:     }
 7667:     if (!$max_bubble) { $max_bubble=2**31; }
 7668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7670: 	if ($line=~/^[\s\cz]*$/) { next; }
 7671: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7672: 						 $scan_data);
 7673: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7674: 	my @to_correct;
 7675: 	
 7676: 	# Probably here's where the error is...
 7677: 
 7678: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7679:             my $lastbubble;
 7680:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7681:                my $question = $1;
 7682:                my $subquestion = $2;
 7683:                if (!defined($first_bubble_line{$question -1})) { next; }
 7684:                my $first = $first_bubble_line{$question-1};
 7685:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7686:                my $subcount = 1;
 7687:                while ($subcount<$subquestion) {
 7688:                    $first += $subans[$subcount-1];
 7689:                    $subcount ++;
 7690:                }
 7691:                my $count = $subans[$subquestion-1];
 7692:                $lastbubble = $first + $count;
 7693:             } else {
 7694:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7695:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7696:             }
 7697:             if ($lastbubble > $max_bubble) { next; }
 7698: 	    push(@to_correct,$missing);
 7699: 	}
 7700: 	if (@to_correct) {
 7701: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7702: 				     $line,'missingbubble',\@to_correct);
 7703: 	    return (1,$currentphase);
 7704: 	}
 7705: 
 7706:     }
 7707:     return (0,$currentphase+1);
 7708: }
 7709: 
 7710: 
 7711: sub scantron_process_students {
 7712:     my ($r) = @_;
 7713: 
 7714:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7715:     my ($symb)=&get_symb($r);
 7716:     if (!$symb) {
 7717: 	return '';
 7718:     }
 7719:     my $default_form_data=&defaultFormData($symb);
 7720: 
 7721:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7722:     my ($scanlines,$scan_data)=&scantron_getfile();
 7723:     my $classlist=&Apache::loncoursedata::get_classlist();
 7724:     my %idmap=&username_to_idmap($classlist);
 7725:     my $navmap=Apache::lonnavmaps::navmap->new();
 7726:     unless (ref($navmap)) {
 7727:         $r->print(&navmap_errormsg());
 7728:         return '';
 7729:     }  
 7730:     my $map=$navmap->getResourceByUrl($sequence);
 7731:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7732:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7733:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7734:                             \%grader_randomlists_by_symb);
 7735:     my $resource_error;
 7736:     foreach my $resource (@resources) {
 7737:         my $ressymb;
 7738:         if (ref($resource)) {
 7739:             $ressymb = $resource->symb();
 7740:         } else {
 7741:             $resource_error = 1;
 7742:             last;
 7743:         }
 7744:         my ($analysis,$parts) =
 7745:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7746:                                       $env{'user.name'},$env{'user.domain'},1);
 7747:         $grader_partids_by_symb{$ressymb} = $parts;
 7748:         if (ref($analysis) eq 'HASH') {
 7749:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7750:                 $grader_randomlists_by_symb{$ressymb} = 
 7751:                     $analysis->{'parts_withrandomlist'};
 7752:             }
 7753:         }
 7754:     }
 7755:     if ($resource_error) {
 7756:         $r->print(&navmap_errormsg());
 7757:         return '';
 7758:     }
 7759: 
 7760:     my ($uname,$udom);
 7761:     my $result= <<SCANTRONFORM;
 7762: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7763:   <input type="hidden" name="command" value="scantron_configphase" />
 7764:   $default_form_data
 7765: SCANTRONFORM
 7766:     $r->print($result);
 7767: 
 7768:     my @delayqueue;
 7769:     my (%completedstudents,%scandata);
 7770:     
 7771:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7772:     my $count=&get_todo_count($scanlines,$scan_data);
 7773:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7774:  				    'Bubblesheet Progress',$count,
 7775: 				    'inline',undef,'scantronupload');
 7776:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7777: 					  'Processing first student');
 7778:     $r->print('<br />');
 7779:     my $start=&Time::HiRes::time();
 7780:     my $i=-1;
 7781:     my $started;
 7782: 
 7783:     my $nav_error;
 7784:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7785:     if ($nav_error) {
 7786:         $r->print(&navmap_errormsg());
 7787:         return '';
 7788:     }
 7789: 
 7790:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7791:     # the user and return.
 7792: 
 7793:     if ($ssi_error) {
 7794: 	$r->print("</form>");
 7795: 	&ssi_print_error($r);
 7796: 	$r->print(&show_grading_menu_form($symb));
 7797:         &Apache::lonnet::remove_lock($lock);
 7798: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7799:     }
 7800: 
 7801:     my %lettdig = &letter_to_digits();
 7802:     my $numletts = scalar(keys(%lettdig));
 7803: 
 7804:     while ($i<$scanlines->{'count'}) {
 7805:  	($uname,$udom)=('','');
 7806:  	$i++;
 7807:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7808:  	if ($line=~/^[\s\cz]*$/) { next; }
 7809: 	if ($started) {
 7810: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7811: 						     'last student');
 7812: 	}
 7813: 	$started=1;
 7814:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7815:  						 $scan_data);
 7816:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7817:  					      \%idmap,$i)) {
 7818:   	    &scantron_add_delay(\@delayqueue,$line,
 7819:  				'Unable to find a student that matches',1);
 7820:  	    next;
 7821:   	}
 7822:  	if (exists $completedstudents{$uname}) {
 7823:  	    &scantron_add_delay(\@delayqueue,$line,
 7824:  				'Student '.$uname.' has multiple sheets',2);
 7825:  	    next;
 7826:  	}
 7827:   	($uname,$udom)=split(/:/,$uname);
 7828: 
 7829:         my (%partids_by_symb,$res_error);
 7830:         foreach my $resource (@resources) {
 7831:             my $ressymb;
 7832:             if (ref($resource)) {
 7833:                 $ressymb = $resource->symb();
 7834:             } else {
 7835:                 $res_error = 1;
 7836:                 last;
 7837:             }
 7838:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7839:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7840:                 my ($analysis,$parts) =
 7841:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7842:                 $partids_by_symb{$ressymb} = $parts;
 7843:             } else {
 7844:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7845:             }
 7846:         }
 7847: 
 7848:         if ($res_error) {
 7849:             &scantron_add_delay(\@delayqueue,$line,
 7850:                                 'An error occurred while grading student '.$uname,2);
 7851:             next;
 7852:         }
 7853: 
 7854: 	&Apache::lonxml::clear_problem_counter();
 7855:   	&Apache::lonnet::appenv($scan_record);
 7856: 
 7857: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7858: 	    &scantron_putfile($scanlines,$scan_data);
 7859: 	}
 7860: 	
 7861:         my $scancode;
 7862:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7863:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7864:             $scancode = $scan_record->{'scantron.CODE'};
 7865:         } else {
 7866:             $scancode = '';
 7867:         }
 7868: 
 7869:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7870:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7871:             $ssi_error = 0; # So end of handler error message does not trigger.
 7872:             $r->print("</form>");
 7873:             &ssi_print_error($r);
 7874:             $r->print(&show_grading_menu_form($symb));
 7875:             &Apache::lonnet::remove_lock($lock);
 7876:             return '';      # Why return ''?  Beats me.
 7877:         }
 7878: 
 7879: 	$completedstudents{$uname}={'line'=>$line};
 7880:         if ($env{'form.verifyrecord'}) {
 7881:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7882:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7883:             chomp($studentdata);
 7884:             $studentdata =~ s/\r$//;
 7885:             my $studentrecord = '';
 7886:             my $counter = -1;
 7887:             foreach my $resource (@resources) {
 7888:                 my $ressymb = $resource->symb();
 7889:                 ($counter,my $recording) =
 7890:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7891:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7892:                                              \%scantron_config,\%lettdig,$numletts);
 7893:                 $studentrecord .= $recording;
 7894:             }
 7895:             if ($studentrecord ne $studentdata) {
 7896:                 &Apache::lonxml::clear_problem_counter();
 7897:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7898:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7899:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7900:                     $r->print("</form>");
 7901:                     &ssi_print_error($r);
 7902:                     $r->print(&show_grading_menu_form($symb));
 7903:                     &Apache::lonnet::remove_lock($lock);
 7904:                     delete($completedstudents{$uname});
 7905:                     return '';
 7906:                 }
 7907:                 $counter = -1;
 7908:                 $studentrecord = '';
 7909:                 foreach my $resource (@resources) {
 7910:                     my $ressymb = $resource->symb();
 7911:                     ($counter,my $recording) =
 7912:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7913:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7914:                                                  \%scantron_config,\%lettdig,$numletts);
 7915:                     $studentrecord .= $recording;
 7916:                 }
 7917:                 if ($studentrecord ne $studentdata) {
 7918:                     $r->print('<p><span class="LC_error">');
 7919:                     if ($scancode eq '') {
 7920:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7921:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7922:                     } else {
 7923:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7924:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7925:                     }
 7926:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7927:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7928:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7929:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7930:                               &Apache::loncommon::start_data_table_row().
 7931:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7932:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7933:                               &Apache::loncommon::end_data_table_row().
 7934:                               &Apache::loncommon::start_data_table_row().
 7935:                               '<td>Stored submissions</td>'.
 7936:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7937:                               &Apache::loncommon::end_data_table_row().
 7938:                               &Apache::loncommon::end_data_table().'</p>');
 7939:                 } else {
 7940:                     $r->print('<br /><span class="LC_warning">'.
 7941:                              &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 />'.
 7942:                              &mt("As a consequence, this user's submission history records two tries.").
 7943:                                  '</span><br />');
 7944:                 }
 7945:             }
 7946:         }
 7947:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7948:     } continue {
 7949: 	&Apache::lonxml::clear_problem_counter();
 7950: 	&Apache::lonnet::delenv('scantron.');
 7951:     }
 7952:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7953:     &Apache::lonnet::remove_lock($lock);
 7954: #    my $lasttime = &Time::HiRes::time()-$start;
 7955: #    $r->print("<p>took $lasttime</p>");
 7956: 
 7957:     $r->print("</form>");
 7958:     $r->print(&show_grading_menu_form($symb));
 7959:     return '';
 7960: }
 7961: 
 7962: sub graders_resources_pass {
 7963:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7964:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7965:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7966:         foreach my $resource (@{$resources}) {
 7967:             my $ressymb = $resource->symb();
 7968:             my ($analysis,$parts) =
 7969:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7970:                                           $env{'user.name'},$env{'user.domain'},1);
 7971:             $grader_partids_by_symb->{$ressymb} = $parts;
 7972:             if (ref($analysis) eq 'HASH') {
 7973:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7974:                     $grader_randomlists_by_symb->{$ressymb} =
 7975:                         $analysis->{'parts_withrandomlist'};
 7976:                 }
 7977:             }
 7978:         }
 7979:     }
 7980:     return;
 7981: }
 7982: 
 7983: sub grade_student_bubbles {
 7984:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7985:     if (ref($resources) eq 'ARRAY') {
 7986:         my $count = 0;
 7987:         foreach my $resource (@{$resources}) {
 7988:             my $ressymb = $resource->symb();
 7989:             my %form = ('submitted'      => 'scantron',
 7990:                         'grade_target'   => 'grade',
 7991:                         'grade_username' => $uname,
 7992:                         'grade_domain'   => $udom,
 7993:                         'grade_courseid' => $env{'request.course.id'},
 7994:                         'grade_symb'     => $ressymb,
 7995:                         'CODE'           => $scancode
 7996:                        );
 7997:             if (ref($parts) eq 'HASH') {
 7998:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7999:                     foreach my $part (@{$parts->{$ressymb}}) {
 8000:                         $form{'scantron_questnum_start.'.$part} =
 8001:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8002:                         $count++;
 8003:                     }
 8004:                 }
 8005:             }
 8006:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8007:             return 'ssi_error' if ($ssi_error);
 8008:             last if (&Apache::loncommon::connection_aborted($r));
 8009:         }
 8010:     }
 8011:     return;
 8012: }
 8013: 
 8014: sub scantron_upload_scantron_data {
 8015:     my ($r)=@_;
 8016:     my $dom = $env{'request.role.domain'};
 8017:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8018:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8019:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8020: 							  'domainid',
 8021: 							  'coursename',$dom);
 8022:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8023:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8024:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8025:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8026:     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.");
 8027:     $r->print('
 8028: <script type="text/javascript" language="javascript">
 8029:     function checkUpload(formname) {
 8030: 	if (formname.upfile.value == "") {
 8031: 	    alert("'.$nofile_alert.'");
 8032: 	    return false;
 8033: 	}
 8034:         if (formname.courseid.value == "") {
 8035:             alert("'.$nocourseid_alert.'");
 8036:             return false;
 8037:         }
 8038: 	formname.submit();
 8039:     }
 8040: 
 8041:     function ToSyllabus() {
 8042:         var cdom = '."'$dom'".';
 8043:         var cnum = document.rules.courseid.value;
 8044:         if (cdom == "" || cdom == null) {
 8045:             return;
 8046:         }
 8047:         if (cnum == "" || cnum == null) {
 8048:            return;
 8049:         }
 8050:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8051:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8052:         return;
 8053:     }
 8054: 
 8055: </script>
 8056: 
 8057: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 8058: 
 8059: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8060: '.$default_form_data.
 8061:   &Apache::lonhtmlcommon::start_pick_box().
 8062:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8063:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8064:   &Apache::lonhtmlcommon::row_closure().
 8065:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8066:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8067:   &Apache::lonhtmlcommon::row_closure().
 8068:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8069:   '<input name="domainid" type="hidden" />'.$domdesc.
 8070:   &Apache::lonhtmlcommon::row_closure().
 8071:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8072:   '<input type="file" name="upfile" size="50" />'.
 8073:   &Apache::lonhtmlcommon::row_closure(1).
 8074:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8075: 
 8076: <input name="command" value="scantronupload_save" type="hidden" />
 8077: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8078: </form>
 8079: ');
 8080:     return '';
 8081: }
 8082: 
 8083: 
 8084: sub scantron_upload_scantron_data_save {
 8085:     my($r)=@_;
 8086:     my ($symb)=&get_symb($r,1);
 8087:     my $doanotherupload=
 8088: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8089: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8090: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8091: 	'</form>'."\n";
 8092:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8093: 	!&Apache::lonnet::allowed('usc',
 8094: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8095: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8096: 	if ($symb) {
 8097: 	    $r->print(&show_grading_menu_form($symb));
 8098: 	} else {
 8099: 	    $r->print($doanotherupload);
 8100: 	}
 8101: 	return '';
 8102:     }
 8103:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8104:     my $uploadedfile;
 8105:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8106:     if (length($env{'form.upfile'}) < 2) {
 8107:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8108:     } else {
 8109:         my $result = 
 8110:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8111:                                             $env{'form.courseid'},$env{'form.domainid'});
 8112: 	if ($result =~ m{^/uploaded/}) {
 8113: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8114:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8115: 			  '<span class="LC_filename">'.$result.'</span>'));
 8116:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8117:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8118:                                                        $env{'form.courseid'},$uploadedfile));
 8119: 	} else {
 8120: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8121:                           '<span class="LC_error">','</span>',$result,
 8122: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8123: 	}
 8124:     }
 8125:     if ($symb) {
 8126: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8127:     } else {
 8128: 	$r->print($doanotherupload);
 8129:     }
 8130:     return '';
 8131: }
 8132: 
 8133: sub validate_uploaded_scantron_file {
 8134:     my ($cdom,$cname,$fname) = @_;
 8135:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8136:     my @lines;
 8137:     if ($scanlines ne '-1') {
 8138:         @lines=split("\n",$scanlines,-1);
 8139:     }
 8140:     my $output;
 8141:     if (@lines) {
 8142:         my (%counts,$max_match_format);
 8143:         my ($max_match_count,$max_match_pct) = (0,0);
 8144:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8145:         my %idmap = &username_to_idmap($classlist);
 8146:         foreach my $key (keys(%idmap)) {
 8147:             my $lckey = lc($key);
 8148:             $idmap{$lckey} = $idmap{$key};
 8149:         }
 8150:         my %unique_formats;
 8151:         my @formatlines = &get_scantronformat_file();
 8152:         foreach my $line (@formatlines) {
 8153:             chomp($line);
 8154:             my @config = split(/:/,$line);
 8155:             my $idstart = $config[5];
 8156:             my $idlength = $config[6];
 8157:             if (($idstart ne '') && ($idlength > 0)) {
 8158:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8159:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8160:                 } else {
 8161:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8162:                 }
 8163:             }
 8164:         }
 8165:         foreach my $key (keys(%unique_formats)) {
 8166:             my ($idstart,$idlength) = split(':',$key);
 8167:             %{$counts{$key}} = (
 8168:                                'found'   => 0,
 8169:                                'total'   => 0,
 8170:                               );
 8171:             foreach my $line (@lines) {
 8172:                 next if ($line =~ /^#/);
 8173:                 next if ($line =~ /^[\s\cz]*$/);
 8174:                 my $id = substr($line,$idstart-1,$idlength);
 8175:                 $id = lc($id);
 8176:                 if (exists($idmap{$id})) {
 8177:                     $counts{$key}{'found'} ++;
 8178:                 }
 8179:                 $counts{$key}{'total'} ++;
 8180:             }
 8181:             if ($counts{$key}{'total'}) {
 8182:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8183:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8184:                     $max_match_pct = $percent_match;
 8185:                     $max_match_format = $key;
 8186:                     $max_match_count = $counts{$key}{'total'};
 8187:                 }
 8188:             }
 8189:         }
 8190:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8191:             my $format_descs;
 8192:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8193:             for (my $i=0; $i<$numwithformat; $i++) {
 8194:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8195:                 if ($i<$numwithformat-2) {
 8196:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8197:                 } elsif ($i==$numwithformat-2) {
 8198:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8199:                 } elsif ($i==$numwithformat-1) {
 8200:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8201:                 }
 8202:             }
 8203:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8204:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
 8205:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8206:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8207:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8208:                                   '<i>'.$cdom.'</i>').'</li>'.
 8209:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8210:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8211:                        '</ul>';
 8212:         }
 8213:     } else {
 8214:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8215:     }
 8216:     return $output;
 8217: }
 8218: 
 8219: sub valid_file {
 8220:     my ($requested_file)=@_;
 8221:     foreach my $filename (sort(&scantron_filenames())) {
 8222: 	if ($requested_file eq $filename) { return 1; }
 8223:     }
 8224:     return 0;
 8225: }
 8226: 
 8227: sub scantron_download_scantron_data {
 8228:     my ($r)=@_;
 8229:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8230:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8231:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8232:     my $file=$env{'form.scantron_selectfile'};
 8233:     if (! &valid_file($file)) {
 8234: 	$r->print('
 8235: 	<p>
 8236: 	    '.&mt('The requested file name was invalid.').'
 8237:         </p>
 8238: ');
 8239: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8240: 	return;
 8241:     }
 8242:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8243:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8244:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8245:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8246:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8247:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8248:     $r->print('
 8249:     <p>
 8250: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8251: 	      '<a href="'.$orig.'">','</a>').'
 8252:     </p>
 8253:     <p>
 8254: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8255: 	      '<a href="'.$corrected.'">','</a>').'
 8256:     </p>
 8257:     <p>
 8258: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8259: 	      '<a href="'.$skipped.'">','</a>').'
 8260:     </p>
 8261: ');
 8262:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8263:     return '';
 8264: }
 8265: 
 8266: sub checkscantron_results {
 8267:     my ($r) = @_;
 8268:     my ($symb)=&get_symb($r);
 8269:     if (!$symb) {return '';}
 8270:     my $grading_menu_button=&show_grading_menu_form($symb);
 8271:     my $cid = $env{'request.course.id'};
 8272:     my %lettdig = &letter_to_digits();
 8273:     my $numletts = scalar(keys(%lettdig));
 8274:     my $cnum = $env{'course.'.$cid.'.num'};
 8275:     my $cdom = $env{'course.'.$cid.'.domain'};
 8276:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8277:     my %record;
 8278:     my %scantron_config =
 8279:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8280:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8281:     my $classlist=&Apache::loncoursedata::get_classlist();
 8282:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8283:     my $navmap=Apache::lonnavmaps::navmap->new();
 8284:     unless (ref($navmap)) {
 8285:         $r->print(&navmap_errormsg());
 8286:         return '';
 8287:     }
 8288:     my $map=$navmap->getResourceByUrl($sequence);
 8289:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8290:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8291:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8292: 
 8293:     my ($uname,$udom);
 8294:     my (%scandata,%lastname,%bylast);
 8295:     $r->print('
 8296: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8297: 
 8298:     my @delayqueue;
 8299:     my %completedstudents;
 8300: 
 8301:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8302:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8303:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8304:                                     'inline',undef,'checkscantron');
 8305:     my ($username,$domain,$started);
 8306:     my $nav_error;
 8307:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8308:     if ($nav_error) {
 8309:         $r->print(&navmap_errormsg());
 8310:         return '';
 8311:     }
 8312: 
 8313:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8314:                                           'Processing first student');
 8315:     my $start=&Time::HiRes::time();
 8316:     my $i=-1;
 8317: 
 8318:     while ($i<$scanlines->{'count'}) {
 8319:         ($username,$domain,$uname)=('','','');
 8320:         $i++;
 8321:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8322:         if ($line=~/^[\s\cz]*$/) { next; }
 8323:         if ($started) {
 8324:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8325:                                                      'last student');
 8326:         }
 8327:         $started=1;
 8328:         my $scan_record=
 8329:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8330:                                                      $scan_data);
 8331:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8332:                                                               \%idmap,$i)) {
 8333:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8334:                                 'Unable to find a student that matches',1);
 8335:             next;
 8336:         }
 8337:         if (exists $completedstudents{$uname}) {
 8338:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8339:                                 'Student '.$uname.' has multiple sheets',2);
 8340:             next;
 8341:         }
 8342:         my $pid = $scan_record->{'scantron.ID'};
 8343:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8344:         push(@{$bylast{$lastname{$pid}}},$pid);
 8345:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8346:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8347:         chomp($scandata{$pid});
 8348:         $scandata{$pid} =~ s/\r$//;
 8349:         ($username,$domain)=split(/:/,$uname);
 8350:         my $counter = -1;
 8351:         foreach my $resource (@resources) {
 8352:             my $parts;
 8353:             my $ressymb = $resource->symb();
 8354:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8355:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8356:                 (my $analysis,$parts) =
 8357:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8358:             } else {
 8359:                 $parts = $grader_partids_by_symb{$ressymb};
 8360:             }
 8361:             ($counter,my $recording) =
 8362:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8363:                                          $scandata{$pid},$parts,
 8364:                                          \%scantron_config,\%lettdig,$numletts);
 8365:             $record{$pid} .= $recording;
 8366:         }
 8367:     }
 8368:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8369:     $r->print('<br />');
 8370:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8371:     $passed = 0;
 8372:     $failed = 0;
 8373:     $numstudents = 0;
 8374:     foreach my $last (sort(keys(%bylast))) {
 8375:         if (ref($bylast{$last}) eq 'ARRAY') {
 8376:             foreach my $pid (sort(@{$bylast{$last}})) {
 8377:                 my $showscandata = $scandata{$pid};
 8378:                 my $showrecord = $record{$pid};
 8379:                 $showscandata =~ s/\s/&nbsp;/g;
 8380:                 $showrecord =~ s/\s/&nbsp;/g;
 8381:                 if ($scandata{$pid} eq $record{$pid}) {
 8382:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8383:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8384: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8385: '</tr>'."\n".
 8386: '<tr class="'.$css_class.'">'."\n".
 8387: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8388:                     $passed ++;
 8389:                 } else {
 8390:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8391:                     $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".
 8392: '</tr>'."\n".
 8393: '<tr class="'.$css_class.'">'."\n".
 8394: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8395: '</tr>'."\n";
 8396:                     $failed ++;
 8397:                 }
 8398:                 $numstudents ++;
 8399:             }
 8400:         }
 8401:     }
 8402:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8403:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8404:     if ($passed) {
 8405:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8406:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8407:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8408:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8409:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8410:                  $okstudents."\n".
 8411:                  &Apache::loncommon::end_data_table().'<br />');
 8412:     }
 8413:     if ($failed) {
 8414:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8415:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8416:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8417:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8418:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8419:                  $badstudents."\n".
 8420:                  &Apache::loncommon::end_data_table()).'<br />'.
 8421:                  &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.');  
 8422:     }
 8423:     $r->print('</form><br />'.$grading_menu_button);
 8424:     return;
 8425: }
 8426: 
 8427: sub verify_scantron_grading {
 8428:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8429:         $scantron_config,$lettdig,$numletts) = @_;
 8430:     my ($record,%expected,%startpos);
 8431:     return ($counter,$record) if (!ref($resource));
 8432:     return ($counter,$record) if (!$resource->is_problem());
 8433:     my $symb = $resource->symb();
 8434:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8435:     foreach my $part_id (@{$partids}) {
 8436:         $counter ++;
 8437:         $expected{$part_id} = 0;
 8438:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8439:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8440:             foreach my $item (@sub_lines) {
 8441:                 $expected{$part_id} += $item;
 8442:             }
 8443:         } else {
 8444:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8445:         }
 8446:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8447:     }
 8448:     if ($symb) {
 8449:         my %recorded;
 8450:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8451:         if ($returnhash{'version'}) {
 8452:             my %lasthash=();
 8453:             my $version;
 8454:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8455:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8456:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8457:                 }
 8458:             }
 8459:             foreach my $key (keys(%lasthash)) {
 8460:                 if ($key =~ /\.scantron$/) {
 8461:                     my $value = &unescape($lasthash{$key});
 8462:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8463:                     if ($value eq '') {
 8464:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8465:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8466:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8467:                             }
 8468:                         }
 8469:                     } else {
 8470:                         my @tocheck;
 8471:                         my @items = split(//,$value);
 8472:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8473:                             ($scantron_config->{'Qon'} eq 'number')) {
 8474:                             if (@items < $expected{$part_id}) {
 8475:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8476:                                 my @singles = split(//,$fragment);
 8477:                                 foreach my $pos (@singles) {
 8478:                                     if ($pos eq ' ') {
 8479:                                         push(@tocheck,$pos);
 8480:                                     } else {
 8481:                                         my $next = shift(@items);
 8482:                                         push(@tocheck,$next);
 8483:                                     }
 8484:                                 }
 8485:                             } else {
 8486:                                 @tocheck = @items;
 8487:                             }
 8488:                             foreach my $letter (@tocheck) {
 8489:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8490:                                     if ($letter !~ /^[A-J]$/) {
 8491:                                         $letter = $scantron_config->{'Qoff'};
 8492:                                     }
 8493:                                     $recorded{$part_id} .= $letter;
 8494:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8495:                                     my $digit;
 8496:                                     if ($letter !~ /^[A-J]$/) {
 8497:                                         $digit = $scantron_config->{'Qoff'};
 8498:                                     } else {
 8499:                                         $digit = $lettdig->{$letter};
 8500:                                     }
 8501:                                     $recorded{$part_id} .= $digit;
 8502:                                 }
 8503:                             }
 8504:                         } else {
 8505:                             @tocheck = @items;
 8506:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8507:                                 my $curr_sub = shift(@tocheck);
 8508:                                 my $digit;
 8509:                                 if ($curr_sub =~ /^[A-J]$/) {
 8510:                                     $digit = $lettdig->{$curr_sub}-1;
 8511:                                 }
 8512:                                 if ($curr_sub eq 'J') {
 8513:                                     $digit += scalar($numletts);
 8514:                                 }
 8515:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8516:                                     if ($j == $digit) {
 8517:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8518:                                     } else {
 8519:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8520:                                     }
 8521:                                 }
 8522:                             }
 8523:                         }
 8524:                     }
 8525:                 }
 8526:             }
 8527:         }
 8528:         foreach my $part_id (@{$partids}) {
 8529:             if ($recorded{$part_id} eq '') {
 8530:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8531:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8532:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8533:                     }
 8534:                 }
 8535:             }
 8536:             $record .= $recorded{$part_id};
 8537:         }
 8538:     }
 8539:     return ($counter,$record);
 8540: }
 8541: 
 8542: sub letter_to_digits { 
 8543:     my %lettdig = (
 8544:                     A => 1,
 8545:                     B => 2,
 8546:                     C => 3,
 8547:                     D => 4,
 8548:                     E => 5,
 8549:                     F => 6,
 8550:                     G => 7,
 8551:                     H => 8,
 8552:                     I => 9,
 8553:                     J => 0,
 8554:                   );
 8555:     return %lettdig;
 8556: }
 8557: 
 8558: 
 8559: #-------- end of section for handling grading scantron forms -------
 8560: #
 8561: #-------------------------------------------------------------------
 8562: 
 8563: #-------------------------- Menu interface -------------------------
 8564: #
 8565: #--- Show a Grading Menu button - Calls the next routine ---
 8566: sub show_grading_menu_form {
 8567:     my ($symb)=@_;
 8568:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8569: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8570: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8571: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8572: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8573: 	'</form>'."\n";
 8574:     return $result;
 8575: }
 8576: 
 8577: # -- Retrieve choices for grading form
 8578: sub savedState {
 8579:     my %savedState = ();
 8580:     if ($env{'form.saveState'}) {
 8581: 	foreach (split(/:/,$env{'form.saveState'})) {
 8582: 	    my ($key,$value) = split(/=/,$_,2);
 8583: 	    $savedState{$key} = $value;
 8584: 	}
 8585:     }
 8586:     return \%savedState;
 8587: }
 8588: 
 8589: sub grading_menu {
 8590:     my ($request) = @_;
 8591:     my ($symb)=&get_symb($request);
 8592:     if (!$symb) {return '';}
 8593:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8594:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8595: 
 8596:     $request->print($table);
 8597:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8598:                   'handgrade'=>$hdgrade,
 8599:                   'probTitle'=>$probTitle,
 8600:                   'command'=>'submit_options',
 8601:                   'saveState'=>"",
 8602:                   'gradingMenu'=>1,
 8603:                   'showgrading'=>"yes");
 8604:     
 8605:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8606:     
 8607:     $fields{'command'} = 'csvform';
 8608:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8609:     
 8610:     $fields{'command'} = 'processclicker';
 8611:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8612:     
 8613:     $fields{'command'} = 'scantron_selectphase';
 8614:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8615:     
 8616:     my @menu = ({	categorytitle=>'Course Grading',
 8617:             items =>[
 8618:                         {	linktext => 'Manual Grading/View Submissions',
 8619:                     		url => $url1,
 8620:                     		permission => 'F',
 8621:                     		icon => 'edit-find-replace.png',
 8622:                     		linktitle => 'Start the process of hand grading submissions.'
 8623:                         },
 8624:                 	    {	linktext => 'Upload Scores',
 8625:                     		url => $url2,
 8626:                     		permission => 'F',
 8627:                     		icon => 'uploadscores.png',
 8628:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8629:                 	    },
 8630:                 	    {	linktext => 'Process Clicker',
 8631:                     		url => $url3,
 8632:                     		permission => 'F',
 8633:                     		icon => 'addClickerInfoFile.png',
 8634:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8635:                 	    },
 8636:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8637:                     		url => $url4,
 8638:                     		permission => 'F',
 8639:                     		icon => 'stat.png',
 8640:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8641:                 	    }
 8642:                     ]
 8643:             });
 8644: 
 8645:     #$fields{'command'} = 'verify';
 8646:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8647:     #
 8648:     # Create the menu
 8649:     my $Str;
 8650:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8651:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8652:     $Str .= '<input type="hidden" name="command" value="" />'.
 8653:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8654: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8655: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8656: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8657: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8658: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8659: 
 8660:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8661:     #$menudata->{'jscript'}
 8662:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8663:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8664:         ' /> '.
 8665:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8666:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8667: 
 8668:     $Str .="</form>\n";
 8669:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8670:     $request->print(<<GRADINGMENUJS);
 8671: <script type="text/javascript" language="javascript">
 8672:     function checkChoice(formname,val,cmdx) {
 8673: 	if (val <= 2) {
 8674: 	    var cmd = radioSelection(formname.radioChoice);
 8675: 	    var cmdsave = cmd;
 8676: 	} else {
 8677: 	    cmd = cmdx;
 8678: 	    cmdsave = 'submission';
 8679: 	}
 8680: 	formname.command.value = cmd;
 8681: 	if (val < 5) formname.submit();
 8682: 	if (val == 5) {
 8683: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8684: 	        return false;
 8685: 	    } else {
 8686: 	        formname.submit();
 8687: 	    }
 8688: 	}
 8689:     }
 8690: 
 8691:     function checkReceiptNo(formname,nospace) {
 8692: 	var receiptNo = formname.receipt.value;
 8693: 	var checkOpt = false;
 8694: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8695: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8696: 	if (checkOpt) {
 8697: 	    alert("$receiptalert");
 8698: 	    formname.receipt.value = "";
 8699: 	    formname.receipt.focus();
 8700: 	    return false;
 8701: 	}
 8702: 	return true;
 8703:     }
 8704: </script>
 8705: GRADINGMENUJS
 8706:     &commonJSfunctions($request);
 8707:     return $Str;    
 8708: }
 8709: 
 8710: 
 8711: #--- Displays the submissions first page -------
 8712: sub submit_options {
 8713:     my ($request) = @_;
 8714:     my ($symb)=&get_symb($request);
 8715:     if (!$symb) {return '';}
 8716:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8717: 
 8718:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8719:     $request->print(<<GRADINGMENUJS);
 8720: <script type="text/javascript" language="javascript">
 8721:     function checkChoice(formname,val,cmdx) {
 8722: 	if (val <= 2) {
 8723: 	    var cmd = radioSelection(formname.radioChoice);
 8724: 	    var cmdsave = cmd;
 8725: 	} else {
 8726: 	    cmd = cmdx;
 8727: 	    cmdsave = 'submission';
 8728: 	}
 8729: 	formname.command.value = cmd;
 8730: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8731: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8732: 	if (val < 5) formname.submit();
 8733: 	if (val == 5) {
 8734: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8735: 	    formname.submit();
 8736: 	}
 8737: 	if (val < 7) formname.submit();
 8738:     }
 8739: 
 8740:     function checkReceiptNo(formname,nospace) {
 8741: 	var receiptNo = formname.receipt.value;
 8742: 	var checkOpt = false;
 8743: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8744: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8745: 	if (checkOpt) {
 8746: 	    alert("$receiptalert");
 8747: 	    formname.receipt.value = "";
 8748: 	    formname.receipt.focus();
 8749: 	    return false;
 8750: 	}
 8751: 	return true;
 8752:     }
 8753: </script>
 8754: GRADINGMENUJS
 8755:     &commonJSfunctions($request);
 8756:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8757:     my $result;
 8758:     my (undef,$sections) = &getclasslist('all','0');
 8759:     my $savedState = &savedState();
 8760:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8761:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8762:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8763:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8764: 
 8765:     # Preselect sections
 8766:     my $selsec="";
 8767:     if (ref($sections)) {
 8768:         foreach my $section (sort(@$sections)) {
 8769:             $selsec.='<option value="'.$section.'" '.
 8770:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8771:         }
 8772:     }
 8773: 
 8774:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8775: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8776: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8777: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8778: 	'<input type="hidden" name="command"     value="" />'."\n".
 8779: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8780: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8781: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8782: 
 8783:     $result.='
 8784: <h2>
 8785:   '.&mt('Grade Current Resource').'
 8786: </h2>
 8787: <div>
 8788:   '.$table.'
 8789: </div>
 8790: 
 8791: <div class="LC_columnSection">
 8792:   
 8793:     <fieldset>
 8794:       <legend>
 8795:        '.&mt('Sections').'
 8796:       </legend>
 8797:       <select name="section" multiple="multiple" size="5">'."\n";
 8798:     $result.= $selsec;
 8799:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8800:     $result.='
 8801:     </fieldset>
 8802:   
 8803:     <fieldset>
 8804:       <legend>
 8805:         '.&mt('Groups').'
 8806:       </legend>
 8807:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8808:     </fieldset>
 8809:   
 8810:     <fieldset>
 8811:       <legend>
 8812:         '.&mt('Access Status').'
 8813:       </legend>
 8814:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8815:     </fieldset>
 8816:   
 8817:     <fieldset>
 8818:       <legend>
 8819:         '.&mt('Submission Status').'
 8820:       </legend>
 8821:       <select name="submitonly" size="5">
 8822: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8823: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8824: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8825: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8826:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8827:       </select>
 8828:     </fieldset>
 8829:   
 8830: </div>
 8831: 
 8832: <br />
 8833:           <div>
 8834:             <div>
 8835:               <label>
 8836:                 <input type="radio" name="radioChoice" value="submission" '.
 8837:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8838:              &mt('Select individual students to grade and view submissions.').'
 8839: 	      </label> 
 8840:             </div>
 8841:             <div>
 8842: 	      <label>
 8843:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8844:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8845:                     &mt('Grade all selected students in a grading table.').'
 8846:               </label>
 8847:             </div>
 8848:             <div>
 8849: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8850:             </div>
 8851:           </div>
 8852: 
 8853: 
 8854:         <h2>
 8855:          '.&mt('Grade Complete Folder for One Student').'
 8856:         </h2>
 8857:         <div>
 8858:             <div>
 8859:               <label>
 8860:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8861: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8862:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8863:               </label>
 8864:             </div>
 8865:             <div>
 8866: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8867:             </div>
 8868:         </div>
 8869:   </form>';
 8870:     $result .= &show_grading_menu_form($symb);
 8871:     return $result;
 8872: }
 8873: 
 8874: sub reset_perm {
 8875:     undef(%perm);
 8876: }
 8877: 
 8878: sub init_perm {
 8879:     &reset_perm();
 8880:     foreach my $test_perm ('vgr','mgr','opa') {
 8881: 
 8882: 	my $scope = $env{'request.course.id'};
 8883: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8884: 
 8885: 	    $scope .= '/'.$env{'request.course.sec'};
 8886: 	    if ( $perm{$test_perm}=
 8887: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8888: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8889: 	    } else {
 8890: 		delete($perm{$test_perm});
 8891: 	    }
 8892: 	}
 8893:     }
 8894: }
 8895: 
 8896: sub gather_clicker_ids {
 8897:     my %clicker_ids;
 8898: 
 8899:     my $classlist = &Apache::loncoursedata::get_classlist();
 8900: 
 8901:     # Set up a couple variables.
 8902:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8903:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8904:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8905: 
 8906:     foreach my $student (keys(%$classlist)) {
 8907:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8908:         my $username = $classlist->{$student}->[$username_idx];
 8909:         my $domain   = $classlist->{$student}->[$domain_idx];
 8910:         my $clickers =
 8911: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8912:         foreach my $id (split(/\,/,$clickers)) {
 8913:             $id=~s/^[\#0]+//;
 8914:             $id=~s/[\-\:]//g;
 8915:             if (exists($clicker_ids{$id})) {
 8916: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8917:             } else {
 8918: 		$clicker_ids{$id}=$username.':'.$domain;
 8919:             }
 8920:         }
 8921:     }
 8922:     return %clicker_ids;
 8923: }
 8924: 
 8925: sub gather_adv_clicker_ids {
 8926:     my %clicker_ids;
 8927:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8928:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8929:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8930:     foreach my $element (sort(keys(%coursepersonnel))) {
 8931:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8932:             my ($puname,$pudom)=split(/\:/,$person);
 8933:             my $clickers =
 8934: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8935:             foreach my $id (split(/\,/,$clickers)) {
 8936: 		$id=~s/^[\#0]+//;
 8937:                 $id=~s/[\-\:]//g;
 8938: 		if (exists($clicker_ids{$id})) {
 8939: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8940: 		} else {
 8941: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8942: 		}
 8943:             }
 8944:         }
 8945:     }
 8946:     return %clicker_ids;
 8947: }
 8948: 
 8949: sub clicker_grading_parameters {
 8950:     return ('gradingmechanism' => 'scalar',
 8951:             'upfiletype' => 'scalar',
 8952:             'specificid' => 'scalar',
 8953:             'pcorrect' => 'scalar',
 8954:             'pincorrect' => 'scalar');
 8955: }
 8956: 
 8957: sub process_clicker {
 8958:     my ($r)=@_;
 8959:     my ($symb)=&get_symb($r);
 8960:     if (!$symb) {return '';}
 8961:     my $result=&checkforfile_js();
 8962:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8963:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8964:     $result.=$table;
 8965:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8966:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8967:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8968:         '</b></td></tr>'."\n";
 8969:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8970: # Attempt to restore parameters from last session, set defaults if not present
 8971:     my %Saveable_Parameters=&clicker_grading_parameters();
 8972:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8973:                                                  \%Saveable_Parameters);
 8974:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8975:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8976:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8977:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8978: 
 8979:     my %checked;
 8980:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8981:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8982:           $checked{$gradingmechanism}=' checked="checked"';
 8983:        }
 8984:     }
 8985: 
 8986:     my $upload=&mt("Upload File");
 8987:     my $type=&mt("Type");
 8988:     my $attendance=&mt("Award points just for participation");
 8989:     my $personnel=&mt("Correctness determined from response by course personnel");
 8990:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8991:     my $given=&mt("Correctness determined from given list of answers").' '.
 8992:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8993:     my $pcorrect=&mt("Percentage points for correct solution");
 8994:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8995:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8996:                                                    {'iclicker' => 'i>clicker',
 8997:                                                     'interwrite' => 'interwrite PRS'});
 8998:     $symb = &Apache::lonenc::check_encrypt($symb);
 8999:     $result.=<<ENDUPFORM;
 9000: <script type="text/javascript">
 9001: function sanitycheck() {
 9002: // Accept only integer percentages
 9003:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9004:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9005: // Find out grading choice
 9006:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9007:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9008:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9009:       }
 9010:    }
 9011: // By default, new choice equals user selection
 9012:    newgradingchoice=gradingchoice;
 9013: // Not good to give more points for false answers than correct ones
 9014:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9015:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9016:    }
 9017: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9018:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9019:       document.forms.gradesupload.pcorrect.value=100;
 9020:       document.forms.gradesupload.pincorrect.value=100;
 9021:    }
 9022: // If the values are different, cannot be attendance only
 9023:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9024:        (gradingchoice=='attendance')) {
 9025:        newgradingchoice='personnel';
 9026:    }
 9027: // Change grading choice to new one
 9028:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9029:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9030:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9031:       } else {
 9032:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9033:       }
 9034:    }
 9035: // Remember the old state
 9036:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9037: }
 9038: </script>
 9039: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9040: <input type="hidden" name="symb" value="$symb" />
 9041: <input type="hidden" name="command" value="processclickerfile" />
 9042: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9043: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9044: <input type="file" name="upfile" size="50" />
 9045: <br /><label>$type: $selectform</label>
 9046: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9047: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9048: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9049: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9050: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9051: <br />&nbsp;&nbsp;&nbsp;
 9052: <input type="text" name="givenanswer" size="50" />
 9053: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9054: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9055: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9056: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9057: </form>
 9058: ENDUPFORM
 9059:     $result.='</td></tr></table>'."\n".
 9060:              '</td></tr></table><br /><br />'."\n";
 9061:     $result.=&show_grading_menu_form($symb);
 9062:     return $result;
 9063: }
 9064: 
 9065: sub process_clicker_file {
 9066:     my ($r)=@_;
 9067:     my ($symb)=&get_symb($r);
 9068:     if (!$symb) {return '';}
 9069: 
 9070:     my %Saveable_Parameters=&clicker_grading_parameters();
 9071:     &Apache::loncommon::store_course_settings('grades_clicker',
 9072:                                               \%Saveable_Parameters);
 9073: 
 9074:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9075:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9076: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9077: 	return $result.&show_grading_menu_form($symb);
 9078:     }
 9079:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9080:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9081:         return $result.&show_grading_menu_form($symb);
 9082:     }
 9083:     my $foundgiven=0;
 9084:     if ($env{'form.gradingmechanism'} eq 'given') {
 9085:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9086:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9087:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 9088:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9089:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9090:         $foundgiven=$#answers+1;
 9091:     }
 9092:     my %clicker_ids=&gather_clicker_ids();
 9093:     my %correct_ids;
 9094:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9095: 	%correct_ids=&gather_adv_clicker_ids();
 9096:     }
 9097:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9098: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9099: 	   $correct_id=~tr/a-z/A-Z/;
 9100: 	   $correct_id=~s/\s//gs;
 9101: 	   $correct_id=~s/^[\#0]+//;
 9102:            $correct_id=~s/[\-\:]//g;
 9103:            if ($correct_id) {
 9104: 	      $correct_ids{$correct_id}='specified';
 9105:            }
 9106:         }
 9107:     }
 9108:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9109: 	$result.=&mt('Score based on attendance only');
 9110:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9111:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9112:     } else {
 9113: 	my $number=0;
 9114: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9115: 	foreach my $id (sort(keys(%correct_ids))) {
 9116: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9117: 	    if ($correct_ids{$id} eq 'specified') {
 9118: 		$result.=&mt('specified');
 9119: 	    } else {
 9120: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9121: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9122: 	    }
 9123: 	    $number++;
 9124: 	}
 9125:         $result.="</p>\n";
 9126: 	if ($number==0) {
 9127: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9128: 	    return $result.&show_grading_menu_form($symb);
 9129: 	}
 9130:     }
 9131:     if (length($env{'form.upfile'}) < 2) {
 9132:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9133: 		     '<span class="LC_error">',
 9134: 		     '</span>',
 9135: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9136:         return $result.&show_grading_menu_form($symb);
 9137:     }
 9138: 
 9139: # Were able to get all the info needed, now analyze the file
 9140: 
 9141:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9142:     $symb = &Apache::lonenc::check_encrypt($symb);
 9143:     my $heading=&mt('Scanning clicker file');
 9144:     $result.=(<<ENDHEADER);
 9145: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9146: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9147: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9148: <form method="post" action="/adm/grades" name="clickeranalysis">
 9149: <input type="hidden" name="symb" value="$symb" />
 9150: <input type="hidden" name="command" value="assignclickergrades" />
 9151: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9152: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9153: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9154: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9155: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9156: ENDHEADER
 9157:     if ($env{'form.gradingmechanism'} eq 'given') {
 9158:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9159:     } 
 9160:     my %responses;
 9161:     my @questiontitles;
 9162:     my $errormsg='';
 9163:     my $number=0;
 9164:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9165: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9166:     }
 9167:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9168:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9169:     }
 9170:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9171:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9172:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9173:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9174:              '<br />';
 9175:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9176:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9177:        return $result.&show_grading_menu_form($symb);
 9178:     } 
 9179: # Remember Question Titles
 9180: # FIXME: Possibly need delimiter other than ":"
 9181:     for (my $i=0;$i<$number;$i++) {
 9182:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9183:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9184:     }
 9185:     my $correct_count=0;
 9186:     my $student_count=0;
 9187:     my $unknown_count=0;
 9188: # Match answers with usernames
 9189: # FIXME: Possibly need delimiter other than ":"
 9190:     foreach my $id (keys(%responses)) {
 9191:        if ($correct_ids{$id}) {
 9192:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9193:           $correct_count++;
 9194:        } elsif ($clicker_ids{$id}) {
 9195:           if ($clicker_ids{$id}=~/\,/) {
 9196: # More than one user with the same clicker!
 9197:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9198:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9199:                            "<select name='multi".$id."'>";
 9200:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9201:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9202:              }
 9203:              $result.='</select>';
 9204:              $unknown_count++;
 9205:           } else {
 9206: # Good: found one and only one user with the right clicker
 9207:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9208:              $student_count++;
 9209:           }
 9210:        } else {
 9211:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9212:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9213:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9214:                    "\n".&mt("Domain").": ".
 9215:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9216:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9217:           $unknown_count++;
 9218:        }
 9219:     }
 9220:     $result.='<hr />'.
 9221:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9222:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9223:        if ($correct_count==0) {
 9224:           $errormsg.="Found no correct answers answers for grading!";
 9225:        } elsif ($correct_count>1) {
 9226:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9227:        }
 9228:     }
 9229:     if ($number<1) {
 9230:        $errormsg.="Found no questions.";
 9231:     }
 9232:     if ($errormsg) {
 9233:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9234:     } else {
 9235:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9236:     }
 9237:     $result.='</form></td></tr></table>'."\n".
 9238:              '</td></tr></table><br /><br />'."\n";
 9239:     return $result.&show_grading_menu_form($symb);
 9240: }
 9241: 
 9242: sub iclicker_eval {
 9243:     my ($questiontitles,$responses)=@_;
 9244:     my $number=0;
 9245:     my $errormsg='';
 9246:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9247:         my %components=&Apache::loncommon::record_sep($line);
 9248:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9249: 	if ($entries[0] eq 'Question') {
 9250: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9251: 		$$questiontitles[$number]=$entries[$i];
 9252: 		$number++;
 9253: 	    }
 9254: 	}
 9255: 	if ($entries[0]=~/^\#/) {
 9256: 	    my $id=$entries[0];
 9257: 	    my @idresponses;
 9258: 	    $id=~s/^[\#0]+//;
 9259: 	    for (my $i=0;$i<$number;$i++) {
 9260: 		my $idx=3+$i*6;
 9261: 		push(@idresponses,$entries[$idx]);
 9262: 	    }
 9263: 	    $$responses{$id}=join(',',@idresponses);
 9264: 	}
 9265:     }
 9266:     return ($errormsg,$number);
 9267: }
 9268: 
 9269: sub interwrite_eval {
 9270:     my ($questiontitles,$responses)=@_;
 9271:     my $number=0;
 9272:     my $errormsg='';
 9273:     my $skipline=1;
 9274:     my $questionnumber=0;
 9275:     my %idresponses=();
 9276:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9277:         my %components=&Apache::loncommon::record_sep($line);
 9278:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9279:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9280:         if ($entries[1] eq 'Response') { $skipline=1; }
 9281:         next if $skipline;
 9282:         if ($entries[0]!=$questionnumber) {
 9283:            $questionnumber=$entries[0];
 9284:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9285:            $number++;
 9286:         }
 9287:         my $id=$entries[4];
 9288:         $id=~s/^[\#0]+//;
 9289:         $id=~s/^v\d*\://i;
 9290:         $id=~s/[\-\:]//g;
 9291:         $idresponses{$id}[$number]=$entries[6];
 9292:     }
 9293:     foreach my $id (keys(%idresponses)) {
 9294:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9295:        $$responses{$id}=~s/^\s*\,//;
 9296:     }
 9297:     return ($errormsg,$number);
 9298: }
 9299: 
 9300: sub assign_clicker_grades {
 9301:     my ($r)=@_;
 9302:     my ($symb)=&get_symb($r);
 9303:     if (!$symb) {return '';}
 9304: # See which part we are saving to
 9305:     my $res_error;
 9306:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9307:     if ($res_error) {
 9308:         return &navmap_errormsg();
 9309:     }
 9310: # FIXME: This should probably look for the first handgradeable part
 9311:     my $part=$$partlist[0];
 9312: # Start screen output
 9313:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9314: 
 9315:     my $heading=&mt('Assigning grades based on clicker file');
 9316:     $result.=(<<ENDHEADER);
 9317: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9318: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9319: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9320: ENDHEADER
 9321: # Get correct result
 9322: # FIXME: Possibly need delimiter other than ":"
 9323:     my @correct=();
 9324:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9325:     my $number=$env{'form.number'};
 9326:     if ($gradingmechanism ne 'attendance') {
 9327:        foreach my $key (keys(%env)) {
 9328:           if ($key=~/^form\.correct\:/) {
 9329:              my @input=split(/\,/,$env{$key});
 9330:              for (my $i=0;$i<=$#input;$i++) {
 9331:                  if (($correct[$i]) && ($input[$i]) &&
 9332:                      ($correct[$i] ne $input[$i])) {
 9333:                     $result.='<br /><span class="LC_warning">'.
 9334:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9335:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9336:                  } elsif ($input[$i]) {
 9337:                     $correct[$i]=$input[$i];
 9338:                  }
 9339:              }
 9340:           }
 9341:        }
 9342:        for (my $i=0;$i<$number;$i++) {
 9343:           if (!$correct[$i]) {
 9344:              $result.='<br /><span class="LC_error">'.
 9345:                       &mt('No correct result given for question "[_1]"!',
 9346:                           $env{'form.question:'.$i}).'</span>';
 9347:           }
 9348:        }
 9349:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9350:     }
 9351: # Start grading
 9352:     my $pcorrect=$env{'form.pcorrect'};
 9353:     my $pincorrect=$env{'form.pincorrect'};
 9354:     my $storecount=0;
 9355:     foreach my $key (keys(%env)) {
 9356:        my $user='';
 9357:        if ($key=~/^form\.student\:(.*)$/) {
 9358:           $user=$1;
 9359:        }
 9360:        if ($key=~/^form\.unknown\:(.*)$/) {
 9361:           my $id=$1;
 9362:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9363:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9364:           } elsif ($env{'form.multi'.$id}) {
 9365:              $user=$env{'form.multi'.$id};
 9366:           }
 9367:        }
 9368:        if ($user) { 
 9369:           my @answer=split(/\,/,$env{$key});
 9370:           my $sum=0;
 9371:           my $realnumber=$number;
 9372:           for (my $i=0;$i<$number;$i++) {
 9373:              if  ($correct[$i] eq '-') {
 9374:                 $realnumber--;
 9375:              } elsif ($answer[$i]) {
 9376:                 if ($gradingmechanism eq 'attendance') {
 9377:                    $sum+=$pcorrect;
 9378:                 } elsif ($correct[$i] eq '*') {
 9379:                    $sum+=$pcorrect;
 9380:                 } else {
 9381:                    if ($answer[$i] eq $correct[$i]) {
 9382:                       $sum+=$pcorrect;
 9383:                    } else {
 9384:                       $sum+=$pincorrect;
 9385:                    }
 9386:                 }
 9387:              }
 9388:           }
 9389:           my $ave=$sum/(100*$realnumber);
 9390: # Store
 9391:           my ($username,$domain)=split(/\:/,$user);
 9392:           my %grades=();
 9393:           $grades{"resource.$part.solved"}='correct_by_override';
 9394:           $grades{"resource.$part.awarded"}=$ave;
 9395:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9396:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9397:                                                  $env{'request.course.id'},
 9398:                                                  $domain,$username);
 9399:           if ($returncode ne 'ok') {
 9400:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9401:           } else {
 9402:              $storecount++;
 9403:           }
 9404:        }
 9405:     }
 9406: # We are done
 9407:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9408:              '</td></tr></table>'."\n".
 9409:              '</td></tr></table><br /><br />'."\n";
 9410:     return $result.&show_grading_menu_form($symb);
 9411: }
 9412: 
 9413: sub navmap_errormsg {
 9414:     return '<div class="LC_error">'.
 9415:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9416:            &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>').
 9417:            '</div>';
 9418: }
 9419: 
 9420: sub handler {
 9421:     my $request=$_[0];
 9422:     &reset_caches();
 9423:     if ($env{'browser.mathml'}) {
 9424: 	&Apache::loncommon::content_type($request,'text/xml');
 9425:     } else {
 9426: 	&Apache::loncommon::content_type($request,'text/html');
 9427:     }
 9428:     $request->send_http_header;
 9429:     return '' if $request->header_only;
 9430:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9431:     my $symb=&get_symb($request,1);
 9432:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9433:     my $command=$commands[0];
 9434: 
 9435:     if ($#commands > 0) {
 9436: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9437:     }
 9438: 
 9439:     $ssi_error = 0;
 9440:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9441:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9442:                                           {'bread_crumbs' => $brcrum}));
 9443:     if ($symb eq '' && $command eq '') {
 9444: 	if ($env{'user.adv'}) {
 9445: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9446: 		($env{'form.codethree'})) {
 9447: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9448: 		    $env{'form.codethree'};
 9449: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9450: 		    &Apache::lonnet::checkin($token);
 9451: 		if ($tsymb) {
 9452: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9453: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9454: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9455: 					  ('grade_username' => $tuname,
 9456: 					   'grade_domain' => $tudom,
 9457: 					   'grade_courseid' => $tcrsid,
 9458: 					   'grade_symb' => $tsymb)));
 9459: 		    } else {
 9460: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9461: 		    }
 9462: 		} else {
 9463: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9464: 		}
 9465: 	    } else {
 9466: 		$request->print(&Apache::lonxml::tokeninputfield());
 9467: 	    }
 9468: 	}
 9469:     } else {
 9470: 	&init_perm();
 9471: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9472: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9473: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9474: 	    &pickStudentPage($request);
 9475: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9476: 	    &displayPage($request);
 9477: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9478: 	    &updateGradeByPage($request);
 9479: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9480: 	    &processGroup($request);
 9481: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9482: 	    $request->print(&grading_menu($request));
 9483: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9484: 	    $request->print(&submit_options($request));
 9485: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9486: 	    $request->print(&viewgrades($request));
 9487: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9488: 	    $request->print(&processHandGrade($request));
 9489: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9490: 	    $request->print(&editgrades($request));
 9491: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9492: 	    $request->print(&verifyreceipt($request));
 9493:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9494:             $request->print(&process_clicker($request));
 9495:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9496:             $request->print(&process_clicker_file($request));
 9497:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9498:             $request->print(&assign_clicker_grades($request));
 9499: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9500: 	    $request->print(&upcsvScores_form($request));
 9501: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9502: 	    $request->print(&csvupload($request));
 9503: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9504: 	    $request->print(&csvuploadmap($request));
 9505: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9506: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9507: 		$request->print(&csvuploadoptions($request));
 9508: 	    } else {
 9509: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9510: 		    $env{'form.upfile_associate'} = 'reverse';
 9511: 		} else {
 9512: 		    $env{'form.upfile_associate'} = 'forward';
 9513: 		}
 9514: 		$request->print(&csvuploadmap($request));
 9515: 	    }
 9516: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9517: 	    $request->print(&csvuploadassign($request));
 9518: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9519: 	    $request->print(&scantron_selectphase($request));
 9520:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9521:  	    $request->print(&scantron_do_warning($request));
 9522: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9523: 	    $request->print(&scantron_validate_file($request));
 9524: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9525: 	    $request->print(&scantron_process_students($request));
 9526:  	} elsif ($command eq 'scantronupload' && 
 9527:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9528: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9529:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9530:  	} elsif ($command eq 'scantronupload_save' &&
 9531:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9532: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9533:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9534:  	} elsif ($command eq 'scantron_download' &&
 9535: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9536:  	    $request->print(&scantron_download_scantron_data($request));
 9537:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9538:             $request->print(&checkscantron_results($request));     
 9539: 	} elsif ($command) {
 9540: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9541: 	}
 9542:     }
 9543:     if ($ssi_error) {
 9544: 	&ssi_print_error($request);
 9545:     }
 9546:     $request->print(&Apache::loncommon::end_page());
 9547:     &reset_caches();
 9548:     return '';
 9549: }
 9550: 
 9551: 1;
 9552: 
 9553: __END__;
 9554: 
 9555: 
 9556: =head1 NAME
 9557: 
 9558: Apache::grades
 9559: 
 9560: =head1 SYNOPSIS
 9561: 
 9562: Handles the viewing of grades.
 9563: 
 9564: This is part of the LearningOnline Network with CAPA project
 9565: described at http://www.lon-capa.org.
 9566: 
 9567: =head1 OVERVIEW
 9568: 
 9569: Do an ssi with retries:
 9570: While I'd love to factor out this with the vesrion in lonprintout,
 9571: 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
 9572: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9573: 
 9574: At least the logic that drives this has been pulled out into loncommon.
 9575: 
 9576: 
 9577: 
 9578: ssi_with_retries - Does the server side include of a resource.
 9579:                      if the ssi call returns an error we'll retry it up to
 9580:                      the number of times requested by the caller.
 9581:                      If we still have a proble, no text is appended to the
 9582:                      output and we set some global variables.
 9583:                      to indicate to the caller an SSI error occurred.  
 9584:                      All of this is supposed to deal with the issues described
 9585:                      in LonCAPA BZ 5631 see:
 9586:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9587:                      by informing the user that this happened.
 9588: 
 9589: Parameters:
 9590:   resource   - The resource to include.  This is passed directly, without
 9591:                interpretation to lonnet::ssi.
 9592:   form       - The form hash parameters that guide the interpretation of the resource
 9593:                
 9594:   retries    - Number of retries allowed before giving up completely.
 9595: Returns:
 9596:   On success, returns the rendered resource identified by the resource parameter.
 9597: Side Effects:
 9598:   The following global variables can be set:
 9599:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9600:                               It is up to the caller to initialize this to false
 9601:                               if desired.
 9602:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9603:                               of the resource that could not be rendered by the ssi
 9604:                               call.
 9605:    ssi_error_message   - The error string fetched from the ssi response
 9606:                               in the event of an error.
 9607: 
 9608: 
 9609: =head1 HANDLER SUBROUTINE
 9610: 
 9611: ssi_with_retries()
 9612: 
 9613: =head1 SUBROUTINES
 9614: 
 9615: =over
 9616: 
 9617: =item scantron_get_correction() : 
 9618: 
 9619:    Builds the interface screen to interact with the operator to fix a
 9620:    specific error condition in a specific scanline
 9621: 
 9622:  Arguments:
 9623:     $r           - Apache request object
 9624:     $i           - number of the current scanline
 9625:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9626:     $scan_config - hash ref as returned from &get_scantron_config()
 9627:     $line        - full contents of the current scanline
 9628:     $error       - error condition, valid values are
 9629:                    'incorrectCODE', 'duplicateCODE',
 9630:                    'doublebubble', 'missingbubble',
 9631:                    'duplicateID', 'incorrectID'
 9632:     $arg         - extra information needed
 9633:        For errors:
 9634:          - duplicateID   - paper number that this studentID was seen before on
 9635:          - duplicateCODE - array ref of the paper numbers this CODE was
 9636:                            seen on before
 9637:          - incorrectCODE - current incorrect CODE 
 9638:          - doublebubble  - array ref of the bubble lines that have double
 9639:                            bubble errors
 9640:          - missingbubble - array ref of the bubble lines that have missing
 9641:                            bubble errors
 9642: 
 9643: =item  scantron_get_maxbubble() : 
 9644: 
 9645:    Arguments:
 9646:        $nav_error  - Reference to scalar which is a flag to indicate a
 9647:                       failure to retrieve a navmap object.
 9648:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9649:        calling routine should trap the error condition and display the warning
 9650:        found in &navmap_errormsg().
 9651: 
 9652:    Returns the maximum number of bubble lines that are expected to
 9653:    occur. Does this by walking the selected sequence rendering the
 9654:    resource and then checking &Apache::lonxml::get_problem_counter()
 9655:    for what the current value of the problem counter is.
 9656: 
 9657:    Caches the results to $env{'form.scantron_maxbubble'},
 9658:    $env{'form.scantron.bubble_lines.n'}, 
 9659:    $env{'form.scantron.first_bubble_line.n'} and
 9660:    $env{"form.scantron.sub_bubblelines.n"}
 9661:    which are the total number of bubble, lines, the number of bubble
 9662:    lines for response n and number of the first bubble line for response n,
 9663:    and a comma separated list of numbers of bubble lines for sub-questions
 9664:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9665: 
 9666: 
 9667: =item  scantron_validate_missingbubbles() : 
 9668: 
 9669:    Validates all scanlines in the selected file to not have any
 9670:     answers that don't have bubbles that have not been verified
 9671:     to be bubble free.
 9672: 
 9673: =item  scantron_process_students() : 
 9674: 
 9675:    Routine that does the actual grading of the bubble sheet information.
 9676: 
 9677:    The parsed scanline hash is added to %env 
 9678: 
 9679:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9680:    foreach resource , with the form data of
 9681: 
 9682: 	'submitted'     =>'scantron' 
 9683: 	'grade_target'  =>'grade',
 9684: 	'grade_username'=> username of student
 9685: 	'grade_domain'  => domain of student
 9686: 	'grade_courseid'=> of course
 9687: 	'grade_symb'    => symb of resource to grade
 9688: 
 9689:     This triggers a grading pass. The problem grading code takes care
 9690:     of converting the bubbled letter information (now in %env) into a
 9691:     valid submission.
 9692: 
 9693: =item  scantron_upload_scantron_data() :
 9694: 
 9695:     Creates the screen for adding a new bubble sheet data file to a course.
 9696: 
 9697: =item  scantron_upload_scantron_data_save() : 
 9698: 
 9699:    Adds a provided bubble information data file to the course if user
 9700:    has the correct privileges to do so. 
 9701: 
 9702: =item  valid_file() :
 9703: 
 9704:    Validates that the requested bubble data file exists in the course.
 9705: 
 9706: =item  scantron_download_scantron_data() : 
 9707: 
 9708:    Shows a list of the three internal files (original, corrected,
 9709:    skipped) for a specific bubble sheet data file that exists in the
 9710:    course.
 9711: 
 9712: =item  scantron_validate_ID() : 
 9713: 
 9714:    Validates all scanlines in the selected file to not have any
 9715:    invalid or underspecified student/employee IDs
 9716: 
 9717: =item navmap_errormsg() :
 9718: 
 9719:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9720:    Should be called whenever the request to instantiate a navmap object fails.  
 9721: 
 9722: =back
 9723: 
 9724: =cut

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