File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.596.2.2: download - view: text, annotated - select for diffs
Mon Dec 20 04:23:43 2010 UTC (13 years, 4 months ago) by raeburn
Branches: version_2_10_X
- Backport 1.640.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.596.2.2 2010/12/20 04:23:43 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:                     if ($lasthash{$key} eq 'randomizetry') {
 2509:                         my $id = join(',',@parts);
 2510:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
 2511:                     } else {
 2512:                         unless ($showsurv) {
 2513:                             my $id = join(',',@parts);
 2514:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
 2515:                         }
 2516:                     }
 2517:                     delete($lasthash{$key});
 2518:                 }
 2519:             }
 2520:         }
 2521:         my @hidden = keys(%typeparts);
 2522:         my @randomize = keys(%randombytry);
 2523: 	foreach my $key (keys(%lasthash)) {
 2524: 	    next if ($key !~ /\.submission$/);
 2525:             my $hide;
 2526:             if (@hidden) {
 2527:                 foreach my $id (@hidden) {
 2528:                     if ($key =~ /^\Q$id\E/) {
 2529:                         $hide = 'anon';
 2530:                         last;
 2531:                     }
 2532:                 }
 2533:             }
 2534:             unless ($hide) {
 2535:                 if (@randomize) {
 2536:                     foreach my $id (@hidden) {
 2537:                         if ($key =~ /^\Q$id\E/) {
 2538:                             $hide = 'rand';
 2539:                             last;
 2540:                         }
 2541:                     }
 2542:                 }
 2543:             }
 2544: 	    my ($partid,$foo) = split(/submission$/,$key);
 2545: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2546: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2547: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
 2548: 	}
 2549:     }
 2550:     if (!@string) {
 2551: 	$string[0] =
 2552: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2553:     }
 2554:     return (\@string,\$timestamp);
 2555: }
 2556: 
 2557: #--- High light keywords, with style choosen by user.
 2558: sub keywords_highlight {
 2559:     my $string    = shift;
 2560:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2561:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2562:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2563:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2564:     foreach my $keyword (@keylist) {
 2565: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2566:     }
 2567:     return $string;
 2568: }
 2569: 
 2570: #--- Called from submission routine
 2571: sub processHandGrade {
 2572:     my ($request) = shift;
 2573:     my $symb   = &get_symb($request);
 2574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2575:     my $button = $env{'form.gradeOpt'};
 2576:     my $ngrade = $env{'form.NCT'};
 2577:     my $ntstu  = $env{'form.NTSTU'};
 2578:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2579:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2580: 
 2581:     if ($button eq 'Save & Next') {
 2582: 	my $ctr = 0;
 2583: 	while ($ctr < $ngrade) {
 2584: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2585: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2586: 	    if ($errorflag eq 'no_score') {
 2587: 		$ctr++;
 2588: 		next;
 2589: 	    }
 2590: 	    if ($errorflag eq 'not_allowed') {
 2591: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2592: 		$ctr++;
 2593: 		next;
 2594: 	    }
 2595: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2596: 	    my ($subject,$message,$msgstatus) = ('','','');
 2597: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2598:             my ($feedurl,$showsymb) =
 2599: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2600: 	    my $messagetail;
 2601: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2602: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2603: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2604: 		$subject.=' ['.$restitle.']';
 2605: 		my (@msgnum) = split(/,/,$includemsg);
 2606: 		foreach (@msgnum) {
 2607: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2608: 		}
 2609: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2610: 		if ($env{'form.withgrades'.$ctr}) {
 2611: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2612: 		    $messagetail = " for <a href=\"".
 2613: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2614: 		}
 2615: 		$msgstatus = 
 2616:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2617: 						     $message.$messagetail,
 2618:                                                      undef,$feedurl,undef,
 2619:                                                      undef,undef,$showsymb,
 2620:                                                      $restitle);
 2621: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2622: 				$msgstatus);
 2623: 	    }
 2624: 	    if ($env{'form.collaborator'.$ctr}) {
 2625: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2626: 		foreach my $collabstr (@collabstrs) {
 2627: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2628: 		    foreach my $collaborator (@collaborators) {
 2629: 			my ($errorflag,$pts,$wgt) = 
 2630: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2631: 					   $env{'form.unamedom'.$ctr},$part);
 2632: 			if ($errorflag eq 'not_allowed') {
 2633: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2634: 			    next;
 2635: 			} elsif ($message ne '') {
 2636: 			    my ($baseurl,$showsymb) = 
 2637: 				&get_feedurl_and_symb($symb,$collaborator,
 2638: 						      $udom);
 2639: 			    if ($env{'form.withgrades'.$ctr}) {
 2640: 				$messagetail = " for <a href=\"".
 2641:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2642: 			    }
 2643: 			    $msgstatus = 
 2644: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2645: 			}
 2646: 		    }
 2647: 		}
 2648: 	    }
 2649: 	    $ctr++;
 2650: 	}
 2651:     }
 2652: 
 2653:     if ($env{'form.handgrade'} eq 'yes') {
 2654: 	# Keywords sorted in alphabatical order
 2655: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2656: 	my %keyhash = ();
 2657: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2658: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2659: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2660: 	$env{'form.keywords'} = join(' ',@keywords);
 2661: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2662: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2663: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2664: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2665: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2666: 
 2667: 	# message center - Order of message gets changed. Blank line is eliminated.
 2668: 	# New messages are saved in env for the next student.
 2669: 	# All messages are saved in nohist_handgrade.db
 2670: 	my ($ctr,$idx) = (1,1);
 2671: 	while ($ctr <= $env{'form.savemsgN'}) {
 2672: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2673: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2674: 		$idx++;
 2675: 	    }
 2676: 	    $ctr++;
 2677: 	}
 2678: 	$ctr = 0;
 2679: 	while ($ctr < $ngrade) {
 2680: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2681: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2682: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2683: 		$idx++;
 2684: 	    }
 2685: 	    $ctr++;
 2686: 	}
 2687: 	$env{'form.savemsgN'} = --$idx;
 2688: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2689: 	my $putresult = &Apache::lonnet::put
 2690: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2691:     }
 2692:     # Called by Save & Refresh from Highlight Attribute Window
 2693:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2694:     if ($env{'form.refresh'} eq 'on') {
 2695: 	my ($ctr,$total) = (0,0);
 2696: 	while ($ctr < $ngrade) {
 2697: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2698: 	    $ctr++;
 2699: 	}
 2700: 	$env{'form.NTSTU'}=$ngrade;
 2701: 	$ctr = 0;
 2702: 	while ($ctr < $total) {
 2703: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2704: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2705: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2706: 	    &submission($request,$ctr,$total-1);
 2707: 	    $ctr++;
 2708: 	}
 2709: 	return '';
 2710:     }
 2711: 
 2712: # Go directly to grade student - from submission or link from chart page
 2713:     if ($button eq 'Grade Student') {
 2714: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2715: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2716: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2717: 	$env{'form.fullname'} = $$fullname{$processUser};
 2718: 	&submission($request,0,0);
 2719: 	return '';
 2720:     }
 2721: 
 2722:     # Get the next/previous one or group of students
 2723:     my $firststu = $env{'form.unamedom0'};
 2724:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2725:     my $ctr = 2;
 2726:     while ($laststu eq '') {
 2727: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2728: 	$ctr++;
 2729: 	$laststu = $firststu if ($ctr > $ngrade);
 2730:     }
 2731: 
 2732:     my (@parsedlist,@nextlist);
 2733:     my ($nextflg) = 0;
 2734:     foreach my $item (sort 
 2735: 	     {
 2736: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2737: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2738: 		 }
 2739: 		 return $a cmp $b;
 2740: 	     } (keys(%$fullname))) {
 2741: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2742: 	    push(@parsedlist,$item);
 2743: 	}
 2744: 	$nextflg = 1 if ($item eq $laststu);
 2745: 	if ($button eq 'Previous') {
 2746: 	    last if ($item eq $firststu);
 2747: 	    push(@parsedlist,$item);
 2748: 	}
 2749:     }
 2750:     $ctr = 0;
 2751:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2752:     my $res_error;
 2753:     my ($partlist) = &response_type($symb,\$res_error);
 2754:     if ($res_error) {
 2755:         $request->print(&navmap_errormsg());
 2756:         return;
 2757:     }
 2758:     foreach my $student (@parsedlist) {
 2759: 	my $submitonly=$env{'form.submitonly'};
 2760: 	my ($uname,$udom) = split(/:/,$student);
 2761: 	
 2762: 	if ($submitonly eq 'queued') {
 2763: 	    my %queue_status = 
 2764: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2765: 							$udom,$uname);
 2766: 	    next if (!defined($queue_status{'gradingqueue'}));
 2767: 	}
 2768: 
 2769: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2770: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2771: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2772: 	    my $submitted = 0;
 2773: 	    my $ungraded = 0;
 2774: 	    my $incorrect = 0;
 2775: 	    foreach my $item (keys(%status)) {
 2776: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2777: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2778: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2779: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2780: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2781: 		    $submitted = 0;
 2782: 		}
 2783: 	    }
 2784: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2785: 				     $submitonly eq 'incorrect' ||
 2786: 				     $submitonly eq 'graded'));
 2787: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2788: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2789: 	}
 2790: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2791: 	last if ($ctr == $ntstu);
 2792: 	$ctr++;
 2793:     }
 2794: 
 2795:     $ctr = 0;
 2796:     my $total = scalar(@nextlist)-1;
 2797: 
 2798:     foreach (sort(@nextlist)) {
 2799: 	my ($uname,$udom,$submitter) = split(/:/);
 2800: 	$env{'form.student'}  = $uname;
 2801: 	$env{'form.userdom'}  = $udom;
 2802: 	$env{'form.fullname'} = $$fullname{$_};
 2803: 	&submission($request,$ctr,$total);
 2804: 	$ctr++;
 2805:     }
 2806:     if ($total < 0) {
 2807: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2808: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2809: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2810: 	$the_end.=&show_grading_menu_form($symb);
 2811: 	$request->print($the_end);
 2812:     }
 2813:     return '';
 2814: }
 2815: 
 2816: #---- Save the score and award for each student, if changed
 2817: sub saveHandGrade {
 2818:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2819:     my @version_parts;
 2820:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2821: 					   $env{'request.course.id'});
 2822:     if (!&canmodify($usec)) { return('not_allowed'); }
 2823:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2824:     my @parts_graded;
 2825:     my %newrecord  = ();
 2826:     my ($pts,$wgt) = ('','');
 2827:     my %aggregate = ();
 2828:     my $aggregateflag = 0;
 2829:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2830:     foreach my $new_part (@parts) {
 2831: 	#collaborator ($submi may vary for different parts
 2832: 	if ($submitter && $new_part ne $part) { next; }
 2833: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2834: 	if ($dropMenu eq 'excused') {
 2835: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2836: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2837: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2838: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2839: 		}
 2840: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2841: 	    }
 2842: 	} elsif ($dropMenu eq 'reset status'
 2843: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2844: 	    foreach my $key (keys(%record)) {
 2845: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2846: 	    }
 2847: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2848: 		"$env{'user.name'}:$env{'user.domain'}";
 2849:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2850: 
 2851:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2852: 					       [$new_part]);
 2853:             my $aggtries =$totaltries;
 2854:             if ($last_resets{$new_part}) {
 2855:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2856: 					   $new_part);
 2857:             }
 2858: 
 2859:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2860:             if ($aggtries > 0) {
 2861:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2862:                 $aggregateflag = 1;
 2863:             }
 2864: 	} elsif ($dropMenu eq '') {
 2865: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2866: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2867: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2868: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2869: 		next;
 2870: 	    }
 2871: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2872: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2873: 	    my $partial= $pts/$wgt;
 2874: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2875: 		#do not update score for part if not changed.
 2876:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2877: 		next;
 2878: 	    } else {
 2879: 	        push(@parts_graded,$new_part);
 2880: 	    }
 2881: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2882: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2883: 	    }
 2884: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2885: 	    if ($partial == 0) {
 2886: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2887: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2888: 		}
 2889: 	    } else {
 2890: 		if ($record{$reckey} ne 'correct_by_override') {
 2891: 		    $newrecord{$reckey} = 'correct_by_override';
 2892: 		}
 2893: 	    }	    
 2894: 	    if ($submitter && 
 2895: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2896: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2897: 	    }
 2898: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2899: 		"$env{'user.name'}:$env{'user.domain'}";
 2900: 	}
 2901: 	# unless problem has been graded, set flag to version the submitted files
 2902: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2903: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2904: 	        $dropMenu eq 'reset status')
 2905: 	   {
 2906: 	    push(@version_parts,$new_part);
 2907: 	}
 2908:     }
 2909:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2910:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2911: 
 2912:     if (%newrecord) {
 2913:         if (@version_parts) {
 2914:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2915:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2916: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2917: 	    foreach my $new_part (@version_parts) {
 2918: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2919: 				$new_part,\%newrecord);
 2920: 	    }
 2921:         }
 2922: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2923: 				$env{'request.course.id'},$domain,$stuname);
 2924: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2925: 				     $cdom,$cnum,$domain,$stuname);
 2926:     }
 2927:     if ($aggregateflag) {
 2928:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2929: 			      $cdom,$cnum);
 2930:     }
 2931:     return ('',$pts,$wgt);
 2932: }
 2933: 
 2934: sub check_and_remove_from_queue {
 2935:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2936:     my @ungraded_parts;
 2937:     foreach my $part (@{$parts}) {
 2938: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2939: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2940: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2941: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2942: 		) {
 2943: 	    push(@ungraded_parts, $part);
 2944: 	}
 2945:     }
 2946:     if ( !@ungraded_parts ) {
 2947: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2948: 					       $cnum,$domain,$stuname);
 2949:     }
 2950: }
 2951: 
 2952: sub handback_files {
 2953:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2954:     my $portfolio_root = '/userfiles/portfolio';
 2955:     my $res_error;
 2956:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2957:     if ($res_error) {
 2958:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2959:         return;
 2960:     }
 2961:     my @part_response_id = &flatten_responseType($responseType);
 2962:     foreach my $part_response_id (@part_response_id) {
 2963:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2964: 	my $part_resp = join('_',@{ $part_response_id });
 2965:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2966:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2967:                 my $file_counter = 1;
 2968: 		my $file_msg;
 2969:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2970:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2971:                     my ($directory,$answer_file) = 
 2972:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2973:                     my ($answer_name,$answer_ver,$answer_ext) =
 2974: 		        &file_name_version_ext($answer_file);
 2975: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2976:                     my $getpropath = 1;
 2977: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2978: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2979:                     # fix file name
 2980:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2981:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2982:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2983:             	                                $save_file_name);
 2984:                     if ($result !~ m|^/uploaded/|) {
 2985:                         $request->print('<br /><span class="LC_error">'.
 2986:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2987:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2988:                                         '</span>');
 2989:                     } else {
 2990:                         # mark the file as read only
 2991:                         my @files = ($save_file_name);
 2992:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2993:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2994: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2995: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2996: 			}
 2997:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2998: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2999: 
 3000:                     }
 3001:                     $request->print("<br />".$fname." will be the uploaded file name");
 3002:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 3003:                     $file_counter++;
 3004:                 }
 3005: 		my $subject = "File Handed Back by Instructor ";
 3006: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 3007: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 3008: 		$message .= ' The returned file(s) are named: '. $file_msg;
 3009: 		$message .= " and can be found in your portfolio space.";
 3010: 		my ($feedurl,$showsymb) = 
 3011: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 3012:                 my $restitle = &Apache::lonnet::gettitle($symb);
 3013: 		my $msgstatus = 
 3014:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 3015: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 3016:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 3017:             }
 3018:         }
 3019:     return;
 3020: }
 3021: 
 3022: sub get_feedurl_and_symb {
 3023:     my ($symb,$uname,$udom) = @_;
 3024:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3025:     $url = &Apache::lonnet::clutter($url);
 3026:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 3027: 					$symb,$udom,$uname);
 3028:     if ($encrypturl =~ /^yes$/i) {
 3029: 	&Apache::lonenc::encrypted(\$url,1);
 3030: 	&Apache::lonenc::encrypted(\$symb,1);
 3031:     }
 3032:     return ($url,$symb);
 3033: }
 3034: 
 3035: sub get_submitted_files {
 3036:     my ($udom,$uname,$partid,$respid,$record) = @_;
 3037:     my @files;
 3038:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 3039:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 3040:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 3041:     	    push(@files,$file_url.$file);
 3042:         }
 3043:     }
 3044:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 3045:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 3046:     }
 3047:     return (\@files);
 3048: }
 3049: 
 3050: # ----------- Provides number of tries since last reset.
 3051: sub get_num_tries {
 3052:     my ($record,$last_reset,$part) = @_;
 3053:     my $timestamp = '';
 3054:     my $num_tries = 0;
 3055:     if ($$record{'version'}) {
 3056:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3057:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3058:                 $timestamp = $$record{$version.':timestamp'};
 3059:                 if ($timestamp > $last_reset) {
 3060:                     $num_tries ++;
 3061:                 } else {
 3062:                     last;
 3063:                 }
 3064:             }
 3065:         }
 3066:     }
 3067:     return $num_tries;
 3068: }
 3069: 
 3070: # ----------- Determine decrements required in aggregate totals 
 3071: sub decrement_aggs {
 3072:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3073:     my %decrement = (
 3074:                         attempts => 0,
 3075:                         users => 0,
 3076:                         correct => 0
 3077:                     );
 3078:     $decrement{'attempts'} = $aggtries;
 3079:     if ($solvedstatus =~ /^correct/) {
 3080:         $decrement{'correct'} = 1;
 3081:     }
 3082:     if ($aggtries == $totaltries) {
 3083:         $decrement{'users'} = 1;
 3084:     }
 3085:     foreach my $type (keys(%decrement)) {
 3086:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3087:     }
 3088:     return;
 3089: }
 3090: 
 3091: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3092: sub get_last_resets {
 3093:     my ($symb,$courseid,$partids) =@_;
 3094:     my %last_resets;
 3095:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3096:     my $cname = $env{'course.'.$courseid.'.num'};
 3097:     my @keys;
 3098:     foreach my $part (@{$partids}) {
 3099: 	push(@keys,"$symb\0$part\0resettime");
 3100:     }
 3101:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3102: 				     $cdom,$cname);
 3103:     foreach my $part (@{$partids}) {
 3104: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3105:     }
 3106:     return %last_resets;
 3107: }
 3108: 
 3109: # ----------- Handles creating versions for portfolio files as answers
 3110: sub version_portfiles {
 3111:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3112:     my $version_parts = join('|',@$v_flag);
 3113:     my @returned_keys;
 3114:     my $parts = join('|', @$parts_graded);
 3115:     my $portfolio_root = '/userfiles/portfolio';
 3116:     foreach my $key (keys(%$record)) {
 3117:         my $new_portfiles;
 3118:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3119:             my @versioned_portfiles;
 3120:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3121:             foreach my $file (@portfiles) {
 3122:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3123:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3124: 		my ($answer_name,$answer_ver,$answer_ext) =
 3125: 		    &file_name_version_ext($answer_file);
 3126:                 my $getpropath = 1;    
 3127:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3128:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3129:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3130:                 if ($new_answer ne 'problem getting file') {
 3131:                     push(@versioned_portfiles, $directory.$new_answer);
 3132:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3133:                         [$directory.$new_answer],
 3134:                         [$symb,$env{'request.course.id'},'graded']);
 3135:                 }
 3136:             }
 3137:             $$record{$key} = join(',',@versioned_portfiles);
 3138:             push(@returned_keys,$key);
 3139:         }
 3140:     } 
 3141:     return (@returned_keys);   
 3142: }
 3143: 
 3144: sub get_next_version {
 3145:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3146:     my $version;
 3147:     foreach my $row (@$dir_list) {
 3148:         my ($file) = split(/\&/,$row,2);
 3149:         my ($file_name,$file_version,$file_ext) =
 3150: 	    &file_name_version_ext($file);
 3151:         if (($file_name eq $answer_name) && 
 3152: 	    ($file_ext eq $answer_ext)) {
 3153:                 # gets here if filename and extension match, regardless of version
 3154:                 if ($file_version ne '') {
 3155:                 # a versioned file is found  so save it for later
 3156:                 if ($file_version > $version) {
 3157: 		    $version = $file_version;
 3158: 	        }
 3159:             }
 3160:         }
 3161:     } 
 3162:     $version ++;
 3163:     return($version);
 3164: }
 3165: 
 3166: sub version_selected_portfile {
 3167:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3168:     my ($answer_name,$answer_ver,$answer_ext) =
 3169:         &file_name_version_ext($file_name);
 3170:     my $new_answer;
 3171:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3172:     if($env{'form.copy'} eq '-1') {
 3173:         $new_answer = 'problem getting file';
 3174:     } else {
 3175:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3176:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3177:                             $stu_name,$domain,'copy',
 3178: 		        '/portfolio'.$directory.$new_answer);
 3179:     }    
 3180:     return ($new_answer);
 3181: }
 3182: 
 3183: sub file_name_version_ext {
 3184:     my ($file)=@_;
 3185:     my @file_parts = split(/\./, $file);
 3186:     my ($name,$version,$ext);
 3187:     if (@file_parts > 1) {
 3188: 	$ext=pop(@file_parts);
 3189: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3190: 	    $version=pop(@file_parts);
 3191: 	}
 3192: 	$name=join('.',@file_parts);
 3193:     } else {
 3194: 	$name=join('.',@file_parts);
 3195:     }
 3196:     return($name,$version,$ext);
 3197: }
 3198: 
 3199: #--------------------------------------------------------------------------------------
 3200: #
 3201: #-------------------------- Next few routines handles grading by section or whole class
 3202: #
 3203: #--- Javascript to handle grading by section or whole class
 3204: sub viewgrades_js {
 3205:     my ($request) = shift;
 3206: 
 3207:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3208:     $request->print(<<VIEWJAVASCRIPT);
 3209: <script type="text/javascript" language="javascript">
 3210:    function writePoint(partid,weight,point) {
 3211: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3212: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3213: 	if (point == "textval") {
 3214: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3215: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3216: 		alert("$alertmsg"+parseFloat(point));
 3217: 		var resetbox = false;
 3218: 		for (var i=0; i<radioButton.length; i++) {
 3219: 		    if (radioButton[i].checked) {
 3220: 			textbox.value = i;
 3221: 			resetbox = true;
 3222: 		    }
 3223: 		}
 3224: 		if (!resetbox) {
 3225: 		    textbox.value = "";
 3226: 		}
 3227: 		return;
 3228: 	    }
 3229: 	    if (parseFloat(point) > parseFloat(weight)) {
 3230: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3231: 				   ") greater than the weight for the part. Accept?");
 3232: 		if (resp == false) {
 3233: 		    textbox.value = "";
 3234: 		    return;
 3235: 		}
 3236: 	    }
 3237: 	    for (var i=0; i<radioButton.length; i++) {
 3238: 		radioButton[i].checked=false;
 3239: 		if (parseFloat(point) == i) {
 3240: 		    radioButton[i].checked=true;
 3241: 		}
 3242: 	    }
 3243: 
 3244: 	} else {
 3245: 	    textbox.value = parseFloat(point);
 3246: 	}
 3247: 	for (i=0;i<document.classgrade.total.value;i++) {
 3248: 	    var user = document.classgrade["ctr"+i].value;
 3249: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3250: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3251: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3252: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3253: 	    if (saveval != "correct") {
 3254: 		scorename.value = point;
 3255: 		if (selname[0].selected != true) {
 3256: 		    selname[0].selected = true;
 3257: 		}
 3258: 	    }
 3259: 	}
 3260: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3261:     }
 3262: 
 3263:     function writeRadText(partid,weight) {
 3264: 	var selval   = document.classgrade["SELVAL_"+partid];
 3265: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3266:         var override = document.classgrade["FORCE_"+partid].checked;
 3267: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3268: 	if (selval[1].selected || selval[2].selected) {
 3269: 	    for (var i=0; i<radioButton.length; i++) {
 3270: 		radioButton[i].checked=false;
 3271: 
 3272: 	    }
 3273: 	    textbox.value = "";
 3274: 
 3275: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3276: 		var user = document.classgrade["ctr"+i].value;
 3277: 		user = user.replace(new RegExp(':', 'g'),"_");
 3278: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3279: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3280: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3281: 		if ((saveval != "correct") || override) {
 3282: 		    scorename.value = "";
 3283: 		    if (selval[1].selected) {
 3284: 			selname[1].selected = true;
 3285: 		    } else {
 3286: 			selname[2].selected = true;
 3287: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3288: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3289: 		    }
 3290: 		}
 3291: 	    }
 3292: 	} else {
 3293: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3294: 		var user = document.classgrade["ctr"+i].value;
 3295: 		user = user.replace(new RegExp(':', 'g'),"_");
 3296: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3297: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3298: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3299: 		if ((saveval != "correct") || override) {
 3300: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3301: 		    selname[0].selected = true;
 3302: 		}
 3303: 	    }
 3304: 	}	    
 3305:     }
 3306: 
 3307:     function changeSelect(partid,user) {
 3308: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3309: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3310: 	var point  = textbox.value;
 3311: 	var weight = document.classgrade["weight_"+partid].value;
 3312: 
 3313: 	if (isNaN(point) || parseFloat(point) < 0) {
 3314: 	    alert("$alertmsg"+parseFloat(point));
 3315: 	    textbox.value = "";
 3316: 	    return;
 3317: 	}
 3318: 	if (parseFloat(point) > parseFloat(weight)) {
 3319: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3320: 			       ") greater than the weight of the part. Accept?");
 3321: 	    if (resp == false) {
 3322: 		textbox.value = "";
 3323: 		return;
 3324: 	    }
 3325: 	}
 3326: 	selval[0].selected = true;
 3327:     }
 3328: 
 3329:     function changeOneScore(partid,user) {
 3330: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3331: 	if (selval[1].selected || selval[2].selected) {
 3332: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3333: 	    if (selval[2].selected) {
 3334: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3335: 	    }
 3336:         }
 3337:     }
 3338: 
 3339:     function resetEntry(numpart) {
 3340: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3341: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3342: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3343: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3344: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3345: 	    for (var i=0; i<radioButton.length; i++) {
 3346: 		radioButton[i].checked=false;
 3347: 
 3348: 	    }
 3349: 	    textbox.value = "";
 3350: 	    selval[0].selected = true;
 3351: 
 3352: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3353: 		var user = document.classgrade["ctr"+i].value;
 3354: 		user = user.replace(new RegExp(':', 'g'),"_");
 3355: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3356: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3357: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3358: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3359: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3360: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3361: 		if (saveselval == "excused") {
 3362: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3363: 		} else {
 3364: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3365: 		}
 3366: 	    }
 3367: 	}
 3368:     }
 3369: 
 3370: </script>
 3371: VIEWJAVASCRIPT
 3372: }
 3373: 
 3374: #--- show scores for a section or whole class w/ option to change/update a score
 3375: sub viewgrades {
 3376:     my ($request) = shift;
 3377:     &viewgrades_js($request);
 3378: 
 3379:     my ($symb) = &get_symb($request);
 3380:     #need to make sure we have the correct data for later EXT calls, 
 3381:     #thus invalidate the cache
 3382:     &Apache::lonnet::devalidatecourseresdata(
 3383:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3384:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3385:     &Apache::lonnet::clear_EXT_cache_status();
 3386: 
 3387:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3388:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3389: 
 3390:     #view individual student submission form - called using Javascript viewOneStudent
 3391:     $result.=&jscriptNform($symb);
 3392: 
 3393:     #beginning of class grading form
 3394:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3395:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3396: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3397: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3398: 	&build_section_inputs().
 3399: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3400: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3401: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3402: 
 3403:     my ($common_header,$specific_header);
 3404:     if ($env{'form.section'} eq 'all') {
 3405: 	$common_header = &mt('Assign Common Grade to Class');
 3406:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3407:     } elsif ($env{'form.section'} eq 'none') {
 3408:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3409: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3410:     } else {
 3411:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3412:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3413: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3414:     }
 3415:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3416:     #radio buttons/text box for assigning points for a section or class.
 3417:     #handles different parts of a problem
 3418:     my $res_error;
 3419:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3420:     if ($res_error) {
 3421:         return &navmap_errormsg();
 3422:     }
 3423:     my %weight = ();
 3424:     my $ctsparts = 0;
 3425:     my %seen = ();
 3426:     my @part_response_id = &flatten_responseType($responseType);
 3427:     foreach my $part_response_id (@part_response_id) {
 3428:     	my ($partid,$respid) = @{ $part_response_id };
 3429: 	my $part_resp = join('_',@{ $part_response_id });
 3430: 	next if $seen{$partid};
 3431: 	$seen{$partid}++;
 3432: 	my $handgrade=$$handgrade{$part_resp};
 3433: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3434: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3435: 
 3436: 	my $display_part=&get_display_part($partid,$symb);
 3437: 	my $radio.='<table border="0"><tr>';  
 3438: 	my $ctr = 0;
 3439: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3440: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3441: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3442: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3443: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3444: 	    $ctr++;
 3445: 	}
 3446: 	$radio.='</tr></table>';
 3447: 	my $line = '<input type="text" name="TEXTVAL_'.
 3448: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
 3449: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3450: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3451: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3452: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
 3453: 		$weight{$partid}.')"> '.
 3454: 	    '<option selected="selected"> </option>'.
 3455: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3456: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3457: 	    '</select></td>'.
 3458:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3459: 	$line.='<input type="hidden" name="partid_'.
 3460: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3461: 	$line.='<input type="hidden" name="weight_'.
 3462: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3463: 
 3464: 	$result.=
 3465: 	    &Apache::loncommon::start_data_table_row()."\n".
 3466: 	    '<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>'.
 3467: 	    &Apache::loncommon::end_data_table_row()."\n";
 3468: 	$ctsparts++;
 3469:     }
 3470:     $result.=&Apache::loncommon::end_data_table()."\n".
 3471: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3472:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3473: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
 3474: 
 3475:     #table listing all the students in a section/class
 3476:     #header of table
 3477:     $result.= '<h3>'.$specific_header.'</h3>'.
 3478:               &Apache::loncommon::start_data_table().
 3479: 	      &Apache::loncommon::start_data_table_header_row().
 3480: 	      '<th>'.&mt('No.').'</th>'.
 3481: 	      '<th>'.&nameUserString('header')."</th>\n";
 3482:     my $partserror;
 3483:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3484:     if ($partserror) {
 3485:         return &navmap_errormsg();
 3486:     }
 3487:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3488:     my @partids = ();
 3489:     foreach my $part (@parts) {
 3490: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3491:         my $narrowtext = &mt('Tries');
 3492: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3493: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3494: 	my ($partid) = &split_part_type($part);
 3495:         push(@partids,$partid);
 3496: 	my $display_part=&get_display_part($partid,$symb);
 3497: 	if ($display =~ /^Partial Credit Factor/) {
 3498: 	    $result.='<th>'.
 3499: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3500: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3501: 	    next;
 3502: 	    
 3503: 	} else {
 3504: 	    if ($display =~ /Problem Status/) {
 3505: 		my $grade_status_mt = &mt('Grade Status');
 3506: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3507: 	    }
 3508: 	    my $part_mt = &mt('Part:');
 3509: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3510: 	}
 3511: 
 3512: 	$result.='<th>'.$display.'</th>'."\n";
 3513:     }
 3514:     $result.=&Apache::loncommon::end_data_table_header_row();
 3515: 
 3516:     my %last_resets = 
 3517: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3518: 
 3519:     #get info for each student
 3520:     #list all the students - with points and grade status
 3521:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3522:     my $ctr = 0;
 3523:     foreach (sort 
 3524: 	     {
 3525: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3526: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3527: 		 }
 3528: 		 return $a cmp $b;
 3529: 	     } (keys(%$fullname))) {
 3530: 	$ctr++;
 3531: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3532: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3533:     }
 3534:     $result.=&Apache::loncommon::end_data_table();
 3535:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3536:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3537: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
 3538:     if (scalar(%$fullname) eq 0) {
 3539: 	my $colspan=3+scalar(@parts);
 3540: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3541:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3542: 	$result='<span class="LC_warning">'.
 3543: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3544: 	        $section_display, $stu_status).
 3545: 	    '</span>';
 3546:     }
 3547:     $result.=&show_grading_menu_form($symb);
 3548:     return $result;
 3549: }
 3550: 
 3551: #--- call by previous routine to display each student
 3552: sub viewstudentgrade {
 3553:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3554:     my ($uname,$udom) = split(/:/,$student);
 3555:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3556:     my %aggregates = (); 
 3557:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3558: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3559: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3560: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3561: 	'\');" target="_self">'.$fullname.'</a> '.
 3562: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3563:     $student=~s/:/_/; # colon doen't work in javascript for names
 3564:     foreach my $apart (@$parts) {
 3565: 	my ($part,$type) = &split_part_type($apart);
 3566: 	my $score=$record{"resource.$part.$type"};
 3567:         $result.='<td align="center">';
 3568:         my ($aggtries,$totaltries);
 3569:         unless (exists($aggregates{$part})) {
 3570: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3571: 
 3572: 	    $aggtries = $totaltries;
 3573:             if ($$last_resets{$part}) {  
 3574:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3575: 					   $part);
 3576:             }
 3577:             $result.='<input type="hidden" name="'.
 3578:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3579:             $result.='<input type="hidden" name="'.
 3580:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3581:             $aggregates{$part} = 1;
 3582:         }
 3583: 	if ($type eq 'awarded') {
 3584: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3585: 	    $result.='<input type="hidden" name="'.
 3586: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3587: 	    $result.='<input type="text" name="'.
 3588: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3589:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3590: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3591: 	} elsif ($type eq 'solved') {
 3592: 	    my ($status,$foo)=split(/_/,$score,2);
 3593: 	    $status = 'nothing' if ($status eq '');
 3594: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3595: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3596: 	    $result.='&nbsp;<select name="'.
 3597: 		'GD_'.$student.'_'.$part.'_solved" '.
 3598:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3599: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3600: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3601: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3602: 	    $result.="</select>&nbsp;</td>\n";
 3603: 	} else {
 3604: 	    $result.='<input type="hidden" name="'.
 3605: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3606: 		    "\n";
 3607: 	    $result.='<input type="text" name="'.
 3608: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3609: 		'value="'.$score.'" size="4" /></td>'."\n";
 3610: 	}
 3611:     }
 3612:     $result.=&Apache::loncommon::end_data_table_row();
 3613:     return $result;
 3614: }
 3615: 
 3616: #--- change scores for all the students in a section/class
 3617: #    record does not get update if unchanged
 3618: sub editgrades {
 3619:     my ($request) = @_;
 3620: 
 3621:     my $symb=&get_symb($request);
 3622:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3623:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3624:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3625:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3626: 
 3627:     my $result= &Apache::loncommon::start_data_table().
 3628: 	&Apache::loncommon::start_data_table_header_row().
 3629: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3630: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3631:     my %scoreptr = (
 3632: 		    'correct'  =>'correct_by_override',
 3633: 		    'incorrect'=>'incorrect_by_override',
 3634: 		    'excused'  =>'excused',
 3635: 		    'ungraded' =>'ungraded_attempted',
 3636:                     'credited' =>'credit_attempted',
 3637: 		    'nothing'  => '',
 3638: 		    );
 3639:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3640: 
 3641:     my (@partid);
 3642:     my %weight = ();
 3643:     my %columns = ();
 3644:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3645: 
 3646:     my $partserror;
 3647:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3648:     if ($partserror) {
 3649:         return &navmap_errormsg();
 3650:     }
 3651:     my $header;
 3652:     while ($ctr < $env{'form.totalparts'}) {
 3653: 	my $partid = $env{'form.partid_'.$ctr};
 3654: 	push(@partid,$partid);
 3655: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3656: 	$ctr++;
 3657:     }
 3658:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3659:     foreach my $partid (@partid) {
 3660: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3661: 	    '<th align="center">'.&mt('New Score').'</th>';
 3662: 	$columns{$partid}=2;
 3663: 	foreach my $stores (@parts) {
 3664: 	    my ($part,$type) = &split_part_type($stores);
 3665: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3666: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3667: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3668: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3669:             my $narrowtext = &mt('Tries');
 3670: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3671: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3672: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3673: 	    $columns{$partid}+=2;
 3674: 	}
 3675:     }
 3676:     foreach my $partid (@partid) {
 3677: 	my $display_part=&get_display_part($partid,$symb);
 3678: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3679: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3680: 	    '</th>';
 3681: 
 3682:     }
 3683:     $result .= &Apache::loncommon::end_data_table_header_row().
 3684: 	&Apache::loncommon::start_data_table_header_row().
 3685: 	$header.
 3686: 	&Apache::loncommon::end_data_table_header_row();
 3687:     my @noupdate;
 3688:     my ($updateCtr,$noupdateCtr) = (1,1);
 3689:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3690: 	my $line;
 3691: 	my $user = $env{'form.ctr'.$i};
 3692: 	my ($uname,$udom)=split(/:/,$user);
 3693: 	my %newrecord;
 3694: 	my $updateflag = 0;
 3695: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3696: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3697: 	if (!&canmodify($usec)) {
 3698: 	    my $numcols=scalar(@partid)*4+2;
 3699: 	    push(@noupdate,
 3700: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3701: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3702: 	    next;
 3703: 	}
 3704:         my %aggregate = ();
 3705:         my $aggregateflag = 0;
 3706: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3707: 	foreach (@partid) {
 3708: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3709: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3710: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3711: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3712: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3713: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3714: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3715: 	    my $score;
 3716: 	    if ($partial eq '') {
 3717: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3718: 	    } elsif ($partial > 0) {
 3719: 		$score = 'correct_by_override';
 3720: 	    } elsif ($partial == 0) {
 3721: 		$score = 'incorrect_by_override';
 3722: 	    }
 3723: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3724: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3725: 
 3726: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3727: 		"$env{'user.name'}:$env{'user.domain'}";
 3728: 	    if ($dropMenu eq 'reset status' &&
 3729: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3730: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3731: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3732: 		$newrecord{'resource.'.$_.'.award'} = '';
 3733: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3734: 		$updateflag = 1;
 3735:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3736:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3737:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3738:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3739:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3740:                     $aggregateflag = 1;
 3741:                 }
 3742: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3743: 		$updateflag = 1;
 3744: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3745: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3746: 		$rec_update++;
 3747: 	    }
 3748: 
 3749: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3750: 		'<td align="center">'.$awarded.
 3751: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3752: 
 3753: 
 3754: 	    my $partid=$_;
 3755: 	    foreach my $stores (@parts) {
 3756: 		my ($part,$type) = &split_part_type($stores);
 3757: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3758: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3759: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3760: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3761: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3762: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3763: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3764: 		    $updateflag=1;
 3765: 		}
 3766: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3767: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3768: 	    }
 3769: 	}
 3770: 	$line.="\n";
 3771: 
 3772: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3773: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3774: 
 3775: 	if ($updateflag) {
 3776: 	    $count++;
 3777: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3778: 				    $udom,$uname);
 3779: 
 3780: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3781: 					      $cnum,$udom,$uname)) {
 3782: 		# need to figure out if should be in queue.
 3783: 		my %record =  
 3784: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3785: 					     $udom,$uname);
 3786: 		my $all_graded = 1;
 3787: 		my $none_graded = 1;
 3788: 		foreach my $part (@parts) {
 3789: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3790: 			$all_graded = 0;
 3791: 		    } else {
 3792: 			$none_graded = 0;
 3793: 		    }
 3794: 		}
 3795: 
 3796: 		if ($all_graded || $none_graded) {
 3797: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3798: 							   $symb,$cdom,$cnum,
 3799: 							   $udom,$uname);
 3800: 		}
 3801: 	    }
 3802: 
 3803: 	    $result.=&Apache::loncommon::start_data_table_row().
 3804: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3805: 		&Apache::loncommon::end_data_table_row();
 3806: 	    $updateCtr++;
 3807: 	} else {
 3808: 	    push(@noupdate,
 3809: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3810: 	    $noupdateCtr++;
 3811: 	}
 3812:         if ($aggregateflag) {
 3813:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3814: 				  $cdom,$cnum);
 3815:         }
 3816:     }
 3817:     if (@noupdate) {
 3818: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3819: 	my $numcols=scalar(@partid)*4+2;
 3820: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3821: 	    '<td align="center" colspan="'.$numcols.'">'.
 3822: 	    &mt('No Changes Occurred For the Students Below').
 3823: 	    '</td>'.
 3824: 	    &Apache::loncommon::end_data_table_row();
 3825: 	foreach my $line (@noupdate) {
 3826: 	    $result.=
 3827: 		&Apache::loncommon::start_data_table_row().
 3828: 		$line.
 3829: 		&Apache::loncommon::end_data_table_row();
 3830: 	}
 3831:     }
 3832:     $result .= &Apache::loncommon::end_data_table().
 3833: 	&show_grading_menu_form($symb);
 3834:     my $msg = '<p><b>'.
 3835: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3836: 	    $rec_update,$count).'</b><br />'.
 3837: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3838: 	'</b></p>';
 3839:     return $title.$msg.$result;
 3840: }
 3841: 
 3842: sub split_part_type {
 3843:     my ($partstr) = @_;
 3844:     my ($temp,@allparts)=split(/_/,$partstr);
 3845:     my $type=pop(@allparts);
 3846:     my $part=join('_',@allparts);
 3847:     return ($part,$type);
 3848: }
 3849: 
 3850: #------------- end of section for handling grading by section/class ---------
 3851: #
 3852: #----------------------------------------------------------------------------
 3853: 
 3854: 
 3855: #----------------------------------------------------------------------------
 3856: #
 3857: #-------------------------- Next few routines handles grading by csv upload
 3858: #
 3859: #--- Javascript to handle csv upload
 3860: sub csvupload_javascript_reverse_associate {
 3861:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3862:     my $error2=&mt('You need to specify at least one grading field');
 3863:   return(<<ENDPICK);
 3864:   function verify(vf) {
 3865:     var foundsomething=0;
 3866:     var founduname=0;
 3867:     var foundID=0;
 3868:     for (i=0;i<=vf.nfields.value;i++) {
 3869:       tw=eval('vf.f'+i+'.selectedIndex');
 3870:       if (i==0 && tw!=0) { foundID=1; }
 3871:       if (i==1 && tw!=0) { founduname=1; }
 3872:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3873:     }
 3874:     if (founduname==0 && foundID==0) {
 3875: 	alert('$error1');
 3876: 	return;
 3877:     }
 3878:     if (foundsomething==0) {
 3879: 	alert('$error2');
 3880: 	return;
 3881:     }
 3882:     vf.submit();
 3883:   }
 3884:   function flip(vf,tf) {
 3885:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3886:     var i;
 3887:     for (i=0;i<=vf.nfields.value;i++) {
 3888:       //can not pick the same destination field for both name and domain
 3889:       if (((i ==0)||(i ==1)) && 
 3890:           ((tf==0)||(tf==1)) && 
 3891:           (i!=tf) &&
 3892:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3893:         eval('vf.f'+i+'.selectedIndex=0;')
 3894:       }
 3895:     }
 3896:   }
 3897: ENDPICK
 3898: }
 3899: 
 3900: sub csvupload_javascript_forward_associate {
 3901:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3902:     my $error2=&mt('You need to specify at least one grading field');
 3903:   return(<<ENDPICK);
 3904:   function verify(vf) {
 3905:     var foundsomething=0;
 3906:     var founduname=0;
 3907:     var foundID=0;
 3908:     for (i=0;i<=vf.nfields.value;i++) {
 3909:       tw=eval('vf.f'+i+'.selectedIndex');
 3910:       if (tw==1) { foundID=1; }
 3911:       if (tw==2) { founduname=1; }
 3912:       if (tw>3) { foundsomething=1; }
 3913:     }
 3914:     if (founduname==0 && foundID==0) {
 3915: 	alert('$error1');
 3916: 	return;
 3917:     }
 3918:     if (foundsomething==0) {
 3919: 	alert('$error2');
 3920: 	return;
 3921:     }
 3922:     vf.submit();
 3923:   }
 3924:   function flip(vf,tf) {
 3925:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3926:     var i;
 3927:     //can not pick the same destination field twice
 3928:     for (i=0;i<=vf.nfields.value;i++) {
 3929:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3930:         eval('vf.f'+i+'.selectedIndex=0;')
 3931:       }
 3932:     }
 3933:   }
 3934: ENDPICK
 3935: }
 3936: 
 3937: sub csvuploadmap_header {
 3938:     my ($request,$symb,$datatoken,$distotal)= @_;
 3939:     my $javascript;
 3940:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3941: 	$javascript=&csvupload_javascript_reverse_associate();
 3942:     } else {
 3943: 	$javascript=&csvupload_javascript_forward_associate();
 3944:     }
 3945: 
 3946:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3947:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3948:     my $ignore=&mt('Ignore First Line');
 3949:     $symb = &Apache::lonenc::check_encrypt($symb);
 3950:     $request->print(<<ENDPICK);
 3951: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3952: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3953: $result
 3954: <hr />
 3955: <h3>Identify fields</h3>
 3956: Total number of records found in file: $distotal <hr />
 3957: Enter as many fields as you can. The system will inform you and bring you back
 3958: to this page if the data selected is insufficient to run your class.<hr />
 3959: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3960: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3961: <input type="hidden" name="associate"  value="" />
 3962: <input type="hidden" name="phase"      value="three" />
 3963: <input type="hidden" name="datatoken"  value="$datatoken" />
 3964: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3965: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3966: <input type="hidden" name="upfile_associate" 
 3967:                                        value="$env{'form.upfile_associate'}" />
 3968: <input type="hidden" name="symb"       value="$symb" />
 3969: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3970: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3971: <input type="hidden" name="command"    value="csvuploadoptions" />
 3972: <hr />
 3973: <script type="text/javascript" language="Javascript">
 3974: $javascript
 3975: </script>
 3976: ENDPICK
 3977:     return '';
 3978: 
 3979: }
 3980: 
 3981: sub csvupload_fields {
 3982:     my ($symb,$errorref) = @_;
 3983:     my (@parts) = &getpartlist($symb,$errorref);
 3984:     if (ref($errorref)) {
 3985:         if ($$errorref) {
 3986:             return;
 3987:         }
 3988:     }
 3989: 
 3990:     my @fields=(['ID','Student/Employee ID'],
 3991: 		['username','Student Username'],
 3992: 		['domain','Student Domain']);
 3993:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3994:     foreach my $part (sort(@parts)) {
 3995: 	my @datum;
 3996: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3997: 	my $name=$part;
 3998: 	if  (!$display) { $display = $name; }
 3999: 	@datum=($name,$display);
 4000: 	if ($name=~/^stores_(.*)_awarded/) {
 4001: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 4002: 	}
 4003: 	push(@fields,\@datum);
 4004:     }
 4005:     return (@fields);
 4006: }
 4007: 
 4008: sub csvuploadmap_footer {
 4009:     my ($request,$i,$keyfields) =@_;
 4010:     $request->print(<<ENDPICK);
 4011: </table>
 4012: <input type="hidden" name="nfields" value="$i" />
 4013: <input type="hidden" name="keyfields" value="$keyfields" />
 4014: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
 4015: </form>
 4016: ENDPICK
 4017: }
 4018: 
 4019: sub checkforfile_js {
 4020:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 4021:     my $result =<<CSVFORMJS;
 4022: <script type="text/javascript" language="javascript">
 4023:     function checkUpload(formname) {
 4024: 	if (formname.upfile.value == "") {
 4025: 	    alert("$alertmsg");
 4026: 	    return false;
 4027: 	}
 4028: 	formname.submit();
 4029:     }
 4030:     </script>
 4031: CSVFORMJS
 4032:     return $result;
 4033: }
 4034: 
 4035: sub upcsvScores_form {
 4036:     my ($request) = shift;
 4037:     my ($symb)=&get_symb($request);
 4038:     if (!$symb) {return '';}
 4039:     my $result=&checkforfile_js();
 4040:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 4041:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 4042:     $result.=$table;
 4043:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 4044:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 4045:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 4046: 	'</b></td></tr>'."\n";
 4047:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 4048:     my $upload=&mt("Upload Scores");
 4049:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 4050:     my $ignore=&mt('Ignore First Line');
 4051:     $symb = &Apache::lonenc::check_encrypt($symb);
 4052:     $result.=<<ENDUPFORM;
 4053: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4054: <input type="hidden" name="symb" value="$symb" />
 4055: <input type="hidden" name="command" value="csvuploadmap" />
 4056: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 4057: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 4058: $upfile_select
 4059: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 4060: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 4061: </form>
 4062: ENDUPFORM
 4063:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4064:                            &mt("How do I create a CSV file from a spreadsheet"))
 4065:     .'</td></tr></table>'."\n";
 4066:     $result.='</td></tr></table><br /><br />'."\n";
 4067:     $result.=&show_grading_menu_form($symb);
 4068:     return $result;
 4069: }
 4070: 
 4071: 
 4072: sub csvuploadmap {
 4073:     my ($request)= @_;
 4074:     my ($symb)=&get_symb($request);
 4075:     if (!$symb) {return '';}
 4076: 
 4077:     my $datatoken;
 4078:     if (!$env{'form.datatoken'}) {
 4079: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4080:     } else {
 4081: 	$datatoken=$env{'form.datatoken'};
 4082: 	&Apache::loncommon::load_tmp_file($request);
 4083:     }
 4084:     my @records=&Apache::loncommon::upfile_record_sep();
 4085:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4086:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4087:     my ($i,$keyfields);
 4088:     if (@records) {
 4089:         my $fieldserror;
 4090: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4091:         if ($fieldserror) {
 4092:             $request->print(&navmap_errormsg());
 4093:             return;
 4094:         }
 4095: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4096: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4097: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4098: 							  \@fields);
 4099: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4100: 	    chop($keyfields);
 4101: 	} else {
 4102: 	    unshift(@fields,['none','']);
 4103: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4104: 							    \@fields);
 4105:             foreach my $rec (@records) {
 4106:                 my %temp = &Apache::loncommon::record_sep($rec);
 4107:                 if (%temp) {
 4108:                     $keyfields=join(',',sort(keys(%temp)));
 4109:                     last;
 4110:                 }
 4111:             }
 4112: 	}
 4113:     }
 4114:     &csvuploadmap_footer($request,$i,$keyfields);
 4115:     $request->print(&show_grading_menu_form($symb));
 4116: 
 4117:     return '';
 4118: }
 4119: 
 4120: sub csvuploadoptions {
 4121:     my ($request)= @_;
 4122:     my ($symb)=&get_symb($request);
 4123:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4124:     my $ignore=&mt('Ignore First Line');
 4125:     $request->print(<<ENDPICK);
 4126: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4127: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4128: <input type="hidden" name="command"    value="csvuploadassign" />
 4129: <!--
 4130: <p>
 4131: <label>
 4132:    <input type="checkbox" name="show_full_results" />
 4133:    Show a table of all changes
 4134: </label>
 4135: </p>
 4136: -->
 4137: <p>
 4138: <label>
 4139:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4140:    Overwrite any existing score
 4141: </label>
 4142: </p>
 4143: ENDPICK
 4144:     my %fields=&get_fields();
 4145:     if (!defined($fields{'domain'})) {
 4146: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4147: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4148:     }
 4149:     foreach my $key (sort(keys(%env))) {
 4150: 	if ($key !~ /^form\.(.*)$/) { next; }
 4151: 	my $cleankey=$1;
 4152: 	if ($cleankey eq 'command') { next; }
 4153: 	$request->print('<input type="hidden" name="'.$cleankey.
 4154: 			'"  value="'.$env{$key}.'" />'."\n");
 4155:     }
 4156:     # FIXME do a check for any duplicated user ids...
 4157:     # FIXME do a check for any invalid user ids?...
 4158:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4159: <hr /></form>'."\n");
 4160:     $request->print(&show_grading_menu_form($symb));
 4161:     return '';
 4162: }
 4163: 
 4164: sub get_fields {
 4165:     my %fields;
 4166:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4167:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4168: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4169: 	    if ($env{'form.f'.$i} ne 'none') {
 4170: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4171: 	    }
 4172: 	} else {
 4173: 	    if ($env{'form.f'.$i} ne 'none') {
 4174: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4175: 	    }
 4176: 	}
 4177:     }
 4178:     return %fields;
 4179: }
 4180: 
 4181: sub csvuploadassign {
 4182:     my ($request)= @_;
 4183:     my ($symb)=&get_symb($request);
 4184:     if (!$symb) {return '';}
 4185:     my $error_msg = '';
 4186:     &Apache::loncommon::load_tmp_file($request);
 4187:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4188:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4189:     my %fields=&get_fields();
 4190:     $request->print('<h3>Assigning Grades</h3>');
 4191:     my $courseid=$env{'request.course.id'};
 4192:     my ($classlist) = &getclasslist('all',0);
 4193:     my @notallowed;
 4194:     my @skipped;
 4195:     my $countdone=0;
 4196:     foreach my $grade (@gradedata) {
 4197: 	my %entries=&Apache::loncommon::record_sep($grade);
 4198: 	my $domain;
 4199: 	if ($entries{$fields{'domain'}}) {
 4200: 	    $domain=$entries{$fields{'domain'}};
 4201: 	} else {
 4202: 	    $domain=$env{'form.default_domain'};
 4203: 	}
 4204: 	$domain=~s/\s//g;
 4205: 	my $username=$entries{$fields{'username'}};
 4206: 	$username=~s/\s//g;
 4207: 	if (!$username) {
 4208: 	    my $id=$entries{$fields{'ID'}};
 4209: 	    $id=~s/\s//g;
 4210: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4211: 	    $username=$ids{$id};
 4212: 	}
 4213: 	if (!exists($$classlist{"$username:$domain"})) {
 4214: 	    my $id=$entries{$fields{'ID'}};
 4215: 	    $id=~s/\s//g;
 4216: 	    if ($id) {
 4217: 		push(@skipped,"$id:$domain");
 4218: 	    } else {
 4219: 		push(@skipped,"$username:$domain");
 4220: 	    }
 4221: 	    next;
 4222: 	}
 4223: 	my $usec=$classlist->{"$username:$domain"}[5];
 4224: 	if (!&canmodify($usec)) {
 4225: 	    push(@notallowed,"$username:$domain");
 4226: 	    next;
 4227: 	}
 4228: 	my %points;
 4229: 	my %grades;
 4230: 	foreach my $dest (keys(%fields)) {
 4231: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4232: 		$dest eq 'domain') { next; }
 4233: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4234: 	    if ($dest=~/stores_(.*)_points/) {
 4235: 		my $part=$1;
 4236: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4237: 					      $symb,$domain,$username);
 4238:                 if ($wgt) {
 4239:                     $entries{$fields{$dest}}=~s/\s//g;
 4240:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4241:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4242:                                           : 'correct_by_override';
 4243:                     $grades{"resource.$part.awarded"}=$pcr;
 4244:                     $grades{"resource.$part.solved"}=$award;
 4245:                     $points{$part}=1;
 4246:                 } else {
 4247:                     $error_msg = "<br />" .
 4248:                         &mt("Some point values were assigned"
 4249:                             ." for problems with a weight "
 4250:                             ."of zero. These values were "
 4251:                             ."ignored.");
 4252:                 }
 4253: 	    } else {
 4254: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4255: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4256: 		my $store_key=$dest;
 4257: 		$store_key=~s/^stores/resource/;
 4258: 		$store_key=~s/_/\./g;
 4259: 		$grades{$store_key}=$entries{$fields{$dest}};
 4260: 	    }
 4261: 	}
 4262: 	if (! %grades) { 
 4263:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4264:         } else {
 4265: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4266: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4267: 					   $env{'request.course.id'},
 4268: 					   $domain,$username);
 4269: 	   if ($result eq 'ok') {
 4270: 	      $request->print('.');
 4271: 	   } else {
 4272: 	      $request->print("<p><span class=\"LC_error\">".
 4273:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4274:                                   "$username:$domain",$result)."</span></p>");
 4275: 	   }
 4276: 	   $request->rflush();
 4277: 	   $countdone++;
 4278:         }
 4279:     }
 4280:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4281:     if (@skipped) {
 4282: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4283:         $request->print(join(', ',@skipped));
 4284:     }
 4285:     if (@notallowed) {
 4286: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4287: 	$request->print(join(', ',@notallowed));
 4288:     }
 4289:     $request->print("<br />\n");
 4290:     $request->print(&show_grading_menu_form($symb));
 4291:     return $error_msg;
 4292: }
 4293: #------------- end of section for handling csv file upload ---------
 4294: #
 4295: #-------------------------------------------------------------------
 4296: #
 4297: #-------------- Next few routines handle grading by page/sequence
 4298: #
 4299: #--- Select a page/sequence and a student to grade
 4300: sub pickStudentPage {
 4301:     my ($request) = shift;
 4302: 
 4303:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4304:     $request->print(<<LISTJAVASCRIPT);
 4305: <script type="text/javascript" language="javascript">
 4306: 
 4307: function checkPickOne(formname) {
 4308:     if (radioSelection(formname.student) == null) {
 4309: 	alert("$alertmsg");
 4310: 	return;
 4311:     }
 4312:     ptr = pullDownSelection(formname.selectpage);
 4313:     formname.page.value = formname["page"+ptr].value;
 4314:     formname.title.value = formname["title"+ptr].value;
 4315:     formname.submit();
 4316: }
 4317: 
 4318: </script>
 4319: LISTJAVASCRIPT
 4320:     &commonJSfunctions($request);
 4321:     my ($symb) = &get_symb($request);
 4322:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4323:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4324:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4325: 
 4326:     my $result='<h3><span class="LC_info">&nbsp;'.
 4327: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4328: 
 4329:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4330:     my $map_error;
 4331:     my ($titles,$symbx) = &getSymbMap($map_error);
 4332:     if ($map_error) {
 4333:         $request->print(&navmap_errormsg());
 4334:         return; 
 4335:     }
 4336:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4337: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4338: #    my $type=($curpage =~ /\.(page|sequence)/);
 4339:     my $select = '<select name="selectpage">'."\n";
 4340:     my $ctr=0;
 4341:     foreach (@$titles) {
 4342: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4343: 	$select.='<option value="'.$ctr.'" '.
 4344: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4345: 	    '>'.$showtitle.'</option>'."\n";
 4346: 	$ctr++;
 4347:     }
 4348:     $select.= '</select>';
 4349:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4350: 
 4351:     $ctr=0;
 4352:     foreach (@$titles) {
 4353: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4354: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4355: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4356: 	$ctr++;
 4357:     }
 4358:     $result.='<input type="hidden" name="page" />'."\n".
 4359: 	'<input type="hidden" name="title" />'."\n";
 4360: 
 4361:     my $options =
 4362: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4363: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4364:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4365: 
 4366:     $options =
 4367: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4368: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4369: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4370:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4371:     
 4372:     $result.=&build_section_inputs();
 4373:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4374:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4375: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4376: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4377: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4378: 
 4379:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4380: 
 4381:     $result.='&nbsp;<input type="button" '.
 4382:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4383: 
 4384:     $request->print($result);
 4385: 
 4386:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4387: 	&Apache::loncommon::start_data_table().
 4388: 	&Apache::loncommon::start_data_table_header_row().
 4389: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4390: 	'<th>'.&nameUserString('header').'</th>'.
 4391: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4392: 	'<th>'.&nameUserString('header').'</th>'.
 4393: 	&Apache::loncommon::end_data_table_header_row();
 4394:  
 4395:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4396:     my $ptr = 1;
 4397:     foreach my $student (sort 
 4398: 			 {
 4399: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4400: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4401: 			     }
 4402: 			     return $a cmp $b;
 4403: 			 } (keys(%$fullname))) {
 4404: 	my ($uname,$udom) = split(/:/,$student);
 4405: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4406:                                   : '</td>');
 4407: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4408: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4409: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4410: 	$studentTable.=
 4411: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4412:                          : '');
 4413: 	$ptr++;
 4414:     }
 4415:     if ($ptr%2 == 0) {
 4416: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4417: 	    &Apache::loncommon::end_data_table_row();
 4418:     }
 4419:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4420:     $studentTable.='<input type="button" '.
 4421:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4422: 
 4423:     $studentTable.=&show_grading_menu_form($symb);
 4424:     $request->print($studentTable);
 4425: 
 4426:     return '';
 4427: }
 4428: 
 4429: sub getSymbMap {
 4430:     my ($map_error) = @_;
 4431:     my $navmap = Apache::lonnavmaps::navmap->new();
 4432:     unless (ref($navmap)) {
 4433:         if (ref($map_error)) {
 4434:             $$map_error = 'navmap';
 4435:         }
 4436:         return;
 4437:     }
 4438:     my %symbx = ();
 4439:     my @titles = ();
 4440:     my $minder = 0;
 4441: 
 4442:     # Gather every sequence that has problems.
 4443:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4444: 					       1,0,1);
 4445:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4446: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4447: 	    my $title = $minder.'.'.
 4448: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4449: 	    push(@titles, $title); # minder in case two titles are identical
 4450: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4451: 	    $minder++;
 4452: 	}
 4453:     }
 4454:     return \@titles,\%symbx;
 4455: }
 4456: 
 4457: #
 4458: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4459: sub displayPage {
 4460:     my ($request) = shift;
 4461: 
 4462:     my ($symb) = &get_symb($request);
 4463:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4464:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4465:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4466:     my $pageTitle = $env{'form.page'};
 4467:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4468:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4469:     my $usec=$classlist->{$env{'form.student'}}[5];
 4470: 
 4471:     #need to make sure we have the correct data for later EXT calls, 
 4472:     #thus invalidate the cache
 4473:     &Apache::lonnet::devalidatecourseresdata(
 4474:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4475:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4476:     &Apache::lonnet::clear_EXT_cache_status();
 4477: 
 4478:     if (!&canview($usec)) {
 4479: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4480: 	$request->print(&show_grading_menu_form($symb));
 4481: 	return;
 4482:     }
 4483:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4484:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4485: 	'</h3>'."\n";
 4486:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4487:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4488: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4489:     } else {
 4490: 	delete($env{'form.CODE'});
 4491:     }
 4492:     &sub_page_js($request);
 4493:     $request->print($result);
 4494: 
 4495:     my $navmap = Apache::lonnavmaps::navmap->new();
 4496:     unless (ref($navmap)) {
 4497:         $request->print(&navmap_errormsg());
 4498:         $request->print(&show_grading_menu_form($symb));
 4499:         return;
 4500:     }
 4501:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4502:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4503:     if (!$map) {
 4504: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4505: 	$request->print(&show_grading_menu_form($symb));
 4506: 	return; 
 4507:     }
 4508:     my $iterator = $navmap->getIterator($map->map_start(),
 4509: 					$map->map_finish());
 4510: 
 4511:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4512: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4513: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4514: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4515: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4516: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4517: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4518: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4519: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4520: 
 4521:     if (defined($env{'form.CODE'})) {
 4522: 	$studentTable.=
 4523: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4524:     }
 4525:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4526: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4527: 
 4528:     $studentTable.='&nbsp;<span class="LC_info">'.
 4529:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
 4530:         '</span>'."\n".
 4531: 	&Apache::loncommon::start_data_table().
 4532: 	&Apache::loncommon::start_data_table_header_row().
 4533: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4534: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4535: 	&Apache::loncommon::end_data_table_header_row();
 4536: 
 4537:     &Apache::lonxml::clear_problem_counter();
 4538:     my ($depth,$question,$prob) = (1,1,1);
 4539:     $iterator->next(); # skip the first BEGIN_MAP
 4540:     my $curRes = $iterator->next(); # for "current resource"
 4541:     while ($depth > 0) {
 4542:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4543:         if($curRes == $iterator->END_MAP) { $depth--; }
 4544: 
 4545:         if (ref($curRes) && $curRes->is_problem()) {
 4546: 	    my $parts = $curRes->parts();
 4547:             my $title = $curRes->compTitle();
 4548: 	    my $symbx = $curRes->symb();
 4549: 	    $studentTable.=
 4550: 		&Apache::loncommon::start_data_table_row().
 4551: 		'<td align="center" valign="top" >'.$prob.
 4552: 		(scalar(@{$parts}) == 1 ? '' 
 4553: 		                        : '<br />('.&mt('[_1]parts)',
 4554: 							scalar(@{$parts}).'&nbsp;')
 4555: 		 ).
 4556: 		 '</td>';
 4557: 	    $studentTable.='<td valign="top">';
 4558: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4559: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4560: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4561: 					     undef,'both',\%form);
 4562: 	    } else {
 4563: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4564: 		$companswer =~ s|<form(.*?)>||g;
 4565: 		$companswer =~ s|</form>||g;
 4566: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4567: #		    $companswer =~ s/$1/ /ms;
 4568: #		    $request->print('match='.$1."<br />\n");
 4569: #		}
 4570: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4571: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4572: 	    }
 4573: 
 4574: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4575: 
 4576: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4577: 		if ($record{'version'} eq '') {
 4578: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4579: 		} else {
 4580: 		    my %responseType = ();
 4581: 		    foreach my $partid (@{$parts}) {
 4582: 			my @responseIds =$curRes->responseIds($partid);
 4583: 			my @responseType =$curRes->responseType($partid);
 4584: 			my %responseIds;
 4585: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4586: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4587: 			}
 4588: 			$responseType{$partid} = \%responseIds;
 4589: 		    }
 4590: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4591: 
 4592: 		}
 4593: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4594: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4595: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4596: 									$env{'request.course.id'},
 4597: 									'','.submission');
 4598:  
 4599: 	    }
 4600: 	    if (&canmodify($usec)) {
 4601:             $studentTable.=&gradeBox_start();
 4602: 		foreach my $partid (@{$parts}) {
 4603: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4604: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4605: 		    $question++;
 4606: 		}
 4607:             $studentTable.=&gradeBox_end();
 4608: 		$prob++;
 4609: 	    }
 4610: 	    $studentTable.='</td></tr>';
 4611: 
 4612: 	}
 4613:         $curRes = $iterator->next();
 4614:     }
 4615: 
 4616:     $studentTable.=
 4617:         '</table>'."\n".
 4618:         '<input type="button" value="'.&mt('Save').'" '.
 4619:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4620:         '</form>'."\n";
 4621:     $studentTable.=&show_grading_menu_form($symb);
 4622:     $request->print($studentTable);
 4623: 
 4624:     return '';
 4625: }
 4626: 
 4627: sub displaySubByDates {
 4628:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4629:     my $isCODE=0;
 4630:     my $isTask = ($symb =~/\.task$/);
 4631:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4632:     my $studentTable=&Apache::loncommon::start_data_table().
 4633: 	&Apache::loncommon::start_data_table_header_row().
 4634: 	'<th>'.&mt('Date/Time').'</th>'.
 4635: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4636: 	'<th>'.&mt('Submission').'</th>'.
 4637: 	'<th>'.&mt('Status').'</th>'.
 4638: 	&Apache::loncommon::end_data_table_header_row();
 4639:     my ($version);
 4640:     my %mark;
 4641:     my %orders;
 4642:     $mark{'correct_by_student'} = $checkIcon;
 4643:     if (!exists($$record{'1:timestamp'})) {
 4644: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4645:     }
 4646: 
 4647:     my $interaction;
 4648:     my $no_increment = 1;
 4649:     my %lastrndseed;
 4650:     for ($version=1;$version<=$$record{'version'};$version++) {
 4651: 	my $timestamp = 
 4652: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4653: 	if (exists($$record{$version.':resource.0.version'})) {
 4654: 	    $interaction = $$record{$version.':resource.0.version'};
 4655: 	}
 4656: 
 4657: 	my $where = ($isTask ? "$version:resource.$interaction"
 4658: 		             : "$version:resource");
 4659: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4660: 	    '<td>'.$timestamp.'</td>';
 4661: 	if ($isCODE) {
 4662: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4663: 	}
 4664: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4665: 	my @displaySub = ();
 4666: 	foreach my $partid (@{$parts}) {
 4667:             my ($hidden,$type);
 4668:             $type = $$record{$version.':resource.'.$partid.'.type'};
 4669:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
 4670:                 $hidden = 1;
 4671:             }
 4672: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4673: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4674: 	    
 4675: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4676: 	    my $display_part=&get_display_part($partid,$symb);
 4677: 	    foreach my $matchKey (@matchKey) {
 4678: 		if (exists($$record{$version.':'.$matchKey}) &&
 4679: 		    $$record{$version.':'.$matchKey} ne '') {
 4680:                     
 4681: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4682: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4683:                     $displaySub[0].='<span class="LC_nobreak"';
 4684:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4685:                                    .' <span class="LC_internal_info">'
 4686:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4687:                                    .'</span>'
 4688:                                    .' <b>';
 4689:                     if ($hidden) {
 4690:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
 4691:                     } else {
 4692:                         my ($trial,$rndseed,$newvariation);
 4693:                         if ($type eq 'randomizetry') {
 4694:                             $trial = $$record{"$where.$partid.tries"};
 4695:                             $rndseed = $$record{"$where.$partid.rndseed"};
 4696:                         }
 4697: 		        if ($$record{"$where.$partid.tries"} eq '') {
 4698: 			    $displaySub[0].=&mt('Trial not counted');
 4699: 		        } else {
 4700: 			    $displaySub[0].=&mt('Trial: [_1]',
 4701: 					    $$record{"$where.$partid.tries"});
 4702:                             if ($rndseed || $lastrndseed{$partid}) {
 4703:                                 if ($rndseed ne $lastrndseed{$partid}) {
 4704:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
 4705:                                 }
 4706:                             }
 4707: 		        }
 4708: 		        my $responseType=($isTask ? 'Task'
 4709:                                               : $responseType->{$partid}->{$responseId});
 4710: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4711: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
 4712: 			    $orders{$partid}->{$responseId}=
 4713: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
 4714:                                            $no_increment,$type,$trial,$rndseed);
 4715: 		        }
 4716: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
 4717: 		        $displaySub[0].='&nbsp; '.
 4718: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
 4719:                     }
 4720: 		}
 4721: 	    }
 4722: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4723: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4724: 				    $$record{"$where.$partid.checkedin"},
 4725: 				    $$record{"$where.$partid.checkedin.slot"}).
 4726: 					'<br />';
 4727: 	    }
 4728: 	    if (exists $$record{"$where.$partid.award"}) {
 4729: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4730: 		    lc($$record{"$where.$partid.award"}).' '.
 4731: 		    $mark{$$record{"$where.$partid.solved"}}.
 4732: 		    '<br />';
 4733: 	    }
 4734: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4735: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4736: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4737: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4738: 		$displaySub[2].=
 4739: 		    $$record{"$version:resource.$partid.regrader"}.
 4740: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4741: 	    }
 4742: 	}
 4743: 	# needed because old essay regrader has not parts info
 4744: 	if (exists $$record{"$version:resource.regrader"}) {
 4745: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4746: 	}
 4747: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4748: 	if ($displaySub[2]) {
 4749: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4750: 	}
 4751: 	$studentTable.='&nbsp;</td>'.
 4752: 	    &Apache::loncommon::end_data_table_row();
 4753:     }
 4754:     $studentTable.=&Apache::loncommon::end_data_table();
 4755:     return $studentTable;
 4756: }
 4757: 
 4758: sub updateGradeByPage {
 4759:     my ($request) = shift;
 4760: 
 4761:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4762:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4763:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4764:     my $pageTitle = $env{'form.page'};
 4765:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4766:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4767:     my $usec=$classlist->{$env{'form.student'}}[5];
 4768:     if (!&canmodify($usec)) {
 4769: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4770: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4771: 	return;
 4772:     }
 4773:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4774:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4775: 	'</h3>'."\n";
 4776: 
 4777:     $request->print($result);
 4778: 
 4779: 
 4780:     my $navmap = Apache::lonnavmaps::navmap->new();
 4781:     unless (ref($navmap)) {
 4782:         $request->print(&navmap_errormsg());
 4783:         return;
 4784:     }
 4785:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4786:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4787:     if (!$map) {
 4788: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4789: 	my ($symb)=&get_symb($request);
 4790: 	$request->print(&show_grading_menu_form($symb));
 4791: 	return; 
 4792:     }
 4793:     my $iterator = $navmap->getIterator($map->map_start(),
 4794: 					$map->map_finish());
 4795: 
 4796:     my $studentTable=
 4797: 	&Apache::loncommon::start_data_table().
 4798: 	&Apache::loncommon::start_data_table_header_row().
 4799: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4800: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4801: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4802: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4803: 	&Apache::loncommon::end_data_table_header_row();
 4804: 
 4805:     $iterator->next(); # skip the first BEGIN_MAP
 4806:     my $curRes = $iterator->next(); # for "current resource"
 4807:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4808:     while ($depth > 0) {
 4809:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4810:         if($curRes == $iterator->END_MAP) { $depth--; }
 4811: 
 4812:         if (ref($curRes) && $curRes->is_problem()) {
 4813: 	    my $parts = $curRes->parts();
 4814:             my $title = $curRes->compTitle();
 4815: 	    my $symbx = $curRes->symb();
 4816: 	    $studentTable.=
 4817: 		&Apache::loncommon::start_data_table_row().
 4818: 		'<td align="center" valign="top" >'.$prob.
 4819: 		(scalar(@{$parts}) == 1 ? '' 
 4820:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
 4821: 		.')').'</td>';
 4822: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4823: 
 4824: 	    my %newrecord=();
 4825: 	    my @displayPts=();
 4826:             my %aggregate = ();
 4827:             my $aggregateflag = 0;
 4828: 	    foreach my $partid (@{$parts}) {
 4829: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4830: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4831: 
 4832: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4833: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4834: 		my $partial = $newpts/$wgt;
 4835: 		my $score;
 4836: 		if ($partial > 0) {
 4837: 		    $score = 'correct_by_override';
 4838: 		} elsif ($newpts ne '') { #empty is taken as 0
 4839: 		    $score = 'incorrect_by_override';
 4840: 		}
 4841: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4842: 		if ($dropMenu eq 'excused') {
 4843: 		    $partial = '';
 4844: 		    $score = 'excused';
 4845: 		} elsif ($dropMenu eq 'reset status'
 4846: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4847: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4848: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4849: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4850: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4851: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4852: 		    $changeflag++;
 4853: 		    $newpts = '';
 4854:                     
 4855:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4856:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4857:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4858:                     if ($aggtries > 0) {
 4859:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4860:                         $aggregateflag = 1;
 4861:                     }
 4862: 		}
 4863: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4864: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4865: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4866: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4867: 		    '&nbsp;<br />';
 4868: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4869: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4870: 		    '&nbsp;<br />';
 4871: 		$question++;
 4872: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4873: 
 4874: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4875: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4876: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4877: 		    if (scalar(keys(%newrecord)) > 0);
 4878: 
 4879: 		$changeflag++;
 4880: 	    }
 4881: 	    if (scalar(keys(%newrecord)) > 0) {
 4882: 		my %record = 
 4883: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4884: 					     $udom,$uname);
 4885: 
 4886: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4887: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4888: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4889: 		    $newrecord{'resource.CODE'} = '';
 4890: 		}
 4891: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4892: 					$udom,$uname);
 4893: 		%record = &Apache::lonnet::restore($symbx,
 4894: 						   $env{'request.course.id'},
 4895: 						   $udom,$uname);
 4896: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4897: 					     $cdom,$cnum,$udom,$uname);
 4898: 	    }
 4899: 	    
 4900:             if ($aggregateflag) {
 4901:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4902:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4903:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4904:             }
 4905: 
 4906: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4907: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4908: 		&Apache::loncommon::end_data_table_row();
 4909: 
 4910: 	    $prob++;
 4911: 	}
 4912:         $curRes = $iterator->next();
 4913:     }
 4914: 
 4915:     $studentTable.=&Apache::loncommon::end_data_table();
 4916:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4917:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4918: 		  &mt('The scores were changed for [quant,_1,problem].',
 4919: 		  $changeflag));
 4920:     $request->print($grademsg.$studentTable);
 4921: 
 4922:     return '';
 4923: }
 4924: 
 4925: #-------- end of section for handling grading by page/sequence ---------
 4926: #
 4927: #-------------------------------------------------------------------
 4928: 
 4929: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4930: #
 4931: #------ start of section for handling grading by page/sequence ---------
 4932: 
 4933: =pod
 4934: 
 4935: =head1 Bubble sheet grading routines
 4936: 
 4937:   For this documentation:
 4938: 
 4939:    'scanline' refers to the full line of characters
 4940:    from the file that we are parsing that represents one entire sheet
 4941: 
 4942:    'bubble line' refers to the data
 4943:    representing the line of bubbles that are on the physical bubble sheet
 4944: 
 4945: 
 4946: The overall process is that a scanned in bubble sheet data is uploaded
 4947: into a course. When a user wants to grade, they select a
 4948: sequence/folder of resources, a file of bubble sheet info, and pick
 4949: one of the predefined configurations for what each scanline looks
 4950: like.
 4951: 
 4952: Next each scanline is checked for any errors of either 'missing
 4953: bubbles' (it's an error because it may have been mis-scanned
 4954: because too light bubbling), 'double bubble' (each bubble line should
 4955: have no more that one letter picked), invalid or duplicated CODE,
 4956: invalid student/employee ID
 4957: 
 4958: If the CODE option is used that determines the randomization of the
 4959: homework problems, either way the student/employee ID is looked up into a
 4960: username:domain.
 4961: 
 4962: During the validation phase the instructor can choose to skip scanlines. 
 4963: 
 4964: After the validation phase, there are now 3 bubble sheet files
 4965: 
 4966:   scantron_original_filename (unmodified original file)
 4967:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4968:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4969: 
 4970: Also there is a separate hash nohist_scantrondata that contains extra
 4971: correction information that isn't representable in the bubble sheet
 4972: file (see &scantron_getfile() for more information)
 4973: 
 4974: After all scanlines are either valid, marked as valid or skipped, then
 4975: foreach line foreach problem in the picked sequence, an ssi request is
 4976: made that simulates a user submitting their selected letter(s) against
 4977: the homework problem.
 4978: 
 4979: =over 4
 4980: 
 4981: 
 4982: 
 4983: =item defaultFormData
 4984: 
 4985:   Returns html hidden inputs used to hold context/default values.
 4986: 
 4987:  Arguments:
 4988:   $symb - $symb of the current resource 
 4989: 
 4990: =cut
 4991: 
 4992: sub defaultFormData {
 4993:     my ($symb)=@_;
 4994:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4995:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4996:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4997: }
 4998: 
 4999: 
 5000: =pod 
 5001: 
 5002: =item getSequenceDropDown
 5003: 
 5004:    Return html dropdown of possible sequences to grade
 5005:  
 5006:  Arguments:
 5007:    $symb - $symb of the current resource
 5008:    $map_error - ref to scalar which will container error if
 5009:                 $navmap object is unavailable in &getSymbMap().
 5010: 
 5011: =cut
 5012: 
 5013: sub getSequenceDropDown {
 5014:     my ($symb,$map_error)=@_;
 5015:     my $result='<select name="selectpage">'."\n";
 5016:     my ($titles,$symbx) = &getSymbMap($map_error);
 5017:     if (ref($map_error)) {
 5018:         return if ($$map_error);
 5019:     }
 5020:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 5021:     my $ctr=0;
 5022:     foreach (@$titles) {
 5023: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 5024: 	$result.='<option value="'.$$symbx{$_}.'" '.
 5025: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 5026: 	    '>'.$showtitle.'</option>'."\n";
 5027: 	$ctr++;
 5028:     }
 5029:     $result.= '</select>';
 5030:     return $result;
 5031: }
 5032: 
 5033: my %bubble_lines_per_response;     # no. bubble lines for each response.
 5034:                                    # key is zero-based index - 0, 1, 2 ...
 5035: 
 5036: my %first_bubble_line;             # First bubble line no. for each bubble.
 5037: 
 5038: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 5039:                                    # matchresponse or rankresponse, where 
 5040:                                    # an individual response can have multiple 
 5041:                                    # lines
 5042: 
 5043: my %responsetype_per_response;     # responsetype for each response
 5044: 
 5045: # Save and restore the bubble lines array to the form env.
 5046: 
 5047: 
 5048: sub save_bubble_lines {
 5049:     foreach my $line (keys(%bubble_lines_per_response)) {
 5050: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 5051: 	$env{"form.scantron.first_bubble_line.$line"} =
 5052: 	    $first_bubble_line{$line};
 5053:         $env{"form.scantron.sub_bubblelines.$line"} = 
 5054:             $subdivided_bubble_lines{$line};
 5055:         $env{"form.scantron.responsetype.$line"} =
 5056:             $responsetype_per_response{$line};
 5057:     }
 5058: }
 5059: 
 5060: 
 5061: sub restore_bubble_lines {
 5062:     my $line = 0;
 5063:     %bubble_lines_per_response = ();
 5064:     while ($env{"form.scantron.bubblelines.$line"}) {
 5065: 	my $value = $env{"form.scantron.bubblelines.$line"};
 5066: 	$bubble_lines_per_response{$line} = $value;
 5067: 	$first_bubble_line{$line}  =
 5068: 	    $env{"form.scantron.first_bubble_line.$line"};
 5069:         $subdivided_bubble_lines{$line} =
 5070:             $env{"form.scantron.sub_bubblelines.$line"};
 5071:         $responsetype_per_response{$line} =
 5072:             $env{"form.scantron.responsetype.$line"};
 5073: 	$line++;
 5074:     }
 5075: }
 5076: 
 5077: #  Given the parsed scanline, get the response for 
 5078: #  'answer' number n:
 5079: 
 5080: sub get_response_bubbles {
 5081:     my ($parsed_line, $response)  = @_;
 5082: 
 5083:     my $bubble_line = $first_bubble_line{$response-1} +1;
 5084:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 5085:     
 5086:     my $selected = "";
 5087: 
 5088:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 5089: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 5090: 	$bubble_line++;
 5091:     }
 5092:     return $selected;
 5093: }
 5094: 
 5095: =pod 
 5096: 
 5097: =item scantron_filenames
 5098: 
 5099:    Returns a list of the scantron files in the current course 
 5100: 
 5101: =cut
 5102: 
 5103: sub scantron_filenames {
 5104:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5105:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5106:     my $getpropath = 1;
 5107:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 5108:                                        $getpropath);
 5109:     my @possiblenames;
 5110:     foreach my $filename (sort(@files)) {
 5111: 	($filename)=split(/&/,$filename);
 5112: 	if ($filename!~/^scantron_orig_/) { next ; }
 5113: 	$filename=~s/^scantron_orig_//;
 5114: 	push(@possiblenames,$filename);
 5115:     }
 5116:     return @possiblenames;
 5117: }
 5118: 
 5119: =pod 
 5120: 
 5121: =item scantron_uploads
 5122: 
 5123:    Returns  html drop-down list of scantron files in current course.
 5124: 
 5125:  Arguments:
 5126:    $file2grade - filename to set as selected in the dropdown
 5127: 
 5128: =cut
 5129: 
 5130: sub scantron_uploads {
 5131:     my ($file2grade) = @_;
 5132:     my $result=	'<select name="scantron_selectfile">';
 5133:     $result.="<option></option>";
 5134:     foreach my $filename (sort(&scantron_filenames())) {
 5135: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5136:     }
 5137:     $result.="</select>";
 5138:     return $result;
 5139: }
 5140: 
 5141: =pod 
 5142: 
 5143: =item scantron_scantab
 5144: 
 5145:   Returns html drop down of the scantron formats in the scantronformat.tab
 5146:   file.
 5147: 
 5148: =cut
 5149: 
 5150: sub scantron_scantab {
 5151:     my $result='<select name="scantron_format">'."\n";
 5152:     $result.='<option></option>'."\n";
 5153:     my @lines = &get_scantronformat_file();
 5154:     if (@lines > 0) {
 5155:         foreach my $line (@lines) {
 5156:             next if (($line =~ /^\#/) || ($line eq ''));
 5157: 	    my ($name,$descrip)=split(/:/,$line);
 5158: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5159:         }
 5160:     }
 5161:     $result.='</select>'."\n";
 5162:     return $result;
 5163: }
 5164: 
 5165: =pod
 5166: 
 5167: =item get_scantronformat_file
 5168: 
 5169:   Returns an array containing lines from the scantron format file for
 5170:   the domain of the course.
 5171: 
 5172:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5173:   lines are from this file.
 5174: 
 5175:   Otherwise, if a default.tab has been published in RES space by the 
 5176:   domainconfig user, lines are from this file.
 5177: 
 5178:   Otherwise, fall back to getting lines from the legacy file on the
 5179:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5180: 
 5181: =cut
 5182: 
 5183: sub get_scantronformat_file {
 5184:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5185:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5186:     my $gottab = 0;
 5187:     my @lines;
 5188:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5189:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5190:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5191:             if ($formatfile ne '-1') {
 5192:                 @lines = split("\n",$formatfile,-1);
 5193:                 $gottab = 1;
 5194:             }
 5195:         }
 5196:     }
 5197:     if (!$gottab) {
 5198:         my $confname = $cdom.'-domainconfig';
 5199:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5200:         my $formatfile =  &Apache::lonnet::getfile($default);
 5201:         if ($formatfile ne '-1') {
 5202:             @lines = split("\n",$formatfile,-1);
 5203:             $gottab = 1;
 5204:         }
 5205:     }
 5206:     if (!$gottab) {
 5207:         my @domains = &Apache::lonnet::current_machine_domains();
 5208:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5209:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5210:             @lines = <$fh>;
 5211:             close($fh);
 5212:         } else {
 5213:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5214:             @lines = <$fh>;
 5215:             close($fh);
 5216:         }
 5217:     }
 5218:     return @lines;
 5219: }
 5220: 
 5221: =pod 
 5222: 
 5223: =item scantron_CODElist
 5224: 
 5225:   Returns html drop down of the saved CODE lists from current course,
 5226:   generated from earlier printings.
 5227: 
 5228: =cut
 5229: 
 5230: sub scantron_CODElist {
 5231:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5232:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5233:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5234:     my $namechoice='<option></option>';
 5235:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5236: 	if ($name =~ /^error: 2 /) { next; }
 5237: 	if ($name =~ /^type\0/) { next; }
 5238: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5239:     }
 5240:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5241:     return $namechoice;
 5242: }
 5243: 
 5244: =pod 
 5245: 
 5246: =item scantron_CODEunique
 5247: 
 5248:   Returns the html for "Each CODE to be used once" radio.
 5249: 
 5250: =cut
 5251: 
 5252: sub scantron_CODEunique {
 5253:     my $result='<span class="LC_nobreak">
 5254:                  <label><input type="radio" name="scantron_CODEunique"
 5255:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5256:                 </span>
 5257:                 <span class="LC_nobreak">
 5258:                  <label><input type="radio" name="scantron_CODEunique"
 5259:                         value="no" />'.&mt('No').' </label>
 5260:                 </span>';
 5261:     return $result;
 5262: }
 5263: 
 5264: =pod 
 5265: 
 5266: =item scantron_selectphase
 5267: 
 5268:   Generates the initial screen to start the bubble sheet process.
 5269:   Allows for - starting a grading run.
 5270:              - downloading existing scan data (original, corrected
 5271:                                                 or skipped info)
 5272: 
 5273:              - uploading new scan data
 5274: 
 5275:  Arguments:
 5276:   $r          - The Apache request object
 5277:   $file2grade - name of the file that contain the scanned data to score
 5278: 
 5279: =cut
 5280: 
 5281: sub scantron_selectphase {
 5282:     my ($r,$file2grade) = @_;
 5283:     my ($symb)=&get_symb($r);
 5284:     if (!$symb) {return '';}
 5285:     my $map_error;
 5286:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5287:     if ($map_error) {
 5288:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5289:         return;
 5290:     }
 5291:     my $default_form_data=&defaultFormData($symb);
 5292:     my $grading_menu_button=&show_grading_menu_form($symb);
 5293:     my $file_selector=&scantron_uploads($file2grade);
 5294:     my $format_selector=&scantron_scantab();
 5295:     my $CODE_selector=&scantron_CODElist();
 5296:     my $CODE_unique=&scantron_CODEunique();
 5297:     my $result;
 5298: 
 5299:     $ssi_error = 0;
 5300: 
 5301:     # Chunk of form to prompt for a file to grade and how:
 5302: 
 5303:     $result.= '
 5304:     <br />
 5305:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5306:     <input type="hidden" name="command" value="scantron_warning" />
 5307:     '.$default_form_data.'
 5308:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5309:        '.&Apache::loncommon::start_data_table_header_row().'
 5310:             <th colspan="2">
 5311:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5312:             </th>
 5313:        '.&Apache::loncommon::end_data_table_header_row().'
 5314:        '.&Apache::loncommon::start_data_table_row().'
 5315:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5316:        '.&Apache::loncommon::end_data_table_row().'
 5317:        '.&Apache::loncommon::start_data_table_row().'
 5318:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5319:        '.&Apache::loncommon::end_data_table_row().'
 5320:        '.&Apache::loncommon::start_data_table_row().'
 5321:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5322:        '.&Apache::loncommon::end_data_table_row().'
 5323:        '.&Apache::loncommon::start_data_table_row().'
 5324:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5325:        '.&Apache::loncommon::end_data_table_row().'
 5326:        '.&Apache::loncommon::start_data_table_row().'
 5327:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5328:        '.&Apache::loncommon::end_data_table_row().'
 5329:        '.&Apache::loncommon::start_data_table_row().'
 5330: 	    <td> '.&mt('Options:').' </td>
 5331:             <td>
 5332: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5333:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5334:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5335: 	    </td>
 5336:        '.&Apache::loncommon::end_data_table_row().'
 5337:        '.&Apache::loncommon::start_data_table_row().'
 5338:             <td colspan="2">
 5339:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5340:             </td>
 5341:        '.&Apache::loncommon::end_data_table_row().'
 5342:     '.&Apache::loncommon::end_data_table().'
 5343:     </form>
 5344: ';
 5345:    
 5346:     $r->print($result);
 5347: 
 5348:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5349:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5350: 
 5351: 	# Chunk of form to prompt for a scantron file upload.
 5352: 
 5353:         $r->print('
 5354:     <br />
 5355:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5356:        '.&Apache::loncommon::start_data_table_header_row().'
 5357:             <th>
 5358:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5359:             </th>
 5360:        '.&Apache::loncommon::end_data_table_header_row().'
 5361:        '.&Apache::loncommon::start_data_table_row().'
 5362:             <td>
 5363: ');
 5364:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5365:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5366:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5367:     $r->print('
 5368:               <script type="text/javascript" language="javascript">
 5369:     function checkUpload(formname) {
 5370: 	if (formname.upfile.value == "") {
 5371: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5372: 	    return false;
 5373: 	}
 5374: 	formname.submit();
 5375:     }
 5376:               </script>
 5377: 
 5378:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5379:                 '.$default_form_data.'
 5380:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5381:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5382:                 <input name="command" value="scantronupload_save" type="hidden" />
 5383:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5384:                 <br />
 5385:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5386:               </form>
 5387: ');
 5388: 
 5389:         $r->print('
 5390:             </td>
 5391:        '.&Apache::loncommon::end_data_table_row().'
 5392:        '.&Apache::loncommon::end_data_table().'
 5393: ');
 5394:     }
 5395: 
 5396:     # Chunk of the form that prompts to view a scoring office file,
 5397:     # corrected file, skipped records in a file.
 5398: 
 5399:     $r->print('
 5400:    <br />
 5401:    <form action="/adm/grades" name="scantron_download">
 5402:      '.$default_form_data.'
 5403:      <input type="hidden" name="command" value="scantron_download" />
 5404:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5405:        '.&Apache::loncommon::start_data_table_header_row().'
 5406:               <th>
 5407:                 &nbsp;'.&mt('Download a scoring office file').'
 5408:               </th>
 5409:        '.&Apache::loncommon::end_data_table_header_row().'
 5410:        '.&Apache::loncommon::start_data_table_row().'
 5411:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5412:                 <br />
 5413:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5414:        '.&Apache::loncommon::end_data_table_row().'
 5415:      '.&Apache::loncommon::end_data_table().'
 5416:    </form>
 5417:    <br />
 5418: ');
 5419: 
 5420:     &Apache::lonpickcode::code_list($r,2);
 5421: 
 5422:     $r->print('<br /><form method="post" name="checkscantron">'.
 5423:              $default_form_data."\n".
 5424:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5425:              &Apache::loncommon::start_data_table_header_row()."\n".
 5426:              '<th colspan="2">
 5427:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5428:              '</th>'."\n".
 5429:               &Apache::loncommon::end_data_table_header_row()."\n".
 5430:               &Apache::loncommon::start_data_table_row()."\n".
 5431:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5432:               '<td> '.$sequence_selector.' </td>'.
 5433:               &Apache::loncommon::end_data_table_row()."\n".
 5434:               &Apache::loncommon::start_data_table_row()."\n".
 5435:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5436:               '<td> '.$file_selector.' </td>'."\n".
 5437:               &Apache::loncommon::end_data_table_row()."\n".
 5438:               &Apache::loncommon::start_data_table_row()."\n".
 5439:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5440:               '<td> '.$format_selector.' </td>'."\n".
 5441:               &Apache::loncommon::end_data_table_row()."\n".
 5442:               &Apache::loncommon::start_data_table_row()."\n".
 5443:               '<td> '.&mt('Options').' </td>'."\n".
 5444:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5445:               &Apache::loncommon::end_data_table_row()."\n".
 5446:               &Apache::loncommon::start_data_table_row()."\n".
 5447:               '<td colspan="2">'."\n".
 5448:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5449:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5450:               '</td>'."\n".
 5451:               &Apache::loncommon::end_data_table_row()."\n".
 5452:               &Apache::loncommon::end_data_table()."\n".
 5453:               '</form><br />');
 5454:     $r->print($grading_menu_button);
 5455:     return;
 5456: }
 5457: 
 5458: =pod
 5459: 
 5460: =item get_scantron_config
 5461: 
 5462:    Parse and return the scantron configuration line selected as a
 5463:    hash of configuration file fields.
 5464: 
 5465:  Arguments:
 5466:     which - the name of the configuration to parse from the file.
 5467: 
 5468: 
 5469:  Returns:
 5470:             If the named configuration is not in the file, an empty
 5471:             hash is returned.
 5472:     a hash with the fields
 5473:       name         - internal name for the this configuration setup
 5474:       description  - text to display to operator that describes this config
 5475:       CODElocation - if 0 or the string 'none'
 5476:                           - no CODE exists for this config
 5477:                      if -1 || the string 'letter'
 5478:                           - a CODE exists for this config and is
 5479:                             a string of letters
 5480:                      Unsupported value (but planned for future support)
 5481:                           if a positive integer
 5482:                                - The CODE exists as the first n items from
 5483:                                  the question section of the form
 5484:                           if the string 'number'
 5485:                                - The CODE exists for this config and is
 5486:                                  a string of numbers
 5487:       CODEstart   - (only matter if a CODE exists) column in the line where
 5488:                      the CODE starts
 5489:       CODElength  - length of the CODE
 5490:       IDstart     - column where the student/employee ID starts
 5491:       IDlength    - length of the student/employee ID info
 5492:       Qstart      - column where the information from the bubbled
 5493:                     'questions' start
 5494:       Qlength     - number of columns comprising a single bubble line from
 5495:                     the sheet. (usually either 1 or 10)
 5496:       Qon         - either a single character representing the character used
 5497:                     to signal a bubble was chosen in the positional setup, or
 5498:                     the string 'letter' if the letter of the chosen bubble is
 5499:                     in the final, or 'number' if a number representing the
 5500:                     chosen bubble is in the file (1->A 0->J)
 5501:       Qoff        - the character used to represent that a bubble was
 5502:                     left blank
 5503:       PaperID     - if the scanning process generates a unique number for each
 5504:                     sheet scanned the column that this ID number starts in
 5505:       PaperIDlength - number of columns that comprise the unique ID number
 5506:                       for the sheet of paper
 5507:       FirstName   - column that the first name starts in
 5508:       FirstNameLength - number of columns that the first name spans
 5509:  
 5510:       LastName    - column that the last name starts in
 5511:       LastNameLength - number of columns that the last name spans
 5512: 
 5513: =cut
 5514: 
 5515: sub get_scantron_config {
 5516:     my ($which) = @_;
 5517:     my @lines = &get_scantronformat_file();
 5518:     my %config;
 5519:     #FIXME probably should move to XML it has already gotten a bit much now
 5520:     foreach my $line (@lines) {
 5521: 	my ($name,$descrip)=split(/:/,$line);
 5522: 	if ($name ne $which ) { next; }
 5523: 	chomp($line);
 5524: 	my @config=split(/:/,$line);
 5525: 	$config{'name'}=$config[0];
 5526: 	$config{'description'}=$config[1];
 5527: 	$config{'CODElocation'}=$config[2];
 5528: 	$config{'CODEstart'}=$config[3];
 5529: 	$config{'CODElength'}=$config[4];
 5530: 	$config{'IDstart'}=$config[5];
 5531: 	$config{'IDlength'}=$config[6];
 5532: 	$config{'Qstart'}=$config[7];
 5533:  	$config{'Qlength'}=$config[8];
 5534: 	$config{'Qoff'}=$config[9];
 5535: 	$config{'Qon'}=$config[10];
 5536: 	$config{'PaperID'}=$config[11];
 5537: 	$config{'PaperIDlength'}=$config[12];
 5538: 	$config{'FirstName'}=$config[13];
 5539: 	$config{'FirstNamelength'}=$config[14];
 5540: 	$config{'LastName'}=$config[15];
 5541: 	$config{'LastNamelength'}=$config[16];
 5542: 	last;
 5543:     }
 5544:     return %config;
 5545: }
 5546: 
 5547: =pod 
 5548: 
 5549: =item username_to_idmap
 5550: 
 5551:     creates a hash keyed by student/employee ID with values of the corresponding
 5552:     student username:domain.
 5553: 
 5554:   Arguments:
 5555: 
 5556:     $classlist - reference to the class list hash. This is a hash
 5557:                  keyed by student name:domain  whose elements are references
 5558:                  to arrays containing various chunks of information
 5559:                  about the student. (See loncoursedata for more info).
 5560: 
 5561:   Returns
 5562:     %idmap - the constructed hash
 5563: 
 5564: =cut
 5565: 
 5566: sub username_to_idmap {
 5567:     my ($classlist)= @_;
 5568:     my %idmap;
 5569:     foreach my $student (keys(%$classlist)) {
 5570: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5571: 	    $student;
 5572:     }
 5573:     return %idmap;
 5574: }
 5575: 
 5576: =pod
 5577: 
 5578: =item scantron_fixup_scanline
 5579: 
 5580:    Process a requested correction to a scanline.
 5581: 
 5582:   Arguments:
 5583:     $scantron_config   - hash from &get_scantron_config()
 5584:     $scan_data         - hash of correction information 
 5585:                           (see &scantron_getfile())
 5586:     $line              - existing scanline
 5587:     $whichline         - line number of the passed in scanline
 5588:     $field             - type of change to process 
 5589:                          (either 
 5590:                           'ID'     -> correct the student/employee ID
 5591:                           'CODE'   -> correct the CODE
 5592:                           'answer' -> fixup the submitted answers)
 5593:     
 5594:    $args               - hash of additional info,
 5595:                           - 'ID' 
 5596:                                'newid' -> studentID to use in replacement
 5597:                                           of existing one
 5598:                           - 'CODE' 
 5599:                                'CODE_ignore_dup' - set to true if duplicates
 5600:                                                    should be ignored.
 5601: 	                       'CODE' - is new code or 'use_unfound'
 5602:                                         if the existing unfound code should
 5603:                                         be used as is
 5604:                           - 'answer'
 5605:                                'response' - new answer or 'none' if blank
 5606:                                'question' - the bubble line to change
 5607:                                'questionnum' - the question identifier,
 5608:                                                may include subquestion. 
 5609: 
 5610:   Returns:
 5611:     $line - the modified scanline
 5612: 
 5613:   Side effects: 
 5614:     $scan_data - may be updated
 5615: 
 5616: =cut
 5617: 
 5618: 
 5619: sub scantron_fixup_scanline {
 5620:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5621:     if ($field eq 'ID') {
 5622: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5623: 	    return ($line,1,'New value too large');
 5624: 	}
 5625: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5626: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5627: 				     $args->{'newid'});
 5628: 	}
 5629: 	substr($line,$$scantron_config{'IDstart'}-1,
 5630: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5631: 	if ($args->{'newid'}=~/^\s*$/) {
 5632: 	    &scan_data($scan_data,"$whichline.user",
 5633: 		       $args->{'username'}.':'.$args->{'domain'});
 5634: 	}
 5635:     } elsif ($field eq 'CODE') {
 5636: 	if ($args->{'CODE_ignore_dup'}) {
 5637: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5638: 	}
 5639: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5640: 	if ($args->{'CODE'} ne 'use_unfound') {
 5641: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5642: 		return ($line,1,'New CODE value too large');
 5643: 	    }
 5644: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5645: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5646: 	    }
 5647: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5648: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5649: 	}
 5650:     } elsif ($field eq 'answer') {
 5651: 	my $length=$scantron_config->{'Qlength'};
 5652: 	my $off=$scantron_config->{'Qoff'};
 5653: 	my $on=$scantron_config->{'Qon'};
 5654: 	my $answer=${off}x$length;
 5655: 	if ($args->{'response'} eq 'none') {
 5656: 	    &scan_data($scan_data,
 5657: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5658: 	} else {
 5659: 	    if ($on eq 'letter') {
 5660: 		my @alphabet=('A'..'Z');
 5661: 		$answer=$alphabet[$args->{'response'}];
 5662: 	    } elsif ($on eq 'number') {
 5663: 		$answer=$args->{'response'}+1;
 5664: 		if ($answer == 10) { $answer = '0'; }
 5665: 	    } else {
 5666: 		substr($answer,$args->{'response'},1)=$on;
 5667: 	    }
 5668: 	    &scan_data($scan_data,
 5669: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5670: 	}
 5671: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5672: 	substr($line,$where-1,$length)=$answer;
 5673:     }
 5674:     return $line;
 5675: }
 5676: 
 5677: =pod
 5678: 
 5679: =item scan_data
 5680: 
 5681:     Edit or look up  an item in the scan_data hash.
 5682: 
 5683:   Arguments:
 5684:     $scan_data  - The hash (see scantron_getfile)
 5685:     $key        - shorthand of the key to edit (actual key is
 5686:                   scantronfilename_key).
 5687:     $data        - New value of the hash entry.
 5688:     $delete      - If true, the entry is removed from the hash.
 5689: 
 5690:   Returns:
 5691:     The new value of the hash table field (undefined if deleted).
 5692: 
 5693: =cut
 5694: 
 5695: 
 5696: sub scan_data {
 5697:     my ($scan_data,$key,$value,$delete)=@_;
 5698:     my $filename=$env{'form.scantron_selectfile'};
 5699:     if (defined($value)) {
 5700: 	$scan_data->{$filename.'_'.$key} = $value;
 5701:     }
 5702:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5703:     return $scan_data->{$filename.'_'.$key};
 5704: }
 5705: 
 5706: # ----- These first few routines are general use routines.----
 5707: 
 5708: # Return the number of occurences of a pattern in a string.
 5709: 
 5710: sub occurence_count {
 5711:     my ($string, $pattern) = @_;
 5712: 
 5713:     my @matches = ($string =~ /$pattern/g);
 5714: 
 5715:     return scalar(@matches);
 5716: }
 5717: 
 5718: 
 5719: # Take a string known to have digits and convert all the
 5720: # digits into letters in the range J,A..I.
 5721: 
 5722: sub digits_to_letters {
 5723:     my ($input) = @_;
 5724: 
 5725:     my @alphabet = ('J', 'A'..'I');
 5726: 
 5727:     my @input    = split(//, $input);
 5728:     my $output ='';
 5729:     for (my $i = 0; $i < scalar(@input); $i++) {
 5730: 	if ($input[$i] =~ /\d/) {
 5731: 	    $output .= $alphabet[$input[$i]];
 5732: 	} else {
 5733: 	    $output .= $input[$i];
 5734: 	}
 5735:     }
 5736:     return $output;
 5737: }
 5738: 
 5739: =pod 
 5740: 
 5741: =item scantron_parse_scanline
 5742: 
 5743:   Decodes a scanline from the selected scantron file
 5744: 
 5745:  Arguments:
 5746:     line             - The text of the scantron file line to process
 5747:     whichline        - Line number
 5748:     scantron_config  - Hash describing the format of the scantron lines.
 5749:     scan_data        - Hash of extra information about the scanline
 5750:                        (see scantron_getfile for more information)
 5751:     just_header      - True if should not process question answers but only
 5752:                        the stuff to the left of the answers.
 5753:  Returns:
 5754:    Hash containing the result of parsing the scanline
 5755: 
 5756:    Keys are all proceeded by the string 'scantron.'
 5757: 
 5758:        CODE    - the CODE in use for this scanline
 5759:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5760:                  by the operator
 5761:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5762:                             CODEs were selected, but the usage has been
 5763:                             forced by the operator
 5764:        ID  - student/employee ID
 5765:        PaperID - if used, the ID number printed on the sheet when the 
 5766:                  paper was scanned
 5767:        FirstName - first name from the sheet
 5768:        LastName  - last name from the sheet
 5769: 
 5770:      if just_header was not true these key may also exist
 5771: 
 5772:        missingerror - a list of bubble ranges that are considered to be answers
 5773:                       to a single question that don't have any bubbles filled in.
 5774:                       Of the form questionnumber:firstbubblenumber:count.
 5775:        doubleerror  - a list of bubble ranges that are considered to be answers
 5776:                       to a single question that have more than one bubble filled in.
 5777:                       Of the form questionnumber::firstbubblenumber:count
 5778:    
 5779:                 In the above, count is the number of bubble responses in the
 5780:                 input line needed to represent the possible answers to the question.
 5781:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5782:                 per line would have count = 2.
 5783: 
 5784:        maxquest     - the number of the last bubble line that was parsed
 5785: 
 5786:        (<number> starts at 1)
 5787:        <number>.answer - zero or more letters representing the selected
 5788:                          letters from the scanline for the bubble line 
 5789:                          <number>.
 5790:                          if blank there was either no bubble or there where
 5791:                          multiple bubbles, (consult the keys missingerror and
 5792:                          doubleerror if this is an error condition)
 5793: 
 5794: =cut
 5795: 
 5796: sub scantron_parse_scanline {
 5797:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5798: 
 5799:     my %record;
 5800:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5801:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5802:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5803:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5804: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5805: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5806: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5807: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5808: 	    $record{'scantron.CODE'}=substr($data,
 5809: 					    $$scantron_config{'CODEstart'}-1,
 5810: 					    $$scantron_config{'CODElength'});
 5811: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5812: 		$record{'scantron.useCODE'}=1;
 5813: 	    }
 5814: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5815: 		$record{'scantron.CODE_ignore_dup'}=1;
 5816: 	    }
 5817: 	} else {
 5818: 	    #FIXME interpret first N questions
 5819: 	}
 5820:     }
 5821:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5822: 				  $$scantron_config{'IDlength'});
 5823:     $record{'scantron.PaperID'}=
 5824: 	substr($data,$$scantron_config{'PaperID'}-1,
 5825: 	       $$scantron_config{'PaperIDlength'});
 5826:     $record{'scantron.FirstName'}=
 5827: 	substr($data,$$scantron_config{'FirstName'}-1,
 5828: 	       $$scantron_config{'FirstNamelength'});
 5829:     $record{'scantron.LastName'}=
 5830: 	substr($data,$$scantron_config{'LastName'}-1,
 5831: 	       $$scantron_config{'LastNamelength'});
 5832:     if ($just_header) { return \%record; }
 5833: 
 5834:     my @alphabet=('A'..'Z');
 5835:     my $questnum=0;
 5836:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5837: 
 5838:     chomp($questions);		# Get rid of any trailing \n.
 5839:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5840:     while (length($questions)) {
 5841: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5842:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5843:                              || 1;
 5844:         $questnum++;
 5845:         my $quest_id = $questnum;
 5846:         my $currentquest = substr($questions,0,$answer_length);
 5847:         $questions       = substr($questions,$answer_length);
 5848:         if (length($currentquest) < $answer_length) { next; }
 5849: 
 5850:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5851:             my $subquestnum = 1;
 5852:             my $subquestions = $currentquest;
 5853:             my @subanswers_needed = 
 5854:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5855:             foreach my $subans (@subanswers_needed) {
 5856:                 my $subans_length =
 5857:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5858:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5859:                 $subquestions   = substr($subquestions,$subans_length);
 5860:                 $quest_id = "$questnum.$subquestnum";
 5861:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5862:                     ($$scantron_config{'Qon'} eq 'number')) {
 5863:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5864:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5865:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5866:                 } else {
 5867:                     $ansnum = &scantron_validator_positional($ansnum,
 5868:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5869:                 }
 5870:                 $subquestnum ++;
 5871:             }
 5872:         } else {
 5873:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5874:                 ($$scantron_config{'Qon'} eq 'number')) {
 5875:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5876:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5877:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5878:             } else {
 5879:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5880:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5881:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5882:             }
 5883:         }
 5884:     }
 5885:     $record{'scantron.maxquest'}=$questnum;
 5886:     return \%record;
 5887: }
 5888: 
 5889: sub scantron_validator_lettnum {
 5890:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5891:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5892: 
 5893:     # Qon 'letter' implies for each slot in currquest we have:
 5894:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5895:     #    about anything else (esp. a value of Qoff) for missing
 5896:     #    bubbles.
 5897:     #
 5898:     # Qon 'number' implies each slot gives a digit that indexes the
 5899:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5900:     #    and * or ? for double bubbles on a single line.
 5901:     #
 5902: 
 5903:     my $matchon;
 5904:     if ($$scantron_config{'Qon'} eq 'letter') {
 5905:         $matchon = '[A-Z]';
 5906:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5907:         $matchon = '\d';
 5908:     }
 5909:     my $occurrences = 0;
 5910:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5911:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5912:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5913:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5914:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5915:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5916:         my @singlelines = split('',$currquest);
 5917:         foreach my $entry (@singlelines) {
 5918:             $occurrences = &occurence_count($entry,$matchon);
 5919:             if ($occurrences > 1) {
 5920:                 last;
 5921:             }
 5922:         } 
 5923:     } else {
 5924:         $occurrences = &occurence_count($currquest,$matchon); 
 5925:     }
 5926:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5927:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5928:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5929:             my $bubble = substr($currquest,$ans,1);
 5930:             if ($bubble =~ /$matchon/ ) {
 5931:                 if ($$scantron_config{'Qon'} eq 'number') {
 5932:                     if ($bubble == 0) {
 5933:                         $bubble = 10; 
 5934:                     }
 5935:                     $record->{"scantron.$ansnum.answer"} = 
 5936:                         $alphabet->[$bubble-1];
 5937:                 } else {
 5938:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5939:                 }
 5940:             } else {
 5941:                 $record->{"scantron.$ansnum.answer"}='';
 5942:             }
 5943:             $ansnum++;
 5944:         }
 5945:     } elsif (!defined($currquest)
 5946:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5947:             || (&occurence_count($currquest,$matchon) == 0)) {
 5948:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5949:             $record->{"scantron.$ansnum.answer"}='';
 5950:             $ansnum++;
 5951:         }
 5952:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5953:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5954:         }
 5955:     } else {
 5956:         if ($$scantron_config{'Qon'} eq 'number') {
 5957:             $currquest = &digits_to_letters($currquest);            
 5958:         }
 5959:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5960:             my $bubble = substr($currquest,$ans,1);
 5961:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5962:             $ansnum++;
 5963:         }
 5964:     }
 5965:     return $ansnum;
 5966: }
 5967: 
 5968: sub scantron_validator_positional {
 5969:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5970:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5971: 
 5972:     # Otherwise there's a positional notation;
 5973:     # each bubble line requires Qlength items, and there are filled in
 5974:     # bubbles for each case where there 'Qon' characters.
 5975:     #
 5976: 
 5977:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5978: 
 5979:     # If the split only gives us one element.. the full length of the
 5980:     # answer string, no bubbles are filled in:
 5981: 
 5982:     if ($answers_needed eq '') {
 5983:         return;
 5984:     }
 5985: 
 5986:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5987:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5988:             $record->{"scantron.$ansnum.answer"}='';
 5989:             $ansnum++;
 5990:         }
 5991:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5992:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5993:         }
 5994:     } elsif (scalar(@array) == 2) {
 5995:         my $location = length($array[0]);
 5996:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5997:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5998:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5999:             if ($ans eq $line_num) {
 6000:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 6001:             } else {
 6002:                 $record->{"scantron.$ansnum.answer"} = ' ';
 6003:             }
 6004:             $ansnum++;
 6005:          }
 6006:     } else {
 6007:         #  If there's more than one instance of a bubble character
 6008:         #  That's a double bubble; with positional notation we can
 6009:         #  record all the bubbles filled in as well as the
 6010:         #  fact this response consists of multiple bubbles.
 6011:         #
 6012:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 6013:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 6014:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 6015:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 6016:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 6017:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 6018:             my $doubleerror = 0;
 6019:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 6020:                    (!$doubleerror)) {
 6021:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 6022:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 6023:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 6024:                if (length(@currarray) > 2) {
 6025:                    $doubleerror = 1;
 6026:                } 
 6027:             }
 6028:             if ($doubleerror) {
 6029:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6030:             }
 6031:         } else {
 6032:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 6033:         }
 6034:         my $item = $ansnum;
 6035:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 6036:             $record->{"scantron.$item.answer"} = '';
 6037:             $item ++;
 6038:         }
 6039: 
 6040:         my @ans=@array;
 6041:         my $i=0;
 6042:         my $increment = 0;
 6043:         while ($#ans) {
 6044:             $i+=length($ans[0]) + $increment;
 6045:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 6046:             my $bubble = $i%$$scantron_config{'Qlength'};
 6047:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 6048:             shift(@ans);
 6049:             $increment = 1;
 6050:         }
 6051:         $ansnum += $answers_needed;
 6052:     }
 6053:     return $ansnum;
 6054: }
 6055: 
 6056: =pod
 6057: 
 6058: =item scantron_add_delay
 6059: 
 6060:    Adds an error message that occurred during the grading phase to a
 6061:    queue of messages to be shown after grading pass is complete
 6062: 
 6063:  Arguments:
 6064:    $delayqueue  - arrary ref of hash ref of error messages
 6065:    $scanline    - the scanline that caused the error
 6066:    $errormesage - the error message
 6067:    $errorcode   - a numeric code for the error
 6068: 
 6069:  Side Effects:
 6070:    updates the $delayqueue to have a new hash ref of the error
 6071: 
 6072: =cut
 6073: 
 6074: sub scantron_add_delay {
 6075:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 6076:     push(@$delayqueue,
 6077: 	 {'line' => $scanline, 'emsg' => $errormessage,
 6078: 	  'ecode' => $errorcode }
 6079: 	 );
 6080: }
 6081: 
 6082: =pod
 6083: 
 6084: =item scantron_find_student
 6085: 
 6086:    Finds the username for the current scanline
 6087: 
 6088:   Arguments:
 6089:    $scantron_record - hash result from scantron_parse_scanline
 6090:    $scan_data       - hash of correction information 
 6091:                       (see &scantron_getfile() form more information)
 6092:    $idmap           - hash from &username_to_idmap()
 6093:    $line            - number of current scanline
 6094:  
 6095:   Returns:
 6096:    Either 'username:domain' or undef if unknown
 6097: 
 6098: =cut
 6099: 
 6100: sub scantron_find_student {
 6101:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 6102:     my $scanID=$$scantron_record{'scantron.ID'};
 6103:     if ($scanID =~ /^\s*$/) {
 6104:  	return &scan_data($scan_data,"$line.user");
 6105:     }
 6106:     foreach my $id (keys(%$idmap)) {
 6107:  	if (lc($id) eq lc($scanID)) {
 6108:  	    return $$idmap{$id};
 6109:  	}
 6110:     }
 6111:     return undef;
 6112: }
 6113: 
 6114: =pod
 6115: 
 6116: =item scantron_filter
 6117: 
 6118:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6119:    hidden resources was selected
 6120: 
 6121: =cut
 6122: 
 6123: sub scantron_filter {
 6124:     my ($curres)=@_;
 6125: 
 6126:     if (ref($curres) && $curres->is_problem()) {
 6127: 	# if the user has asked to not have either hidden
 6128: 	# or 'randomout' controlled resources to be graded
 6129: 	# don't include them
 6130: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6131: 	    && $curres->randomout) {
 6132: 	    return 0;
 6133: 	}
 6134: 	return 1;
 6135:     }
 6136:     return 0;
 6137: }
 6138: 
 6139: =pod
 6140: 
 6141: =item scantron_process_corrections
 6142: 
 6143:    Gets correction information out of submitted form data and corrects
 6144:    the scanline
 6145: 
 6146: =cut
 6147: 
 6148: sub scantron_process_corrections {
 6149:     my ($r) = @_;
 6150:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6151:     my ($scanlines,$scan_data)=&scantron_getfile();
 6152:     my $classlist=&Apache::loncoursedata::get_classlist();
 6153:     my $which=$env{'form.scantron_line'};
 6154:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6155:     my ($skip,$err,$errmsg);
 6156:     if ($env{'form.scantron_skip_record'}) {
 6157: 	$skip=1;
 6158:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6159: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6160: 	    $env{'form.scantron_domain'};
 6161: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6162: 	($line,$err,$errmsg)=
 6163: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6164: 				     'ID',{'newid'=>$newid,
 6165: 				    'username'=>$env{'form.scantron_username'},
 6166: 				    'domain'=>$env{'form.scantron_domain'}});
 6167:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6168: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6169: 	my $newCODE;
 6170: 	my %args;
 6171: 	if      ($resolution eq 'use_unfound') {
 6172: 	    $newCODE='use_unfound';
 6173: 	} elsif ($resolution eq 'use_found') {
 6174: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6175: 	} elsif ($resolution eq 'use_typed') {
 6176: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6177: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6178: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6179: 	}
 6180: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6181: 	    $args{'CODE_ignore_dup'}=1;
 6182: 	}
 6183: 	$args{'CODE'}=$newCODE;
 6184: 	($line,$err,$errmsg)=
 6185: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6186: 				     'CODE',\%args);
 6187:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6188: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6189: 	    ($line,$err,$errmsg)=
 6190: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6191: 					 $which,'answer',
 6192: 					 { 'question'=>$question,
 6193: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6194:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6195: 	    if ($err) { last; }
 6196: 	}
 6197:     }
 6198:     if ($err) {
 6199: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6200:     } else {
 6201: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6202: 	&scantron_putfile($scanlines,$scan_data);
 6203:     }
 6204: }
 6205: 
 6206: =pod
 6207: 
 6208: =item reset_skipping_status
 6209: 
 6210:    Forgets the current set of remember skipped scanlines (and thus
 6211:    reverts back to considering all lines in the
 6212:    scantron_skipped_<filename> file)
 6213: 
 6214: =cut
 6215: 
 6216: sub reset_skipping_status {
 6217:     my ($scanlines,$scan_data)=&scantron_getfile();
 6218:     &scan_data($scan_data,'remember_skipping',undef,1);
 6219:     &scantron_putfile(undef,$scan_data);
 6220: }
 6221: 
 6222: =pod
 6223: 
 6224: =item start_skipping
 6225: 
 6226:    Marks a scanline to be skipped. 
 6227: 
 6228: =cut
 6229: 
 6230: sub start_skipping {
 6231:     my ($scan_data,$i)=@_;
 6232:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6233:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6234: 	$remembered{$i}=2;
 6235:     } else {
 6236: 	$remembered{$i}=1;
 6237:     }
 6238:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6239: }
 6240: 
 6241: =pod
 6242: 
 6243: =item should_be_skipped
 6244: 
 6245:    Checks whether a scanline should be skipped.
 6246: 
 6247: =cut
 6248: 
 6249: sub should_be_skipped {
 6250:     my ($scanlines,$scan_data,$i)=@_;
 6251:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6252: 	# not redoing old skips
 6253: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6254: 	return 0;
 6255:     }
 6256:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6257: 
 6258:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6259: 	return 0;
 6260:     }
 6261:     return 1;
 6262: }
 6263: 
 6264: =pod
 6265: 
 6266: =item remember_current_skipped
 6267: 
 6268:    Discovers what scanlines are in the scantron_skipped_<filename>
 6269:    file and remembers them into scan_data for later use.
 6270: 
 6271: =cut
 6272: 
 6273: sub remember_current_skipped {
 6274:     my ($scanlines,$scan_data)=&scantron_getfile();
 6275:     my %to_remember;
 6276:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6277: 	if ($scanlines->{'skipped'}[$i]) {
 6278: 	    $to_remember{$i}=1;
 6279: 	}
 6280:     }
 6281: 
 6282:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6283:     &scantron_putfile(undef,$scan_data);
 6284: }
 6285: 
 6286: =pod
 6287: 
 6288: =item check_for_error
 6289: 
 6290:     Checks if there was an error when attempting to remove a specific
 6291:     scantron_.. bubble sheet data file. Prints out an error if
 6292:     something went wrong.
 6293: 
 6294: =cut
 6295: 
 6296: sub check_for_error {
 6297:     my ($r,$result)=@_;
 6298:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6299: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6300:     }
 6301: }
 6302: 
 6303: =pod
 6304: 
 6305: =item scantron_warning_screen
 6306: 
 6307:    Interstitial screen to make sure the operator has selected the
 6308:    correct options before we start the validation phase.
 6309: 
 6310: =cut
 6311: 
 6312: sub scantron_warning_screen {
 6313:     my ($button_text)=@_;
 6314:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6315:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6316:     my $CODElist;
 6317:     if ($scantron_config{'CODElocation'} &&
 6318: 	$scantron_config{'CODEstart'} &&
 6319: 	$scantron_config{'CODElength'}) {
 6320: 	$CODElist=$env{'form.scantron_CODElist'};
 6321: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6322: 	$CODElist=
 6323: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6324: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6325:     }
 6326:     return ('
 6327: <p>
 6328: <span class="LC_warning">
 6329: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6330: </p>
 6331: <table>
 6332: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6333: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6334: '.$CODElist.'
 6335: </table>
 6336: <br />
 6337: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6338: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6339: 
 6340: <br />
 6341: ');
 6342: }
 6343: 
 6344: =pod
 6345: 
 6346: =item scantron_do_warning
 6347: 
 6348:    Check if the operator has picked something for all required
 6349:    fields. Error out if something is missing.
 6350: 
 6351: =cut
 6352: 
 6353: sub scantron_do_warning {
 6354:     my ($r)=@_;
 6355:     my ($symb)=&get_symb($r);
 6356:     if (!$symb) {return '';}
 6357:     my $default_form_data=&defaultFormData($symb);
 6358:     $r->print(&scantron_form_start().$default_form_data);
 6359:     if ( $env{'form.selectpage'} eq '' ||
 6360: 	 $env{'form.scantron_selectfile'} eq '' ||
 6361: 	 $env{'form.scantron_format'} eq '' ) {
 6362: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6363: 	if ( $env{'form.selectpage'} eq '') {
 6364: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6365: 	} 
 6366: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6367: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6368: 	} 
 6369: 	if ( $env{'form.scantron_format'} eq '') {
 6370: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6371: 	} 
 6372:     } else {
 6373: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6374: 	$r->print('
 6375: '.$warning.'
 6376: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6377: <input type="hidden" name="command" value="scantron_validate" />
 6378: ');
 6379:     }
 6380:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6381:     return '';
 6382: }
 6383: 
 6384: =pod
 6385: 
 6386: =item scantron_form_start
 6387: 
 6388:     html hidden input for remembering all selected grading options
 6389: 
 6390: =cut
 6391: 
 6392: sub scantron_form_start {
 6393:     my ($max_bubble)=@_;
 6394:     my $result= <<SCANTRONFORM;
 6395: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6396:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6397:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6398:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6399:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6400:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6401:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6402:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6403:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6404:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6405: SCANTRONFORM
 6406: 
 6407:   my $line = 0;
 6408:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6409:        my $chunk =
 6410: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6411:        $chunk .=
 6412: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6413:        $chunk .= 
 6414:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6415:        $chunk .=
 6416:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6417:        $result .= $chunk;
 6418:        $line++;
 6419:    }
 6420:     return $result;
 6421: }
 6422: 
 6423: =pod
 6424: 
 6425: =item scantron_validate_file
 6426: 
 6427:     Dispatch routine for doing validation of a bubble sheet data file.
 6428: 
 6429:     Also processes any necessary information resets that need to
 6430:     occur before validation begins (ignore previous corrections,
 6431:     restarting the skipped records processing)
 6432: 
 6433: =cut
 6434: 
 6435: sub scantron_validate_file {
 6436:     my ($r) = @_;
 6437:     my ($symb)=&get_symb($r);
 6438:     if (!$symb) {return '';}
 6439:     my $default_form_data=&defaultFormData($symb);
 6440:     
 6441:     # do the detection of only doing skipped records first befroe we delete
 6442:     # them when doing the corrections reset
 6443:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6444: 	&reset_skipping_status();
 6445:     }
 6446:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6447: 	&remember_current_skipped();
 6448: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6449:     }
 6450: 
 6451:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6452: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6453: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6454: 	&check_for_error($r,&scantron_remove_scan_data());
 6455: 	$env{'form.scantron_options_ignore'}='done';
 6456:     }
 6457: 
 6458:     if ($env{'form.scantron_corrections'}) {
 6459: 	&scantron_process_corrections($r);
 6460:     }
 6461:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6462:     #get the student pick code ready
 6463:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6464:     my $nav_error;
 6465:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6466:     if ($nav_error) {
 6467:         $r->print(&navmap_errormsg());
 6468:         return '';
 6469:     }
 6470:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6471:     $r->print($result);
 6472:     
 6473:     my @validate_phases=( 'sequence',
 6474: 			  'ID',
 6475: 			  'CODE',
 6476: 			  'doublebubble',
 6477: 			  'missingbubbles');
 6478:     if (!$env{'form.validatepass'}) {
 6479: 	$env{'form.validatepass'} = 0;
 6480:     }
 6481:     my $currentphase=$env{'form.validatepass'};
 6482: 
 6483: 
 6484:     my $stop=0;
 6485:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6486: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6487: 	$r->rflush();
 6488: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6489: 	{
 6490: 	    no strict 'refs';
 6491: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6492: 	}
 6493:     }
 6494:     if (!$stop) {
 6495: 	my $warning=&scantron_warning_screen('Start Grading');
 6496: 	$r->print(&mt('Validation process complete.').'<br />'.
 6497:                   $warning.
 6498:                   &mt('Perform verification for each student after storage of submissions?').
 6499:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6500:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6501:                   ('&nbsp;'x3).'<label>'.
 6502:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6503:                   '</label></span><br />'.
 6504:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6505:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6506:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6507:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6508:     } else {
 6509: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6510: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6511:     }
 6512:     if ($stop) {
 6513: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6514: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6515: 	    $r->print(' '.&mt('this error').' <br />');
 6516: 
 6517: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6518: 	} else {
 6519:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6520: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6521:             } else {
 6522:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6523:             }
 6524: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6525: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6526: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6527: 	}
 6528:     }
 6529:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6530:     return '';
 6531: }
 6532: 
 6533: 
 6534: =pod
 6535: 
 6536: =item scantron_remove_file
 6537: 
 6538:    Removes the requested bubble sheet data file, makes sure that
 6539:    scantron_original_<filename> is never removed
 6540: 
 6541: 
 6542: =cut
 6543: 
 6544: sub scantron_remove_file {
 6545:     my ($which)=@_;
 6546:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6548:     my $file='scantron_';
 6549:     if ($which eq 'corrected' || $which eq 'skipped') {
 6550: 	$file.=$which.'_';
 6551:     } else {
 6552: 	return 'refused';
 6553:     }
 6554:     $file.=$env{'form.scantron_selectfile'};
 6555:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6556: }
 6557: 
 6558: 
 6559: =pod
 6560: 
 6561: =item scantron_remove_scan_data
 6562: 
 6563:    Removes all scan_data correction for the requested bubble sheet
 6564:    data file.  (In the case that both the are doing skipped records we need
 6565:    to remember the old skipped lines for the time being so that element
 6566:    persists for a while.)
 6567: 
 6568: =cut
 6569: 
 6570: sub scantron_remove_scan_data {
 6571:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6572:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6573:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6574:     my @todelete;
 6575:     my $filename=$env{'form.scantron_selectfile'};
 6576:     foreach my $key (@keys) {
 6577: 	if ($key=~/^\Q$filename\E_/) {
 6578: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6579: 		$key=~/remember_skipping/) {
 6580: 		next;
 6581: 	    }
 6582: 	    push(@todelete,$key);
 6583: 	}
 6584:     }
 6585:     my $result;
 6586:     if (@todelete) {
 6587: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6588: 				       \@todelete,$cdom,$cname);
 6589:     } else {
 6590: 	$result = 'ok';
 6591:     }
 6592:     return $result;
 6593: }
 6594: 
 6595: 
 6596: =pod
 6597: 
 6598: =item scantron_getfile
 6599: 
 6600:     Fetches the requested bubble sheet data file (all 3 versions), and
 6601:     the scan_data hash
 6602:   
 6603:   Arguments:
 6604:     None
 6605: 
 6606:   Returns:
 6607:     2 hash references
 6608: 
 6609:      - first one has 
 6610:          orig      -
 6611:          corrected -
 6612:          skipped   -  each of which points to an array ref of the specified
 6613:                       file broken up into individual lines
 6614:          count     - number of scanlines
 6615:  
 6616:      - second is the scan_data hash possible keys are
 6617:        ($number refers to scanline numbered $number and thus the key affects
 6618:         only that scanline
 6619:         $bubline refers to the specific bubble line element and the aspects
 6620:         refers to that specific bubble line element)
 6621: 
 6622:        $number.user - username:domain to use
 6623:        $number.CODE_ignore_dup 
 6624:                     - ignore the duplicate CODE error 
 6625:        $number.useCODE
 6626:                     - use the CODE in the scanline as is
 6627:        $number.no_bubble.$bubline
 6628:                     - it is valid that there is no bubbled in bubble
 6629:                       at $number $bubline
 6630:        remember_skipping
 6631:                     - a frozen hash containing keys of $number and values
 6632:                       of either 
 6633:                         1 - we are on a 'do skipped records pass' and plan
 6634:                             on processing this line
 6635:                         2 - we are on a 'do skipped records pass' and this
 6636:                             scanline has been marked to skip yet again
 6637: 
 6638: =cut
 6639: 
 6640: sub scantron_getfile {
 6641:     #FIXME really would prefer a scantron directory
 6642:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6644:     my $lines;
 6645:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6646: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6647:     my %scanlines;
 6648:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6649:     my $temp=$scanlines{'orig'};
 6650:     $scanlines{'count'}=$#$temp;
 6651: 
 6652:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6653: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6654:     if ($lines eq '-1') {
 6655: 	$scanlines{'corrected'}=[];
 6656:     } else {
 6657: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6658:     }
 6659:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6660: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6661:     if ($lines eq '-1') {
 6662: 	$scanlines{'skipped'}=[];
 6663:     } else {
 6664: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6665:     }
 6666:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6667:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6668:     my %scan_data = @tmp;
 6669:     return (\%scanlines,\%scan_data);
 6670: }
 6671: 
 6672: =pod
 6673: 
 6674: =item lonnet_putfile
 6675: 
 6676:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6677: 
 6678:  Arguments:
 6679:    $contents - data to store
 6680:    $filename - filename to store $contents into
 6681: 
 6682:  Returns:
 6683:    result value from &Apache::lonnet::finishuserfileupload
 6684: 
 6685: =cut
 6686: 
 6687: sub lonnet_putfile {
 6688:     my ($contents,$filename)=@_;
 6689:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6690:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6691:     $env{'form.sillywaytopassafilearound'}=$contents;
 6692:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6693: 
 6694: }
 6695: 
 6696: =pod
 6697: 
 6698: =item scantron_putfile
 6699: 
 6700:     Stores the current version of the bubble sheet data files, and the
 6701:     scan_data hash. (Does not modify the original version only the
 6702:     corrected and skipped versions.
 6703: 
 6704:  Arguments:
 6705:     $scanlines - hash ref that looks like the first return value from
 6706:                  &scantron_getfile()
 6707:     $scan_data - hash ref that looks like the second return value from
 6708:                  &scantron_getfile()
 6709: 
 6710: =cut
 6711: 
 6712: sub scantron_putfile {
 6713:     my ($scanlines,$scan_data) = @_;
 6714:     #FIXME really would prefer a scantron directory
 6715:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6716:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6717:     if ($scanlines) {
 6718: 	my $prefix='scantron_';
 6719: # no need to update orig, shouldn't change
 6720: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6721: #		    $env{'form.scantron_selectfile'});
 6722: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6723: 			$prefix.'corrected_'.
 6724: 			$env{'form.scantron_selectfile'});
 6725: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6726: 			$prefix.'skipped_'.
 6727: 			$env{'form.scantron_selectfile'});
 6728:     }
 6729:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6730: }
 6731: 
 6732: =pod
 6733: 
 6734: =item scantron_get_line
 6735: 
 6736:    Returns the correct version of the scanline
 6737: 
 6738:  Arguments:
 6739:     $scanlines - hash ref that looks like the first return value from
 6740:                  &scantron_getfile()
 6741:     $scan_data - hash ref that looks like the second return value from
 6742:                  &scantron_getfile()
 6743:     $i         - number of the requested line (starts at 0)
 6744: 
 6745:  Returns:
 6746:    A scanline, (either the original or the corrected one if it
 6747:    exists), or undef if the requested scanline should be
 6748:    skipped. (Either because it's an skipped scanline, or it's an
 6749:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6750:    pass.
 6751: 
 6752: =cut
 6753: 
 6754: sub scantron_get_line {
 6755:     my ($scanlines,$scan_data,$i)=@_;
 6756:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6757:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6758:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6759:     return $scanlines->{'orig'}[$i]; 
 6760: }
 6761: 
 6762: =pod
 6763: 
 6764: =item scantron_todo_count
 6765: 
 6766:     Counts the number of scanlines that need processing.
 6767: 
 6768:  Arguments:
 6769:     $scanlines - hash ref that looks like the first return value from
 6770:                  &scantron_getfile()
 6771:     $scan_data - hash ref that looks like the second return value from
 6772:                  &scantron_getfile()
 6773: 
 6774:  Returns:
 6775:     $count - number of scanlines to process
 6776: 
 6777: =cut
 6778: 
 6779: sub get_todo_count {
 6780:     my ($scanlines,$scan_data)=@_;
 6781:     my $count=0;
 6782:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6783: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6784: 	if ($line=~/^[\s\cz]*$/) { next; }
 6785: 	$count++;
 6786:     }
 6787:     return $count;
 6788: }
 6789: 
 6790: =pod
 6791: 
 6792: =item scantron_put_line
 6793: 
 6794:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6795:     data file.
 6796: 
 6797:  Arguments:
 6798:     $scanlines - hash ref that looks like the first return value from
 6799:                  &scantron_getfile()
 6800:     $scan_data - hash ref that looks like the second return value from
 6801:                  &scantron_getfile()
 6802:     $i         - line number to update
 6803:     $newline   - contents of the updated scanline
 6804:     $skip      - if true make the line for skipping and update the
 6805:                  'skipped' file
 6806: 
 6807: =cut
 6808: 
 6809: sub scantron_put_line {
 6810:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6811:     if ($skip) {
 6812: 	$scanlines->{'skipped'}[$i]=$newline;
 6813: 	&start_skipping($scan_data,$i);
 6814: 	return;
 6815:     }
 6816:     $scanlines->{'corrected'}[$i]=$newline;
 6817: }
 6818: 
 6819: =pod
 6820: 
 6821: =item scantron_clear_skip
 6822: 
 6823:    Remove a line from the 'skipped' file
 6824: 
 6825:  Arguments:
 6826:     $scanlines - hash ref that looks like the first return value from
 6827:                  &scantron_getfile()
 6828:     $scan_data - hash ref that looks like the second return value from
 6829:                  &scantron_getfile()
 6830:     $i         - line number to update
 6831: 
 6832: =cut
 6833: 
 6834: sub scantron_clear_skip {
 6835:     my ($scanlines,$scan_data,$i)=@_;
 6836:     if (exists($scanlines->{'skipped'}[$i])) {
 6837: 	undef($scanlines->{'skipped'}[$i]);
 6838: 	return 1;
 6839:     }
 6840:     return 0;
 6841: }
 6842: 
 6843: =pod
 6844: 
 6845: =item scantron_filter_not_exam
 6846: 
 6847:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6848:    filter out resources that are not marked as 'exam' mode
 6849: 
 6850: =cut
 6851: 
 6852: sub scantron_filter_not_exam {
 6853:     my ($curres)=@_;
 6854:     
 6855:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6856: 	# if the user has asked to not have either hidden
 6857: 	# or 'randomout' controlled resources to be graded
 6858: 	# don't include them
 6859: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6860: 	    && $curres->randomout) {
 6861: 	    return 0;
 6862: 	}
 6863: 	return 1;
 6864:     }
 6865:     return 0;
 6866: }
 6867: 
 6868: =pod
 6869: 
 6870: =item scantron_validate_sequence
 6871: 
 6872:     Validates the selected sequence, checking for resource that are
 6873:     not set to exam mode.
 6874: 
 6875: =cut
 6876: 
 6877: sub scantron_validate_sequence {
 6878:     my ($r,$currentphase) = @_;
 6879: 
 6880:     my $navmap=Apache::lonnavmaps::navmap->new();
 6881:     unless (ref($navmap)) {
 6882:         $r->print(&navmap_errormsg());
 6883:         return (1,$currentphase);
 6884:     }
 6885:     my (undef,undef,$sequence)=
 6886: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6887: 
 6888:     my $map=$navmap->getResourceByUrl($sequence);
 6889: 
 6890:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6891:                                     value="ignore" />');
 6892:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6893: 	my @resources=
 6894: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6895: 	if (@resources) {
 6896: 	    $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>");
 6897: 	    return (1,$currentphase);
 6898: 	}
 6899:     }
 6900: 
 6901:     return (0,$currentphase+1);
 6902: }
 6903: 
 6904: 
 6905: 
 6906: sub scantron_validate_ID {
 6907:     my ($r,$currentphase) = @_;
 6908:     
 6909:     #get student info
 6910:     my $classlist=&Apache::loncoursedata::get_classlist();
 6911:     my %idmap=&username_to_idmap($classlist);
 6912: 
 6913:     #get scantron line setup
 6914:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6915:     my ($scanlines,$scan_data)=&scantron_getfile();
 6916: 
 6917:     my $nav_error;
 6918:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6919:     if ($nav_error) {
 6920:         $r->print(&navmap_errormsg());
 6921:         return(1,$currentphase);
 6922:     }
 6923: 
 6924:     my %found=('ids'=>{},'usernames'=>{});
 6925:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6926: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6927: 	if ($line=~/^[\s\cz]*$/) { next; }
 6928: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6929: 						 $scan_data);
 6930: 	my $id=$$scan_record{'scantron.ID'};
 6931: 	my $found;
 6932: 	foreach my $checkid (keys(%idmap)) {
 6933: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6934: 	}
 6935: 	if ($found) {
 6936: 	    my $username=$idmap{$found};
 6937: 	    if ($found{'ids'}{$found}) {
 6938: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6939: 					 $line,'duplicateID',$found);
 6940: 		return(1,$currentphase);
 6941: 	    } elsif ($found{'usernames'}{$username}) {
 6942: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6943: 					 $line,'duplicateID',$username);
 6944: 		return(1,$currentphase);
 6945: 	    }
 6946: 	    #FIXME store away line we previously saw the ID on to use above
 6947: 	    $found{'ids'}{$found}++;
 6948: 	    $found{'usernames'}{$username}++;
 6949: 	} else {
 6950: 	    if ($id =~ /^\s*$/) {
 6951: 		my $username=&scan_data($scan_data,"$i.user");
 6952: 		if (defined($username) && $found{'usernames'}{$username}) {
 6953: 		    &scantron_get_correction($r,$i,$scan_record,
 6954: 					     \%scantron_config,
 6955: 					     $line,'duplicateID',$username);
 6956: 		    return(1,$currentphase);
 6957: 		} elsif (!defined($username)) {
 6958: 		    &scantron_get_correction($r,$i,$scan_record,
 6959: 					     \%scantron_config,
 6960: 					     $line,'incorrectID');
 6961: 		    return(1,$currentphase);
 6962: 		}
 6963: 		$found{'usernames'}{$username}++;
 6964: 	    } else {
 6965: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6966: 					 $line,'incorrectID');
 6967: 		return(1,$currentphase);
 6968: 	    }
 6969: 	}
 6970:     }
 6971: 
 6972:     return (0,$currentphase+1);
 6973: }
 6974: 
 6975: 
 6976: sub scantron_get_correction {
 6977:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6978: #FIXME in the case of a duplicated ID the previous line, probably need
 6979: #to show both the current line and the previous one and allow skipping
 6980: #the previous one or the current one
 6981: 
 6982:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6983: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6984: 			    " for PaperID <tt>[_1]</tt>",
 6985: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6986:     } else {
 6987: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6988: 			    " in scanline [_1] <pre>[_2]</pre>",
 6989: 			    $i,$line)."</p> \n");
 6990:     }
 6991:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6992: 			  "The name on the paper is [_2],[_3]",
 6993: 			  $$scan_record{'scantron.ID'},
 6994: 			  $$scan_record{'scantron.LastName'},
 6995: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6996: 
 6997:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6998:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6999:                            # Array populated for doublebubble or
 7000:     my @lines_to_correct;  # missingbubble errors to build javascript
 7001:                            # to validate radio button checking   
 7002: 
 7003:     if ($error =~ /ID$/) {
 7004: 	if ($error eq 'incorrectID') {
 7005: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 7006: 		      "</p>\n");
 7007: 	} elsif ($error eq 'duplicateID') {
 7008: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 7009: 	}
 7010: 	$r->print($message);
 7011: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7012: 	$r->print("\n<ul><li> ");
 7013: 	#FIXME it would be nice if this sent back the user ID and
 7014: 	#could do partial userID matches
 7015: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 7016: 				       'scantron_username','scantron_domain'));
 7017: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 7018: 	$r->print("\n@".
 7019: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 7020: 
 7021: 	$r->print('</li>');
 7022:     } elsif ($error =~ /CODE$/) {
 7023: 	if ($error eq 'incorrectCODE') {
 7024: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 7025: 	} elsif ($error eq 'duplicateCODE') {
 7026: 	    $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");
 7027: 	}
 7028: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 7029: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 7030: 	$r->print($message);
 7031: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 7032: 	$r->print("\n<br /> ");
 7033: 	my $i=0;
 7034: 	if ($error eq 'incorrectCODE' 
 7035: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 7036: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 7037: 	    if ($closest > 0) {
 7038: 		foreach my $testcode (@{$closest}) {
 7039: 		    my $checked='';
 7040: 		    if (!$i) { $checked=' checked="checked"'; }
 7041: 		    $r->print("
 7042:    <label>
 7043:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 7044:        ".&mt("Use the similar CODE [_1] instead.",
 7045: 	    "<b><tt>".$testcode."</tt></b>")."
 7046:     </label>
 7047:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 7048: 		    $r->print("\n<br />");
 7049: 		    $i++;
 7050: 		}
 7051: 	    }
 7052: 	}
 7053: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 7054: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 7055: 	    $r->print("
 7056:     <label>
 7057:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 7058:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 7059: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 7060:     </label>");
 7061: 	    $r->print("\n<br />");
 7062: 	}
 7063: 
 7064: 	$r->print(<<ENDSCRIPT);
 7065: <script type="text/javascript">
 7066: function change_radio(field) {
 7067:     var slct=document.scantronupload.scantron_CODE_resolution;
 7068:     var i;
 7069:     for (i=0;i<slct.length;i++) {
 7070:         if (slct[i].value==field) { slct[i].checked=true; }
 7071:     }
 7072: }
 7073: </script>
 7074: ENDSCRIPT
 7075: 	my $href="/adm/pickcode?".
 7076: 	   "form=".&escape("scantronupload").
 7077: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 7078: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 7079: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 7080: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 7081: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 7082: 	    $r->print("
 7083:     <label>
 7084:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 7085:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 7086: 	     "<a target='_blank' href='$href'>","</a>")."
 7087:     </label> 
 7088:     ".&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\')" />'));
 7089: 	    $r->print("\n<br />");
 7090: 	}
 7091: 	$r->print("
 7092:     <label>
 7093:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 7094:        ".&mt("Use [_1] as the CODE.",
 7095: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 7096: 	$r->print("\n<br /><br />");
 7097:     } elsif ($error eq 'doublebubble') {
 7098: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 7099: 
 7100: 	# The form field scantron_questions is acutally a list of line numbers.
 7101: 	# represented by this form so:
 7102: 
 7103: 	my $line_list = &questions_to_line_list($arg);
 7104: 
 7105: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7106: 		  $line_list.'" />');
 7107: 	$r->print($message);
 7108: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 7109: 	foreach my $question (@{$arg}) {
 7110: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7111:                                                    $scan_record, $error);
 7112:             push(@lines_to_correct,@linenums);
 7113: 	}
 7114:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7115:     } elsif ($error eq 'missingbubble') {
 7116: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7117: 	$r->print($message);
 7118: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7119: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7120: 
 7121: 	# The form field scantron_questions is actually a list of line numbers not
 7122: 	# a list of question numbers. Therefore:
 7123: 	#
 7124: 	
 7125: 	my $line_list = &questions_to_line_list($arg);
 7126: 
 7127: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7128: 		  $line_list.'" />');
 7129: 	foreach my $question (@{$arg}) {
 7130: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7131:                                                    $scan_record, $error);
 7132:             push(@lines_to_correct,@linenums);
 7133: 	}
 7134:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7135:     } else {
 7136: 	$r->print("\n<ul>");
 7137:     }
 7138:     $r->print("\n</li></ul>");
 7139: }
 7140: 
 7141: sub verify_bubbles_checked {
 7142:     my (@ansnums) = @_;
 7143:     my $ansnumstr = join('","',@ansnums);
 7144:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7145:     my $output = (<<ENDSCRIPT);
 7146: <script type="text/javascript">
 7147: function verify_bubble_radio(form) {
 7148:     var ansnumArray = new Array ("$ansnumstr");
 7149:     var need_bubble_count = 0;
 7150:     for (var i=0; i<ansnumArray.length; i++) {
 7151:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7152:             var bubble_picked = 0; 
 7153:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7154:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7155:                     bubble_picked = 1;
 7156:                 }
 7157:             }
 7158:             if (bubble_picked == 0) {
 7159:                 need_bubble_count ++;
 7160:             }
 7161:         }
 7162:     }
 7163:     if (need_bubble_count) {
 7164:         alert("$warning");
 7165:         return;
 7166:     }
 7167:     form.submit(); 
 7168: }
 7169: </script>
 7170: ENDSCRIPT
 7171:     return $output;
 7172: }
 7173: 
 7174: =pod
 7175: 
 7176: =item  questions_to_line_list
 7177: 
 7178: Converts a list of questions into a string of comma separated
 7179: line numbers in the answer sheet used by the questions.  This is
 7180: used to fill in the scantron_questions form field.
 7181: 
 7182:   Arguments:
 7183:      questions    - Reference to an array of questions.
 7184: 
 7185: =cut
 7186: 
 7187: 
 7188: sub questions_to_line_list {
 7189:     my ($questions) = @_;
 7190:     my @lines;
 7191: 
 7192:     foreach my $item (@{$questions}) {
 7193:         my $question = $item;
 7194:         my ($first,$count,$last);
 7195:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7196:             $question = $1;
 7197:             my $subquestion = $2;
 7198:             $first = $first_bubble_line{$question-1} + 1;
 7199:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7200:             my $subcount = 1;
 7201:             while ($subcount<$subquestion) {
 7202:                 $first += $subans[$subcount-1];
 7203:                 $subcount ++;
 7204:             }
 7205:             $count = $subans[$subquestion-1];
 7206:         } else {
 7207: 	    $first   = $first_bubble_line{$question-1} + 1;
 7208: 	    $count   = $bubble_lines_per_response{$question-1};
 7209:         }
 7210:         $last = $first+$count-1;
 7211:         push(@lines, ($first..$last));
 7212:     }
 7213:     return join(',', @lines);
 7214: }
 7215: 
 7216: =pod 
 7217: 
 7218: =item prompt_for_corrections
 7219: 
 7220: Prompts for a potentially multiline correction to the
 7221: user's bubbling (factors out common code from scantron_get_correction
 7222: for multi and missing bubble cases).
 7223: 
 7224:  Arguments:
 7225:    $r           - Apache request object.
 7226:    $question    - The question number to prompt for.
 7227:    $scan_config - The scantron file configuration hash.
 7228:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7229:    $error       - Type of error
 7230: 
 7231:  Implicit inputs:
 7232:    %bubble_lines_per_response   - Starting line numbers for each question.
 7233:                                   Numbered from 0 (but question numbers are from
 7234:                                   1.
 7235:    %first_bubble_line           - Starting bubble line for each question.
 7236:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7237:                                   type problems render as separate sub-questions, 
 7238:                                   in exam mode. This hash contains a 
 7239:                                   comma-separated list of the lines per 
 7240:                                   sub-question.
 7241:    %responsetype_per_response   - essayresponse, formularesponse,
 7242:                                   stringresponse, imageresponse, reactionresponse,
 7243:                                   and organicresponse type problem parts can have
 7244:                                   multiple lines per response if the weight
 7245:                                   assigned exceeds 10.  In this case, only
 7246:                                   one bubble per line is permitted, but more 
 7247:                                   than one line might contain bubbles, e.g.
 7248:                                   bubbling of: line 1 - J, line 2 - J, 
 7249:                                   line 3 - B would assign 22 points.  
 7250: 
 7251: =cut
 7252: 
 7253: sub prompt_for_corrections {
 7254:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7255:     my ($current_line,$lines);
 7256:     my @linenums;
 7257:     my $questionnum = $question;
 7258:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7259:         $question = $1;
 7260:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7261:         my $subquestion = $2;
 7262:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7263:         my $subcount = 1;
 7264:         while ($subcount<$subquestion) {
 7265:             $current_line += $subans[$subcount-1];
 7266:             $subcount ++;
 7267:         }
 7268:         $lines = $subans[$subquestion-1];
 7269:     } else {
 7270:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7271:         $lines        = $bubble_lines_per_response{$question-1};
 7272:     }
 7273:     if ($lines > 1) {
 7274:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7275:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7276:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7277:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7278:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7279:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7280:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7281:             $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 />');
 7282:         } else {
 7283:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7284:         }
 7285:     }
 7286:     for (my $i =0; $i < $lines; $i++) {
 7287:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7288: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7289: 	        		  $questionnum,$error,split('', $selected));
 7290:         push(@linenums,$current_line);
 7291: 	$current_line++;
 7292:     }
 7293:     if ($lines > 1) {
 7294: 	$r->print("<hr /><br />");
 7295:     }
 7296:     return @linenums;
 7297: }
 7298: 
 7299: =pod
 7300: 
 7301: =item scantron_bubble_selector
 7302:   
 7303:    Generates the html radiobuttons to correct a single bubble line
 7304:    possibly showing the existing the selected bubbles if known
 7305: 
 7306:  Arguments:
 7307:     $r           - Apache request object
 7308:     $scan_config - hash from &get_scantron_config()
 7309:     $line        - Number of the line being displayed.
 7310:     $questionnum - Question number (may include subquestion)
 7311:     $error       - Type of error.
 7312:     @selected    - Array of bubbles picked on this line.
 7313: 
 7314: =cut
 7315: 
 7316: sub scantron_bubble_selector {
 7317:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7318:     my $max=$$scan_config{'Qlength'};
 7319: 
 7320:     my $scmode=$$scan_config{'Qon'};
 7321:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7322: 
 7323:     my @alphabet=('A'..'Z');
 7324:     $r->print(&Apache::loncommon::start_data_table().
 7325:               &Apache::loncommon::start_data_table_row());
 7326:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7327:     for (my $i=0;$i<$max+1;$i++) {
 7328: 	$r->print("\n".'<td align="center">');
 7329: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7330: 	else { $r->print('&nbsp;'); }
 7331: 	$r->print('</td>');
 7332:     }
 7333:     $r->print(&Apache::loncommon::end_data_table_row().
 7334:               &Apache::loncommon::start_data_table_row());
 7335:     for (my $i=0;$i<$max;$i++) {
 7336: 	$r->print("\n".
 7337: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7338: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7339:     }
 7340:     my $nobub_checked = ' ';
 7341:     if ($error eq 'missingbubble') {
 7342:         $nobub_checked = ' checked = "checked" ';
 7343:     }
 7344:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7345: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7346:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7347:               $line.'" value="'.$questionnum.'" /></td>');
 7348:     $r->print(&Apache::loncommon::end_data_table_row().
 7349:               &Apache::loncommon::end_data_table());
 7350: }
 7351: 
 7352: =pod
 7353: 
 7354: =item num_matches
 7355: 
 7356:    Counts the number of characters that are the same between the two arguments.
 7357: 
 7358:  Arguments:
 7359:    $orig - CODE from the scanline
 7360:    $code - CODE to match against
 7361: 
 7362:  Returns:
 7363:    $count - integer count of the number of same characters between the
 7364:             two arguments
 7365: 
 7366: =cut
 7367: 
 7368: sub num_matches {
 7369:     my ($orig,$code) = @_;
 7370:     my @code=split(//,$code);
 7371:     my @orig=split(//,$orig);
 7372:     my $same=0;
 7373:     for (my $i=0;$i<scalar(@code);$i++) {
 7374: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7375:     }
 7376:     return $same;
 7377: }
 7378: 
 7379: =pod
 7380: 
 7381: =item scantron_get_closely_matching_CODEs
 7382: 
 7383:    Cycles through all CODEs and finds the set that has the greatest
 7384:    number of same characters as the provided CODE
 7385: 
 7386:  Arguments:
 7387:    $allcodes - hash ref returned by &get_codes()
 7388:    $CODE     - CODE from the current scanline
 7389: 
 7390:  Returns:
 7391:    2 element list
 7392:     - first elements is number of how closely matching the best fit is 
 7393:       (5 means best set has 5 matching characters)
 7394:     - second element is an arrary ref containing the set of valid CODEs
 7395:       that best fit the passed in CODE
 7396: 
 7397: =cut
 7398: 
 7399: sub scantron_get_closely_matching_CODEs {
 7400:     my ($allcodes,$CODE)=@_;
 7401:     my @CODEs;
 7402:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7403: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7404:     }
 7405: 
 7406:     return ($#CODEs,$CODEs[-1]);
 7407: }
 7408: 
 7409: =pod
 7410: 
 7411: =item get_codes
 7412: 
 7413:    Builds a hash which has keys of all of the valid CODEs from the selected
 7414:    set of remembered CODEs.
 7415: 
 7416:  Arguments:
 7417:   $old_name - name of the set of remembered CODEs
 7418:   $cdom     - domain of the course
 7419:   $cnum     - internal course name
 7420: 
 7421:  Returns:
 7422:   %allcodes - keys are the valid CODEs, values are all 1
 7423: 
 7424: =cut
 7425: 
 7426: sub get_codes {
 7427:     my ($old_name, $cdom, $cnum) = @_;
 7428:     if (!$old_name) {
 7429: 	$old_name=$env{'form.scantron_CODElist'};
 7430:     }
 7431:     if (!$cdom) {
 7432: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:     }
 7434:     if (!$cnum) {
 7435: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7436:     }
 7437:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7438: 				    $cdom,$cnum);
 7439:     my %allcodes;
 7440:     if ($result{"type\0$old_name"} eq 'number') {
 7441: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7442:     } else {
 7443: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7444:     }
 7445:     return %allcodes;
 7446: }
 7447: 
 7448: =pod
 7449: 
 7450: =item scantron_validate_CODE
 7451: 
 7452:    Validates all scanlines in the selected file to not have any
 7453:    invalid or underspecified CODEs and that none of the codes are
 7454:    duplicated if this was requested.
 7455: 
 7456: =cut
 7457: 
 7458: sub scantron_validate_CODE {
 7459:     my ($r,$currentphase) = @_;
 7460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7461:     if ($scantron_config{'CODElocation'} &&
 7462: 	$scantron_config{'CODEstart'} &&
 7463: 	$scantron_config{'CODElength'}) {
 7464: 	if (!defined($env{'form.scantron_CODElist'})) {
 7465: 	    &FIXME_blow_up()
 7466: 	}
 7467:     } else {
 7468: 	return (0,$currentphase+1);
 7469:     }
 7470:     
 7471:     my %usedCODEs;
 7472: 
 7473:     my %allcodes=&get_codes();
 7474: 
 7475:     my $nav_error;
 7476:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7477:     if ($nav_error) {
 7478:         $r->print(&navmap_errormsg());
 7479:         return(1,$currentphase);
 7480:     }
 7481: 
 7482:     my ($scanlines,$scan_data)=&scantron_getfile();
 7483:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7484: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7485: 	if ($line=~/^[\s\cz]*$/) { next; }
 7486: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7487: 						 $scan_data);
 7488: 	my $CODE=$$scan_record{'scantron.CODE'};
 7489: 	my $error=0;
 7490: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7491: 	    &scantron_get_correction($r,$i,$scan_record,
 7492: 				     \%scantron_config,
 7493: 				     $line,'incorrectCODE',\%allcodes);
 7494: 	    return(1,$currentphase);
 7495: 	}
 7496: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7497: 	    && !$$scan_record{'scantron.useCODE'}) {
 7498: 	    &scantron_get_correction($r,$i,$scan_record,
 7499: 				     \%scantron_config,
 7500: 				     $line,'incorrectCODE',\%allcodes);
 7501: 	    return(1,$currentphase);
 7502: 	}
 7503: 	if (exists($usedCODEs{$CODE}) 
 7504: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7505: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7506: 	    &scantron_get_correction($r,$i,$scan_record,
 7507: 				     \%scantron_config,
 7508: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7509: 	    return(1,$currentphase);
 7510: 	}
 7511: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7512:     }
 7513:     return (0,$currentphase+1);
 7514: }
 7515: 
 7516: =pod
 7517: 
 7518: =item scantron_validate_doublebubble
 7519: 
 7520:    Validates all scanlines in the selected file to not have any
 7521:    bubble lines with multiple bubbles marked.
 7522: 
 7523: =cut
 7524: 
 7525: sub scantron_validate_doublebubble {
 7526:     my ($r,$currentphase) = @_;
 7527:     #get student info
 7528:     my $classlist=&Apache::loncoursedata::get_classlist();
 7529:     my %idmap=&username_to_idmap($classlist);
 7530: 
 7531:     #get scantron line setup
 7532:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7533:     my ($scanlines,$scan_data)=&scantron_getfile();
 7534:     my $nav_error;
 7535:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7536:     if ($nav_error) {
 7537:         $r->print(&navmap_errormsg());
 7538:         return(1,$currentphase);
 7539:     }
 7540: 
 7541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7542: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7543: 	if ($line=~/^[\s\cz]*$/) { next; }
 7544: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7545: 						 $scan_data);
 7546: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7547: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7548: 				 'doublebubble',
 7549: 				 $$scan_record{'scantron.doubleerror'});
 7550:     	return (1,$currentphase);
 7551:     }
 7552:     return (0,$currentphase+1);
 7553: }
 7554: 
 7555: 
 7556: sub scantron_get_maxbubble {
 7557:     my ($nav_error) = @_;
 7558:     if (defined($env{'form.scantron_maxbubble'}) &&
 7559: 	$env{'form.scantron_maxbubble'}) {
 7560: 	&restore_bubble_lines();
 7561: 	return $env{'form.scantron_maxbubble'};
 7562:     }
 7563: 
 7564:     my (undef, undef, $sequence) =
 7565: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7566: 
 7567:     my $navmap=Apache::lonnavmaps::navmap->new();
 7568:     unless (ref($navmap)) {
 7569:         if (ref($nav_error)) {
 7570:             $$nav_error = 1;
 7571:         }
 7572:         return;
 7573:     }
 7574:     my $map=$navmap->getResourceByUrl($sequence);
 7575:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7576: 
 7577:     &Apache::lonxml::clear_problem_counter();
 7578: 
 7579:     my $uname       = $env{'user.name'};
 7580:     my $udom        = $env{'user.domain'};
 7581:     my $cid         = $env{'request.course.id'};
 7582:     my $total_lines = 0;
 7583:     %bubble_lines_per_response = ();
 7584:     %first_bubble_line         = ();
 7585:     %subdivided_bubble_lines   = ();
 7586:     %responsetype_per_response = ();
 7587: 
 7588:     my $response_number = 0;
 7589:     my $bubble_line     = 0;
 7590:     foreach my $resource (@resources) {
 7591:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7592:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7593: 	    foreach my $part_id (@{$parts}) {
 7594:                 my $lines;
 7595: 
 7596: 	        # TODO - make this a persistent hash not an array.
 7597: 
 7598:                 # optionresponse, matchresponse and rankresponse type items 
 7599:                 # render as separate sub-questions in exam mode.
 7600:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7601:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7602:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7603:                     my ($numbub,$numshown);
 7604:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7605:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7606:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7607:                         }
 7608:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7609:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7610:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7611:                         }
 7612:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7613:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7614:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7615:                         }
 7616:                     }
 7617:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7618:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7619:                     }
 7620:                     my $bubbles_per_line = 10;
 7621:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7622:                     if (($numbub % $bubbles_per_line) != 0) {
 7623:                         $inner_bubble_lines++;
 7624:                     }
 7625:                     for (my $i=0; $i<$numshown; $i++) {
 7626:                         $subdivided_bubble_lines{$response_number} .= 
 7627:                             $inner_bubble_lines.',';
 7628:                     }
 7629:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7630:                     $lines = $numshown * $inner_bubble_lines;
 7631:                 } else {
 7632:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7633:                 } 
 7634: 
 7635:                 $first_bubble_line{$response_number} = $bubble_line;
 7636: 	        $bubble_lines_per_response{$response_number} = $lines;
 7637:                 $responsetype_per_response{$response_number} = 
 7638:                     $analysis->{$part_id.'.type'};
 7639: 	        $response_number++;
 7640: 
 7641: 	        $bubble_line +=  $lines;
 7642: 	        $total_lines +=  $lines;
 7643: 	    }
 7644:         }
 7645:     }
 7646:     &Apache::lonnet::delenv('scantron.');
 7647: 
 7648:     &save_bubble_lines();
 7649:     $env{'form.scantron_maxbubble'} =
 7650: 	$total_lines;
 7651:     return $env{'form.scantron_maxbubble'};
 7652: }
 7653: 
 7654: sub scantron_validate_missingbubbles {
 7655:     my ($r,$currentphase) = @_;
 7656:     #get student info
 7657:     my $classlist=&Apache::loncoursedata::get_classlist();
 7658:     my %idmap=&username_to_idmap($classlist);
 7659: 
 7660:     #get scantron line setup
 7661:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7662:     my ($scanlines,$scan_data)=&scantron_getfile();
 7663:     my $nav_error;
 7664:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7665:     if ($nav_error) {
 7666:         return(1,$currentphase);
 7667:     }
 7668:     if (!$max_bubble) { $max_bubble=2**31; }
 7669:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7670: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7671: 	if ($line=~/^[\s\cz]*$/) { next; }
 7672: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7673: 						 $scan_data);
 7674: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7675: 	my @to_correct;
 7676: 	
 7677: 	# Probably here's where the error is...
 7678: 
 7679: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7680:             my $lastbubble;
 7681:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7682:                my $question = $1;
 7683:                my $subquestion = $2;
 7684:                if (!defined($first_bubble_line{$question -1})) { next; }
 7685:                my $first = $first_bubble_line{$question-1};
 7686:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7687:                my $subcount = 1;
 7688:                while ($subcount<$subquestion) {
 7689:                    $first += $subans[$subcount-1];
 7690:                    $subcount ++;
 7691:                }
 7692:                my $count = $subans[$subquestion-1];
 7693:                $lastbubble = $first + $count;
 7694:             } else {
 7695:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7696:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7697:             }
 7698:             if ($lastbubble > $max_bubble) { next; }
 7699: 	    push(@to_correct,$missing);
 7700: 	}
 7701: 	if (@to_correct) {
 7702: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7703: 				     $line,'missingbubble',\@to_correct);
 7704: 	    return (1,$currentphase);
 7705: 	}
 7706: 
 7707:     }
 7708:     return (0,$currentphase+1);
 7709: }
 7710: 
 7711: 
 7712: sub scantron_process_students {
 7713:     my ($r) = @_;
 7714: 
 7715:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7716:     my ($symb)=&get_symb($r);
 7717:     if (!$symb) {
 7718: 	return '';
 7719:     }
 7720:     my $default_form_data=&defaultFormData($symb);
 7721: 
 7722:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7723:     my ($scanlines,$scan_data)=&scantron_getfile();
 7724:     my $classlist=&Apache::loncoursedata::get_classlist();
 7725:     my %idmap=&username_to_idmap($classlist);
 7726:     my $navmap=Apache::lonnavmaps::navmap->new();
 7727:     unless (ref($navmap)) {
 7728:         $r->print(&navmap_errormsg());
 7729:         return '';
 7730:     }  
 7731:     my $map=$navmap->getResourceByUrl($sequence);
 7732:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7733:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7734:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7735:                             \%grader_randomlists_by_symb);
 7736:     my $resource_error;
 7737:     foreach my $resource (@resources) {
 7738:         my $ressymb;
 7739:         if (ref($resource)) {
 7740:             $ressymb = $resource->symb();
 7741:         } else {
 7742:             $resource_error = 1;
 7743:             last;
 7744:         }
 7745:         my ($analysis,$parts) =
 7746:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7747:                                       $env{'user.name'},$env{'user.domain'},1);
 7748:         $grader_partids_by_symb{$ressymb} = $parts;
 7749:         if (ref($analysis) eq 'HASH') {
 7750:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7751:                 $grader_randomlists_by_symb{$ressymb} = 
 7752:                     $analysis->{'parts_withrandomlist'};
 7753:             }
 7754:         }
 7755:     }
 7756:     if ($resource_error) {
 7757:         $r->print(&navmap_errormsg());
 7758:         return '';
 7759:     }
 7760: 
 7761:     my ($uname,$udom);
 7762:     my $result= <<SCANTRONFORM;
 7763: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7764:   <input type="hidden" name="command" value="scantron_configphase" />
 7765:   $default_form_data
 7766: SCANTRONFORM
 7767:     $r->print($result);
 7768: 
 7769:     my @delayqueue;
 7770:     my (%completedstudents,%scandata);
 7771:     
 7772:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7773:     my $count=&get_todo_count($scanlines,$scan_data);
 7774:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7775:  				    'Bubblesheet Progress',$count,
 7776: 				    'inline',undef,'scantronupload');
 7777:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7778: 					  'Processing first student');
 7779:     $r->print('<br />');
 7780:     my $start=&Time::HiRes::time();
 7781:     my $i=-1;
 7782:     my $started;
 7783: 
 7784:     my $nav_error;
 7785:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7786:     if ($nav_error) {
 7787:         $r->print(&navmap_errormsg());
 7788:         return '';
 7789:     }
 7790: 
 7791:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7792:     # the user and return.
 7793: 
 7794:     if ($ssi_error) {
 7795: 	$r->print("</form>");
 7796: 	&ssi_print_error($r);
 7797: 	$r->print(&show_grading_menu_form($symb));
 7798:         &Apache::lonnet::remove_lock($lock);
 7799: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7800:     }
 7801: 
 7802:     my %lettdig = &letter_to_digits();
 7803:     my $numletts = scalar(keys(%lettdig));
 7804: 
 7805:     while ($i<$scanlines->{'count'}) {
 7806:  	($uname,$udom)=('','');
 7807:  	$i++;
 7808:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7809:  	if ($line=~/^[\s\cz]*$/) { next; }
 7810: 	if ($started) {
 7811: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7812: 						     'last student');
 7813: 	}
 7814: 	$started=1;
 7815:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7816:  						 $scan_data);
 7817:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7818:  					      \%idmap,$i)) {
 7819:   	    &scantron_add_delay(\@delayqueue,$line,
 7820:  				'Unable to find a student that matches',1);
 7821:  	    next;
 7822:   	}
 7823:  	if (exists $completedstudents{$uname}) {
 7824:  	    &scantron_add_delay(\@delayqueue,$line,
 7825:  				'Student '.$uname.' has multiple sheets',2);
 7826:  	    next;
 7827:  	}
 7828:   	($uname,$udom)=split(/:/,$uname);
 7829: 
 7830:         my (%partids_by_symb,$res_error);
 7831:         foreach my $resource (@resources) {
 7832:             my $ressymb;
 7833:             if (ref($resource)) {
 7834:                 $ressymb = $resource->symb();
 7835:             } else {
 7836:                 $res_error = 1;
 7837:                 last;
 7838:             }
 7839:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7840:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7841:                 my ($analysis,$parts) =
 7842:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7843:                 $partids_by_symb{$ressymb} = $parts;
 7844:             } else {
 7845:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7846:             }
 7847:         }
 7848: 
 7849:         if ($res_error) {
 7850:             &scantron_add_delay(\@delayqueue,$line,
 7851:                                 'An error occurred while grading student '.$uname,2);
 7852:             next;
 7853:         }
 7854: 
 7855: 	&Apache::lonxml::clear_problem_counter();
 7856:   	&Apache::lonnet::appenv($scan_record);
 7857: 
 7858: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7859: 	    &scantron_putfile($scanlines,$scan_data);
 7860: 	}
 7861: 	
 7862:         my $scancode;
 7863:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7864:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7865:             $scancode = $scan_record->{'scantron.CODE'};
 7866:         } else {
 7867:             $scancode = '';
 7868:         }
 7869: 
 7870:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7871:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7872:             $ssi_error = 0; # So end of handler error message does not trigger.
 7873:             $r->print("</form>");
 7874:             &ssi_print_error($r);
 7875:             $r->print(&show_grading_menu_form($symb));
 7876:             &Apache::lonnet::remove_lock($lock);
 7877:             return '';      # Why return ''?  Beats me.
 7878:         }
 7879: 
 7880: 	$completedstudents{$uname}={'line'=>$line};
 7881:         if ($env{'form.verifyrecord'}) {
 7882:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7883:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7884:             chomp($studentdata);
 7885:             $studentdata =~ s/\r$//;
 7886:             my $studentrecord = '';
 7887:             my $counter = -1;
 7888:             foreach my $resource (@resources) {
 7889:                 my $ressymb = $resource->symb();
 7890:                 ($counter,my $recording) =
 7891:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7892:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7893:                                              \%scantron_config,\%lettdig,$numletts);
 7894:                 $studentrecord .= $recording;
 7895:             }
 7896:             if ($studentrecord ne $studentdata) {
 7897:                 &Apache::lonxml::clear_problem_counter();
 7898:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7899:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7900:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7901:                     $r->print("</form>");
 7902:                     &ssi_print_error($r);
 7903:                     $r->print(&show_grading_menu_form($symb));
 7904:                     &Apache::lonnet::remove_lock($lock);
 7905:                     delete($completedstudents{$uname});
 7906:                     return '';
 7907:                 }
 7908:                 $counter = -1;
 7909:                 $studentrecord = '';
 7910:                 foreach my $resource (@resources) {
 7911:                     my $ressymb = $resource->symb();
 7912:                     ($counter,my $recording) =
 7913:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7914:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7915:                                                  \%scantron_config,\%lettdig,$numletts);
 7916:                     $studentrecord .= $recording;
 7917:                 }
 7918:                 if ($studentrecord ne $studentdata) {
 7919:                     $r->print('<p><span class="LC_error">');
 7920:                     if ($scancode eq '') {
 7921:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7922:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7923:                     } else {
 7924:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7925:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7926:                     }
 7927:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7928:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7929:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7930:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7931:                               &Apache::loncommon::start_data_table_row().
 7932:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7933:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7934:                               &Apache::loncommon::end_data_table_row().
 7935:                               &Apache::loncommon::start_data_table_row().
 7936:                               '<td>Stored submissions</td>'.
 7937:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7938:                               &Apache::loncommon::end_data_table_row().
 7939:                               &Apache::loncommon::end_data_table().'</p>');
 7940:                 } else {
 7941:                     $r->print('<br /><span class="LC_warning">'.
 7942:                              &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 />'.
 7943:                              &mt("As a consequence, this user's submission history records two tries.").
 7944:                                  '</span><br />');
 7945:                 }
 7946:             }
 7947:         }
 7948:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7949:     } continue {
 7950: 	&Apache::lonxml::clear_problem_counter();
 7951: 	&Apache::lonnet::delenv('scantron.');
 7952:     }
 7953:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7954:     &Apache::lonnet::remove_lock($lock);
 7955: #    my $lasttime = &Time::HiRes::time()-$start;
 7956: #    $r->print("<p>took $lasttime</p>");
 7957: 
 7958:     $r->print("</form>");
 7959:     $r->print(&show_grading_menu_form($symb));
 7960:     return '';
 7961: }
 7962: 
 7963: sub graders_resources_pass {
 7964:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7965:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7966:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7967:         foreach my $resource (@{$resources}) {
 7968:             my $ressymb = $resource->symb();
 7969:             my ($analysis,$parts) =
 7970:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7971:                                           $env{'user.name'},$env{'user.domain'},1);
 7972:             $grader_partids_by_symb->{$ressymb} = $parts;
 7973:             if (ref($analysis) eq 'HASH') {
 7974:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7975:                     $grader_randomlists_by_symb->{$ressymb} =
 7976:                         $analysis->{'parts_withrandomlist'};
 7977:                 }
 7978:             }
 7979:         }
 7980:     }
 7981:     return;
 7982: }
 7983: 
 7984: sub grade_student_bubbles {
 7985:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7986:     if (ref($resources) eq 'ARRAY') {
 7987:         my $count = 0;
 7988:         foreach my $resource (@{$resources}) {
 7989:             my $ressymb = $resource->symb();
 7990:             my %form = ('submitted'      => 'scantron',
 7991:                         'grade_target'   => 'grade',
 7992:                         'grade_username' => $uname,
 7993:                         'grade_domain'   => $udom,
 7994:                         'grade_courseid' => $env{'request.course.id'},
 7995:                         'grade_symb'     => $ressymb,
 7996:                         'CODE'           => $scancode
 7997:                        );
 7998:             if (ref($parts) eq 'HASH') {
 7999:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 8000:                     foreach my $part (@{$parts->{$ressymb}}) {
 8001:                         $form{'scantron_questnum_start.'.$part} =
 8002:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 8003:                         $count++;
 8004:                     }
 8005:                 }
 8006:             }
 8007:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 8008:             return 'ssi_error' if ($ssi_error);
 8009:             last if (&Apache::loncommon::connection_aborted($r));
 8010:         }
 8011:     }
 8012:     return;
 8013: }
 8014: 
 8015: sub scantron_upload_scantron_data {
 8016:     my ($r)=@_;
 8017:     my $dom = $env{'request.role.domain'};
 8018:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 8019:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 8020:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 8021: 							  'domainid',
 8022: 							  'coursename',$dom);
 8023:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 8024:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 8025:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8026:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 8027:     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.");
 8028:     $r->print('
 8029: <script type="text/javascript" language="javascript">
 8030:     function checkUpload(formname) {
 8031: 	if (formname.upfile.value == "") {
 8032: 	    alert("'.$nofile_alert.'");
 8033: 	    return false;
 8034: 	}
 8035:         if (formname.courseid.value == "") {
 8036:             alert("'.$nocourseid_alert.'");
 8037:             return false;
 8038:         }
 8039: 	formname.submit();
 8040:     }
 8041: 
 8042:     function ToSyllabus() {
 8043:         var cdom = '."'$dom'".';
 8044:         var cnum = document.rules.courseid.value;
 8045:         if (cdom == "" || cdom == null) {
 8046:             return;
 8047:         }
 8048:         if (cnum == "" || cnum == null) {
 8049:            return;
 8050:         }
 8051:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 8052:                             "height=350,width=350,scrollbars=yes,menubar=no");
 8053:         return;
 8054:     }
 8055: 
 8056: </script>
 8057: 
 8058: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 8059: 
 8060: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 8061: '.$default_form_data.
 8062:   &Apache::lonhtmlcommon::start_pick_box().
 8063:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 8064:   '<input name="courseid" type="text" size="30" />'.$select_link.
 8065:   &Apache::lonhtmlcommon::row_closure().
 8066:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 8067:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 8068:   &Apache::lonhtmlcommon::row_closure().
 8069:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 8070:   '<input name="domainid" type="hidden" />'.$domdesc.
 8071:   &Apache::lonhtmlcommon::row_closure().
 8072:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 8073:   '<input type="file" name="upfile" size="50" />'.
 8074:   &Apache::lonhtmlcommon::row_closure(1).
 8075:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 8076: 
 8077: <input name="command" value="scantronupload_save" type="hidden" />
 8078: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 8079: </form>
 8080: ');
 8081:     return '';
 8082: }
 8083: 
 8084: 
 8085: sub scantron_upload_scantron_data_save {
 8086:     my($r)=@_;
 8087:     my ($symb)=&get_symb($r,1);
 8088:     my $doanotherupload=
 8089: 	'<br /><form action="/adm/grades" method="post">'."\n".
 8090: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 8091: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 8092: 	'</form>'."\n";
 8093:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 8094: 	!&Apache::lonnet::allowed('usc',
 8095: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 8096: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 8097: 	if ($symb) {
 8098: 	    $r->print(&show_grading_menu_form($symb));
 8099: 	} else {
 8100: 	    $r->print($doanotherupload);
 8101: 	}
 8102: 	return '';
 8103:     }
 8104:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 8105:     my $uploadedfile;
 8106:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 8107:     if (length($env{'form.upfile'}) < 2) {
 8108:         $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>'));
 8109:     } else {
 8110:         my $result = 
 8111:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 8112:                                             $env{'form.courseid'},$env{'form.domainid'});
 8113: 	if ($result =~ m{^/uploaded/}) {
 8114: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 8115:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 8116: 			  '<span class="LC_filename">'.$result.'</span>'));
 8117:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 8118:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8119:                                                        $env{'form.courseid'},$uploadedfile));
 8120: 	} else {
 8121: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8122:                           '<span class="LC_error">','</span>',$result,
 8123: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8124: 	}
 8125:     }
 8126:     if ($symb) {
 8127: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8128:     } else {
 8129: 	$r->print($doanotherupload);
 8130:     }
 8131:     return '';
 8132: }
 8133: 
 8134: sub validate_uploaded_scantron_file {
 8135:     my ($cdom,$cname,$fname) = @_;
 8136:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8137:     my @lines;
 8138:     if ($scanlines ne '-1') {
 8139:         @lines=split("\n",$scanlines,-1);
 8140:     }
 8141:     my $output;
 8142:     if (@lines) {
 8143:         my (%counts,$max_match_format);
 8144:         my ($max_match_count,$max_match_pct) = (0,0);
 8145:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8146:         my %idmap = &username_to_idmap($classlist);
 8147:         foreach my $key (keys(%idmap)) {
 8148:             my $lckey = lc($key);
 8149:             $idmap{$lckey} = $idmap{$key};
 8150:         }
 8151:         my %unique_formats;
 8152:         my @formatlines = &get_scantronformat_file();
 8153:         foreach my $line (@formatlines) {
 8154:             chomp($line);
 8155:             my @config = split(/:/,$line);
 8156:             my $idstart = $config[5];
 8157:             my $idlength = $config[6];
 8158:             if (($idstart ne '') && ($idlength > 0)) {
 8159:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8160:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8161:                 } else {
 8162:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8163:                 }
 8164:             }
 8165:         }
 8166:         foreach my $key (keys(%unique_formats)) {
 8167:             my ($idstart,$idlength) = split(':',$key);
 8168:             %{$counts{$key}} = (
 8169:                                'found'   => 0,
 8170:                                'total'   => 0,
 8171:                               );
 8172:             foreach my $line (@lines) {
 8173:                 next if ($line =~ /^#/);
 8174:                 next if ($line =~ /^[\s\cz]*$/);
 8175:                 my $id = substr($line,$idstart-1,$idlength);
 8176:                 $id = lc($id);
 8177:                 if (exists($idmap{$id})) {
 8178:                     $counts{$key}{'found'} ++;
 8179:                 }
 8180:                 $counts{$key}{'total'} ++;
 8181:             }
 8182:             if ($counts{$key}{'total'}) {
 8183:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8184:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8185:                     $max_match_pct = $percent_match;
 8186:                     $max_match_format = $key;
 8187:                     $max_match_count = $counts{$key}{'total'};
 8188:                 }
 8189:             }
 8190:         }
 8191:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8192:             my $format_descs;
 8193:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8194:             for (my $i=0; $i<$numwithformat; $i++) {
 8195:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8196:                 if ($i<$numwithformat-2) {
 8197:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8198:                 } elsif ($i==$numwithformat-2) {
 8199:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8200:                 } elsif ($i==$numwithformat-1) {
 8201:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8202:                 }
 8203:             }
 8204:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8205:             $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).
 8206:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8207:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8208:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8209:                                   '<i>'.$cdom.'</i>').'</li>'.
 8210:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8211:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8212:                        '</ul>';
 8213:         }
 8214:     } else {
 8215:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8216:     }
 8217:     return $output;
 8218: }
 8219: 
 8220: sub valid_file {
 8221:     my ($requested_file)=@_;
 8222:     foreach my $filename (sort(&scantron_filenames())) {
 8223: 	if ($requested_file eq $filename) { return 1; }
 8224:     }
 8225:     return 0;
 8226: }
 8227: 
 8228: sub scantron_download_scantron_data {
 8229:     my ($r)=@_;
 8230:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8233:     my $file=$env{'form.scantron_selectfile'};
 8234:     if (! &valid_file($file)) {
 8235: 	$r->print('
 8236: 	<p>
 8237: 	    '.&mt('The requested file name was invalid.').'
 8238:         </p>
 8239: ');
 8240: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8241: 	return;
 8242:     }
 8243:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8244:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8245:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8246:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8247:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8248:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8249:     $r->print('
 8250:     <p>
 8251: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8252: 	      '<a href="'.$orig.'">','</a>').'
 8253:     </p>
 8254:     <p>
 8255: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8256: 	      '<a href="'.$corrected.'">','</a>').'
 8257:     </p>
 8258:     <p>
 8259: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8260: 	      '<a href="'.$skipped.'">','</a>').'
 8261:     </p>
 8262: ');
 8263:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8264:     return '';
 8265: }
 8266: 
 8267: sub checkscantron_results {
 8268:     my ($r) = @_;
 8269:     my ($symb)=&get_symb($r);
 8270:     if (!$symb) {return '';}
 8271:     my $grading_menu_button=&show_grading_menu_form($symb);
 8272:     my $cid = $env{'request.course.id'};
 8273:     my %lettdig = &letter_to_digits();
 8274:     my $numletts = scalar(keys(%lettdig));
 8275:     my $cnum = $env{'course.'.$cid.'.num'};
 8276:     my $cdom = $env{'course.'.$cid.'.domain'};
 8277:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8278:     my %record;
 8279:     my %scantron_config =
 8280:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8281:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8282:     my $classlist=&Apache::loncoursedata::get_classlist();
 8283:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8284:     my $navmap=Apache::lonnavmaps::navmap->new();
 8285:     unless (ref($navmap)) {
 8286:         $r->print(&navmap_errormsg());
 8287:         return '';
 8288:     }
 8289:     my $map=$navmap->getResourceByUrl($sequence);
 8290:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8291:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8292:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8293: 
 8294:     my ($uname,$udom);
 8295:     my (%scandata,%lastname,%bylast);
 8296:     $r->print('
 8297: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8298: 
 8299:     my @delayqueue;
 8300:     my %completedstudents;
 8301: 
 8302:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8303:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8304:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8305:                                     'inline',undef,'checkscantron');
 8306:     my ($username,$domain,$started);
 8307:     my $nav_error;
 8308:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8309:     if ($nav_error) {
 8310:         $r->print(&navmap_errormsg());
 8311:         return '';
 8312:     }
 8313: 
 8314:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8315:                                           'Processing first student');
 8316:     my $start=&Time::HiRes::time();
 8317:     my $i=-1;
 8318: 
 8319:     while ($i<$scanlines->{'count'}) {
 8320:         ($username,$domain,$uname)=('','','');
 8321:         $i++;
 8322:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8323:         if ($line=~/^[\s\cz]*$/) { next; }
 8324:         if ($started) {
 8325:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8326:                                                      'last student');
 8327:         }
 8328:         $started=1;
 8329:         my $scan_record=
 8330:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8331:                                                      $scan_data);
 8332:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8333:                                                               \%idmap,$i)) {
 8334:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8335:                                 'Unable to find a student that matches',1);
 8336:             next;
 8337:         }
 8338:         if (exists $completedstudents{$uname}) {
 8339:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8340:                                 'Student '.$uname.' has multiple sheets',2);
 8341:             next;
 8342:         }
 8343:         my $pid = $scan_record->{'scantron.ID'};
 8344:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8345:         push(@{$bylast{$lastname{$pid}}},$pid);
 8346:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8347:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8348:         chomp($scandata{$pid});
 8349:         $scandata{$pid} =~ s/\r$//;
 8350:         ($username,$domain)=split(/:/,$uname);
 8351:         my $counter = -1;
 8352:         foreach my $resource (@resources) {
 8353:             my $parts;
 8354:             my $ressymb = $resource->symb();
 8355:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8356:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8357:                 (my $analysis,$parts) =
 8358:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8359:             } else {
 8360:                 $parts = $grader_partids_by_symb{$ressymb};
 8361:             }
 8362:             ($counter,my $recording) =
 8363:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8364:                                          $scandata{$pid},$parts,
 8365:                                          \%scantron_config,\%lettdig,$numletts);
 8366:             $record{$pid} .= $recording;
 8367:         }
 8368:     }
 8369:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8370:     $r->print('<br />');
 8371:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8372:     $passed = 0;
 8373:     $failed = 0;
 8374:     $numstudents = 0;
 8375:     foreach my $last (sort(keys(%bylast))) {
 8376:         if (ref($bylast{$last}) eq 'ARRAY') {
 8377:             foreach my $pid (sort(@{$bylast{$last}})) {
 8378:                 my $showscandata = $scandata{$pid};
 8379:                 my $showrecord = $record{$pid};
 8380:                 $showscandata =~ s/\s/&nbsp;/g;
 8381:                 $showrecord =~ s/\s/&nbsp;/g;
 8382:                 if ($scandata{$pid} eq $record{$pid}) {
 8383:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8384:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8385: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8386: '</tr>'."\n".
 8387: '<tr class="'.$css_class.'">'."\n".
 8388: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8389:                     $passed ++;
 8390:                 } else {
 8391:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8392:                     $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".
 8393: '</tr>'."\n".
 8394: '<tr class="'.$css_class.'">'."\n".
 8395: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8396: '</tr>'."\n";
 8397:                     $failed ++;
 8398:                 }
 8399:                 $numstudents ++;
 8400:             }
 8401:         }
 8402:     }
 8403:     $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>');
 8404:     $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>');
 8405:     if ($passed) {
 8406:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8407:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8408:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8409:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8410:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8411:                  $okstudents."\n".
 8412:                  &Apache::loncommon::end_data_table().'<br />');
 8413:     }
 8414:     if ($failed) {
 8415:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8416:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8417:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8418:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8419:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8420:                  $badstudents."\n".
 8421:                  &Apache::loncommon::end_data_table()).'<br />'.
 8422:                  &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.');  
 8423:     }
 8424:     $r->print('</form><br />'.$grading_menu_button);
 8425:     return;
 8426: }
 8427: 
 8428: sub verify_scantron_grading {
 8429:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8430:         $scantron_config,$lettdig,$numletts) = @_;
 8431:     my ($record,%expected,%startpos);
 8432:     return ($counter,$record) if (!ref($resource));
 8433:     return ($counter,$record) if (!$resource->is_problem());
 8434:     my $symb = $resource->symb();
 8435:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8436:     foreach my $part_id (@{$partids}) {
 8437:         $counter ++;
 8438:         $expected{$part_id} = 0;
 8439:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8440:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8441:             foreach my $item (@sub_lines) {
 8442:                 $expected{$part_id} += $item;
 8443:             }
 8444:         } else {
 8445:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8446:         }
 8447:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8448:     }
 8449:     if ($symb) {
 8450:         my %recorded;
 8451:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8452:         if ($returnhash{'version'}) {
 8453:             my %lasthash=();
 8454:             my $version;
 8455:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8456:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8457:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8458:                 }
 8459:             }
 8460:             foreach my $key (keys(%lasthash)) {
 8461:                 if ($key =~ /\.scantron$/) {
 8462:                     my $value = &unescape($lasthash{$key});
 8463:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8464:                     if ($value eq '') {
 8465:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8466:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8467:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8468:                             }
 8469:                         }
 8470:                     } else {
 8471:                         my @tocheck;
 8472:                         my @items = split(//,$value);
 8473:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8474:                             ($scantron_config->{'Qon'} eq 'number')) {
 8475:                             if (@items < $expected{$part_id}) {
 8476:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8477:                                 my @singles = split(//,$fragment);
 8478:                                 foreach my $pos (@singles) {
 8479:                                     if ($pos eq ' ') {
 8480:                                         push(@tocheck,$pos);
 8481:                                     } else {
 8482:                                         my $next = shift(@items);
 8483:                                         push(@tocheck,$next);
 8484:                                     }
 8485:                                 }
 8486:                             } else {
 8487:                                 @tocheck = @items;
 8488:                             }
 8489:                             foreach my $letter (@tocheck) {
 8490:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8491:                                     if ($letter !~ /^[A-J]$/) {
 8492:                                         $letter = $scantron_config->{'Qoff'};
 8493:                                     }
 8494:                                     $recorded{$part_id} .= $letter;
 8495:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8496:                                     my $digit;
 8497:                                     if ($letter !~ /^[A-J]$/) {
 8498:                                         $digit = $scantron_config->{'Qoff'};
 8499:                                     } else {
 8500:                                         $digit = $lettdig->{$letter};
 8501:                                     }
 8502:                                     $recorded{$part_id} .= $digit;
 8503:                                 }
 8504:                             }
 8505:                         } else {
 8506:                             @tocheck = @items;
 8507:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8508:                                 my $curr_sub = shift(@tocheck);
 8509:                                 my $digit;
 8510:                                 if ($curr_sub =~ /^[A-J]$/) {
 8511:                                     $digit = $lettdig->{$curr_sub}-1;
 8512:                                 }
 8513:                                 if ($curr_sub eq 'J') {
 8514:                                     $digit += scalar($numletts);
 8515:                                 }
 8516:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8517:                                     if ($j == $digit) {
 8518:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8519:                                     } else {
 8520:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8521:                                     }
 8522:                                 }
 8523:                             }
 8524:                         }
 8525:                     }
 8526:                 }
 8527:             }
 8528:         }
 8529:         foreach my $part_id (@{$partids}) {
 8530:             if ($recorded{$part_id} eq '') {
 8531:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8532:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8533:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8534:                     }
 8535:                 }
 8536:             }
 8537:             $record .= $recorded{$part_id};
 8538:         }
 8539:     }
 8540:     return ($counter,$record);
 8541: }
 8542: 
 8543: sub letter_to_digits { 
 8544:     my %lettdig = (
 8545:                     A => 1,
 8546:                     B => 2,
 8547:                     C => 3,
 8548:                     D => 4,
 8549:                     E => 5,
 8550:                     F => 6,
 8551:                     G => 7,
 8552:                     H => 8,
 8553:                     I => 9,
 8554:                     J => 0,
 8555:                   );
 8556:     return %lettdig;
 8557: }
 8558: 
 8559: 
 8560: #-------- end of section for handling grading scantron forms -------
 8561: #
 8562: #-------------------------------------------------------------------
 8563: 
 8564: #-------------------------- Menu interface -------------------------
 8565: #
 8566: #--- Show a Grading Menu button - Calls the next routine ---
 8567: sub show_grading_menu_form {
 8568:     my ($symb)=@_;
 8569:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8570: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8571: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8572: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8573: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8574: 	'</form>'."\n";
 8575:     return $result;
 8576: }
 8577: 
 8578: # -- Retrieve choices for grading form
 8579: sub savedState {
 8580:     my %savedState = ();
 8581:     if ($env{'form.saveState'}) {
 8582: 	foreach (split(/:/,$env{'form.saveState'})) {
 8583: 	    my ($key,$value) = split(/=/,$_,2);
 8584: 	    $savedState{$key} = $value;
 8585: 	}
 8586:     }
 8587:     return \%savedState;
 8588: }
 8589: 
 8590: sub grading_menu {
 8591:     my ($request) = @_;
 8592:     my ($symb)=&get_symb($request);
 8593:     if (!$symb) {return '';}
 8594:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8595:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8596: 
 8597:     $request->print($table);
 8598:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8599:                   'handgrade'=>$hdgrade,
 8600:                   'probTitle'=>$probTitle,
 8601:                   'command'=>'submit_options',
 8602:                   'saveState'=>"",
 8603:                   'gradingMenu'=>1,
 8604:                   'showgrading'=>"yes");
 8605:     
 8606:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8607:     
 8608:     $fields{'command'} = 'csvform';
 8609:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8610:     
 8611:     $fields{'command'} = 'processclicker';
 8612:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8613:     
 8614:     $fields{'command'} = 'scantron_selectphase';
 8615:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8616:     
 8617:     my @menu = ({	categorytitle=>'Course Grading',
 8618:             items =>[
 8619:                         {	linktext => 'Manual Grading/View Submissions',
 8620:                     		url => $url1,
 8621:                     		permission => 'F',
 8622:                     		icon => 'edit-find-replace.png',
 8623:                     		linktitle => 'Start the process of hand grading submissions.'
 8624:                         },
 8625:                 	    {	linktext => 'Upload Scores',
 8626:                     		url => $url2,
 8627:                     		permission => 'F',
 8628:                     		icon => 'uploadscores.png',
 8629:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8630:                 	    },
 8631:                 	    {	linktext => 'Process Clicker',
 8632:                     		url => $url3,
 8633:                     		permission => 'F',
 8634:                     		icon => 'addClickerInfoFile.png',
 8635:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8636:                 	    },
 8637:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8638:                     		url => $url4,
 8639:                     		permission => 'F',
 8640:                     		icon => 'stat.png',
 8641:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8642:                 	    }
 8643:                     ]
 8644:             });
 8645: 
 8646:     #$fields{'command'} = 'verify';
 8647:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8648:     #
 8649:     # Create the menu
 8650:     my $Str;
 8651:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8652:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8653:     $Str .= '<input type="hidden" name="command" value="" />'.
 8654:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8655: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8656: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8657: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8658: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8659: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8660: 
 8661:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8662:     #$menudata->{'jscript'}
 8663:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8664:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8665:         ' /> '.
 8666:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8667:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8668: 
 8669:     $Str .="</form>\n";
 8670:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8671:     $request->print(<<GRADINGMENUJS);
 8672: <script type="text/javascript" language="javascript">
 8673:     function checkChoice(formname,val,cmdx) {
 8674: 	if (val <= 2) {
 8675: 	    var cmd = radioSelection(formname.radioChoice);
 8676: 	    var cmdsave = cmd;
 8677: 	} else {
 8678: 	    cmd = cmdx;
 8679: 	    cmdsave = 'submission';
 8680: 	}
 8681: 	formname.command.value = cmd;
 8682: 	if (val < 5) formname.submit();
 8683: 	if (val == 5) {
 8684: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8685: 	        return false;
 8686: 	    } else {
 8687: 	        formname.submit();
 8688: 	    }
 8689: 	}
 8690:     }
 8691: 
 8692:     function checkReceiptNo(formname,nospace) {
 8693: 	var receiptNo = formname.receipt.value;
 8694: 	var checkOpt = false;
 8695: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8696: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8697: 	if (checkOpt) {
 8698: 	    alert("$receiptalert");
 8699: 	    formname.receipt.value = "";
 8700: 	    formname.receipt.focus();
 8701: 	    return false;
 8702: 	}
 8703: 	return true;
 8704:     }
 8705: </script>
 8706: GRADINGMENUJS
 8707:     &commonJSfunctions($request);
 8708:     return $Str;    
 8709: }
 8710: 
 8711: 
 8712: #--- Displays the submissions first page -------
 8713: sub submit_options {
 8714:     my ($request) = @_;
 8715:     my ($symb)=&get_symb($request);
 8716:     if (!$symb) {return '';}
 8717:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8718: 
 8719:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8720:     $request->print(<<GRADINGMENUJS);
 8721: <script type="text/javascript" language="javascript">
 8722:     function checkChoice(formname,val,cmdx) {
 8723: 	if (val <= 2) {
 8724: 	    var cmd = radioSelection(formname.radioChoice);
 8725: 	    var cmdsave = cmd;
 8726: 	} else {
 8727: 	    cmd = cmdx;
 8728: 	    cmdsave = 'submission';
 8729: 	}
 8730: 	formname.command.value = cmd;
 8731: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8732: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8733: 	if (val < 5) formname.submit();
 8734: 	if (val == 5) {
 8735: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8736: 	    formname.submit();
 8737: 	}
 8738: 	if (val < 7) formname.submit();
 8739:     }
 8740: 
 8741:     function checkReceiptNo(formname,nospace) {
 8742: 	var receiptNo = formname.receipt.value;
 8743: 	var checkOpt = false;
 8744: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8745: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8746: 	if (checkOpt) {
 8747: 	    alert("$receiptalert");
 8748: 	    formname.receipt.value = "";
 8749: 	    formname.receipt.focus();
 8750: 	    return false;
 8751: 	}
 8752: 	return true;
 8753:     }
 8754: </script>
 8755: GRADINGMENUJS
 8756:     &commonJSfunctions($request);
 8757:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8758:     my $result;
 8759:     my (undef,$sections) = &getclasslist('all','0');
 8760:     my $savedState = &savedState();
 8761:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8762:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8763:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8764:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8765: 
 8766:     # Preselect sections
 8767:     my $selsec="";
 8768:     if (ref($sections)) {
 8769:         foreach my $section (sort(@$sections)) {
 8770:             $selsec.='<option value="'.$section.'" '.
 8771:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8772:         }
 8773:     }
 8774: 
 8775:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8776: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8777: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8778: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8779: 	'<input type="hidden" name="command"     value="" />'."\n".
 8780: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8781: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8782: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8783: 
 8784:     $result.='
 8785: <h2>
 8786:   '.&mt('Grade Current Resource').'
 8787: </h2>
 8788: <div>
 8789:   '.$table.'
 8790: </div>
 8791: 
 8792: <div class="LC_columnSection">
 8793:   
 8794:     <fieldset>
 8795:       <legend>
 8796:        '.&mt('Sections').'
 8797:       </legend>
 8798:       <select name="section" multiple="multiple" size="5">'."\n";
 8799:     $result.= $selsec;
 8800:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8801:     $result.='
 8802:     </fieldset>
 8803:   
 8804:     <fieldset>
 8805:       <legend>
 8806:         '.&mt('Groups').'
 8807:       </legend>
 8808:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8809:     </fieldset>
 8810:   
 8811:     <fieldset>
 8812:       <legend>
 8813:         '.&mt('Access Status').'
 8814:       </legend>
 8815:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8816:     </fieldset>
 8817:   
 8818:     <fieldset>
 8819:       <legend>
 8820:         '.&mt('Submission Status').'
 8821:       </legend>
 8822:       <select name="submitonly" size="5">
 8823: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8824: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8825: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8826: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8827:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8828:       </select>
 8829:     </fieldset>
 8830:   
 8831: </div>
 8832: 
 8833: <br />
 8834:           <div>
 8835:             <div>
 8836:               <label>
 8837:                 <input type="radio" name="radioChoice" value="submission" '.
 8838:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8839:              &mt('Select individual students to grade and view submissions.').'
 8840: 	      </label> 
 8841:             </div>
 8842:             <div>
 8843: 	      <label>
 8844:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8845:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8846:                     &mt('Grade all selected students in a grading table.').'
 8847:               </label>
 8848:             </div>
 8849:             <div>
 8850: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8851:             </div>
 8852:           </div>
 8853: 
 8854: 
 8855:         <h2>
 8856:          '.&mt('Grade Complete Folder for One Student').'
 8857:         </h2>
 8858:         <div>
 8859:             <div>
 8860:               <label>
 8861:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8862: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8863:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8864:               </label>
 8865:             </div>
 8866:             <div>
 8867: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8868:             </div>
 8869:         </div>
 8870:   </form>';
 8871:     $result .= &show_grading_menu_form($symb);
 8872:     return $result;
 8873: }
 8874: 
 8875: sub reset_perm {
 8876:     undef(%perm);
 8877: }
 8878: 
 8879: sub init_perm {
 8880:     &reset_perm();
 8881:     foreach my $test_perm ('vgr','mgr','opa') {
 8882: 
 8883: 	my $scope = $env{'request.course.id'};
 8884: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8885: 
 8886: 	    $scope .= '/'.$env{'request.course.sec'};
 8887: 	    if ( $perm{$test_perm}=
 8888: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8889: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8890: 	    } else {
 8891: 		delete($perm{$test_perm});
 8892: 	    }
 8893: 	}
 8894:     }
 8895: }
 8896: 
 8897: sub gather_clicker_ids {
 8898:     my %clicker_ids;
 8899: 
 8900:     my $classlist = &Apache::loncoursedata::get_classlist();
 8901: 
 8902:     # Set up a couple variables.
 8903:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8904:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8905:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8906: 
 8907:     foreach my $student (keys(%$classlist)) {
 8908:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8909:         my $username = $classlist->{$student}->[$username_idx];
 8910:         my $domain   = $classlist->{$student}->[$domain_idx];
 8911:         my $clickers =
 8912: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8913:         foreach my $id (split(/\,/,$clickers)) {
 8914:             $id=~s/^[\#0]+//;
 8915:             $id=~s/[\-\:]//g;
 8916:             if (exists($clicker_ids{$id})) {
 8917: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8918:             } else {
 8919: 		$clicker_ids{$id}=$username.':'.$domain;
 8920:             }
 8921:         }
 8922:     }
 8923:     return %clicker_ids;
 8924: }
 8925: 
 8926: sub gather_adv_clicker_ids {
 8927:     my %clicker_ids;
 8928:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8930:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8931:     foreach my $element (sort(keys(%coursepersonnel))) {
 8932:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8933:             my ($puname,$pudom)=split(/\:/,$person);
 8934:             my $clickers =
 8935: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8936:             foreach my $id (split(/\,/,$clickers)) {
 8937: 		$id=~s/^[\#0]+//;
 8938:                 $id=~s/[\-\:]//g;
 8939: 		if (exists($clicker_ids{$id})) {
 8940: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8941: 		} else {
 8942: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8943: 		}
 8944:             }
 8945:         }
 8946:     }
 8947:     return %clicker_ids;
 8948: }
 8949: 
 8950: sub clicker_grading_parameters {
 8951:     return ('gradingmechanism' => 'scalar',
 8952:             'upfiletype' => 'scalar',
 8953:             'specificid' => 'scalar',
 8954:             'pcorrect' => 'scalar',
 8955:             'pincorrect' => 'scalar');
 8956: }
 8957: 
 8958: sub process_clicker {
 8959:     my ($r)=@_;
 8960:     my ($symb)=&get_symb($r);
 8961:     if (!$symb) {return '';}
 8962:     my $result=&checkforfile_js();
 8963:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8964:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8965:     $result.=$table;
 8966:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8967:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8968:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8969:         '</b></td></tr>'."\n";
 8970:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8971: # Attempt to restore parameters from last session, set defaults if not present
 8972:     my %Saveable_Parameters=&clicker_grading_parameters();
 8973:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8974:                                                  \%Saveable_Parameters);
 8975:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8976:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8977:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8978:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8979: 
 8980:     my %checked;
 8981:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8982:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8983:           $checked{$gradingmechanism}=' checked="checked"';
 8984:        }
 8985:     }
 8986: 
 8987:     my $upload=&mt("Upload File");
 8988:     my $type=&mt("Type");
 8989:     my $attendance=&mt("Award points just for participation");
 8990:     my $personnel=&mt("Correctness determined from response by course personnel");
 8991:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8992:     my $given=&mt("Correctness determined from given list of answers").' '.
 8993:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8994:     my $pcorrect=&mt("Percentage points for correct solution");
 8995:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8996:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8997:                                                    {'iclicker' => 'i>clicker',
 8998:                                                     'interwrite' => 'interwrite PRS'});
 8999:     $symb = &Apache::lonenc::check_encrypt($symb);
 9000:     $result.=<<ENDUPFORM;
 9001: <script type="text/javascript">
 9002: function sanitycheck() {
 9003: // Accept only integer percentages
 9004:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 9005:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 9006: // Find out grading choice
 9007:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9008:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 9009:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 9010:       }
 9011:    }
 9012: // By default, new choice equals user selection
 9013:    newgradingchoice=gradingchoice;
 9014: // Not good to give more points for false answers than correct ones
 9015:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 9016:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 9017:    }
 9018: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 9019:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 9020:       document.forms.gradesupload.pcorrect.value=100;
 9021:       document.forms.gradesupload.pincorrect.value=100;
 9022:    }
 9023: // If the values are different, cannot be attendance only
 9024:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 9025:        (gradingchoice=='attendance')) {
 9026:        newgradingchoice='personnel';
 9027:    }
 9028: // Change grading choice to new one
 9029:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 9030:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 9031:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 9032:       } else {
 9033:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 9034:       }
 9035:    }
 9036: // Remember the old state
 9037:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 9038: }
 9039: </script>
 9040: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 9041: <input type="hidden" name="symb" value="$symb" />
 9042: <input type="hidden" name="command" value="processclickerfile" />
 9043: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9044: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9045: <input type="file" name="upfile" size="50" />
 9046: <br /><label>$type: $selectform</label>
 9047: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
 9048: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
 9049: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
 9050: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 9051: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
 9052: <br />&nbsp;&nbsp;&nbsp;
 9053: <input type="text" name="givenanswer" size="50" />
 9054: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 9055: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
 9056: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
 9057: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
 9058: </form>
 9059: ENDUPFORM
 9060:     $result.='</td></tr></table>'."\n".
 9061:              '</td></tr></table><br /><br />'."\n";
 9062:     $result.=&show_grading_menu_form($symb);
 9063:     return $result;
 9064: }
 9065: 
 9066: sub process_clicker_file {
 9067:     my ($r)=@_;
 9068:     my ($symb)=&get_symb($r);
 9069:     if (!$symb) {return '';}
 9070: 
 9071:     my %Saveable_Parameters=&clicker_grading_parameters();
 9072:     &Apache::loncommon::store_course_settings('grades_clicker',
 9073:                                               \%Saveable_Parameters);
 9074: 
 9075:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9076:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 9077: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 9078: 	return $result.&show_grading_menu_form($symb);
 9079:     }
 9080:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 9081:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 9082:         return $result.&show_grading_menu_form($symb);
 9083:     }
 9084:     my $foundgiven=0;
 9085:     if ($env{'form.gradingmechanism'} eq 'given') {
 9086:         $env{'form.givenanswer'}=~s/^\s*//gs;
 9087:         $env{'form.givenanswer'}=~s/\s*$//gs;
 9088:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 9089:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 9090:         my @answers=split(/\,/,$env{'form.givenanswer'});
 9091:         $foundgiven=$#answers+1;
 9092:     }
 9093:     my %clicker_ids=&gather_clicker_ids();
 9094:     my %correct_ids;
 9095:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 9096: 	%correct_ids=&gather_adv_clicker_ids();
 9097:     }
 9098:     if ($env{'form.gradingmechanism'} eq 'specific') {
 9099: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 9100: 	   $correct_id=~tr/a-z/A-Z/;
 9101: 	   $correct_id=~s/\s//gs;
 9102: 	   $correct_id=~s/^[\#0]+//;
 9103:            $correct_id=~s/[\-\:]//g;
 9104:            if ($correct_id) {
 9105: 	      $correct_ids{$correct_id}='specified';
 9106:            }
 9107:         }
 9108:     }
 9109:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 9110: 	$result.=&mt('Score based on attendance only');
 9111:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 9112:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 9113:     } else {
 9114: 	my $number=0;
 9115: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 9116: 	foreach my $id (sort(keys(%correct_ids))) {
 9117: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 9118: 	    if ($correct_ids{$id} eq 'specified') {
 9119: 		$result.=&mt('specified');
 9120: 	    } else {
 9121: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9122: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9123: 	    }
 9124: 	    $number++;
 9125: 	}
 9126:         $result.="</p>\n";
 9127: 	if ($number==0) {
 9128: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9129: 	    return $result.&show_grading_menu_form($symb);
 9130: 	}
 9131:     }
 9132:     if (length($env{'form.upfile'}) < 2) {
 9133:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9134: 		     '<span class="LC_error">',
 9135: 		     '</span>',
 9136: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9137:         return $result.&show_grading_menu_form($symb);
 9138:     }
 9139: 
 9140: # Were able to get all the info needed, now analyze the file
 9141: 
 9142:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9143:     $symb = &Apache::lonenc::check_encrypt($symb);
 9144:     my $heading=&mt('Scanning clicker file');
 9145:     $result.=(<<ENDHEADER);
 9146: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9147: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9148: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9149: <form method="post" action="/adm/grades" name="clickeranalysis">
 9150: <input type="hidden" name="symb" value="$symb" />
 9151: <input type="hidden" name="command" value="assignclickergrades" />
 9152: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9153: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9154: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9155: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9156: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9157: ENDHEADER
 9158:     if ($env{'form.gradingmechanism'} eq 'given') {
 9159:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9160:     } 
 9161:     my %responses;
 9162:     my @questiontitles;
 9163:     my $errormsg='';
 9164:     my $number=0;
 9165:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9166: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9167:     }
 9168:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9169:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9170:     }
 9171:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9172:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9173:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9174:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9175:              '<br />';
 9176:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9177:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9178:        return $result.&show_grading_menu_form($symb);
 9179:     } 
 9180: # Remember Question Titles
 9181: # FIXME: Possibly need delimiter other than ":"
 9182:     for (my $i=0;$i<$number;$i++) {
 9183:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9184:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9185:     }
 9186:     my $correct_count=0;
 9187:     my $student_count=0;
 9188:     my $unknown_count=0;
 9189: # Match answers with usernames
 9190: # FIXME: Possibly need delimiter other than ":"
 9191:     foreach my $id (keys(%responses)) {
 9192:        if ($correct_ids{$id}) {
 9193:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9194:           $correct_count++;
 9195:        } elsif ($clicker_ids{$id}) {
 9196:           if ($clicker_ids{$id}=~/\,/) {
 9197: # More than one user with the same clicker!
 9198:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9199:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9200:                            "<select name='multi".$id."'>";
 9201:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9202:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9203:              }
 9204:              $result.='</select>';
 9205:              $unknown_count++;
 9206:           } else {
 9207: # Good: found one and only one user with the right clicker
 9208:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9209:              $student_count++;
 9210:           }
 9211:        } else {
 9212:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9213:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9214:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9215:                    "\n".&mt("Domain").": ".
 9216:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9217:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9218:           $unknown_count++;
 9219:        }
 9220:     }
 9221:     $result.='<hr />'.
 9222:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9223:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9224:        if ($correct_count==0) {
 9225:           $errormsg.="Found no correct answers answers for grading!";
 9226:        } elsif ($correct_count>1) {
 9227:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9228:        }
 9229:     }
 9230:     if ($number<1) {
 9231:        $errormsg.="Found no questions.";
 9232:     }
 9233:     if ($errormsg) {
 9234:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9235:     } else {
 9236:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9237:     }
 9238:     $result.='</form></td></tr></table>'."\n".
 9239:              '</td></tr></table><br /><br />'."\n";
 9240:     return $result.&show_grading_menu_form($symb);
 9241: }
 9242: 
 9243: sub iclicker_eval {
 9244:     my ($questiontitles,$responses)=@_;
 9245:     my $number=0;
 9246:     my $errormsg='';
 9247:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9248:         my %components=&Apache::loncommon::record_sep($line);
 9249:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9250: 	if ($entries[0] eq 'Question') {
 9251: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9252: 		$$questiontitles[$number]=$entries[$i];
 9253: 		$number++;
 9254: 	    }
 9255: 	}
 9256: 	if ($entries[0]=~/^\#/) {
 9257: 	    my $id=$entries[0];
 9258: 	    my @idresponses;
 9259: 	    $id=~s/^[\#0]+//;
 9260: 	    for (my $i=0;$i<$number;$i++) {
 9261: 		my $idx=3+$i*6;
 9262: 		push(@idresponses,$entries[$idx]);
 9263: 	    }
 9264: 	    $$responses{$id}=join(',',@idresponses);
 9265: 	}
 9266:     }
 9267:     return ($errormsg,$number);
 9268: }
 9269: 
 9270: sub interwrite_eval {
 9271:     my ($questiontitles,$responses)=@_;
 9272:     my $number=0;
 9273:     my $errormsg='';
 9274:     my $skipline=1;
 9275:     my $questionnumber=0;
 9276:     my %idresponses=();
 9277:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9278:         my %components=&Apache::loncommon::record_sep($line);
 9279:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9280:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9281:         if ($entries[1] eq 'Response') { $skipline=1; }
 9282:         next if $skipline;
 9283:         if ($entries[0]!=$questionnumber) {
 9284:            $questionnumber=$entries[0];
 9285:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9286:            $number++;
 9287:         }
 9288:         my $id=$entries[4];
 9289:         $id=~s/^[\#0]+//;
 9290:         $id=~s/^v\d*\://i;
 9291:         $id=~s/[\-\:]//g;
 9292:         $idresponses{$id}[$number]=$entries[6];
 9293:     }
 9294:     foreach my $id (keys(%idresponses)) {
 9295:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9296:        $$responses{$id}=~s/^\s*\,//;
 9297:     }
 9298:     return ($errormsg,$number);
 9299: }
 9300: 
 9301: sub assign_clicker_grades {
 9302:     my ($r)=@_;
 9303:     my ($symb)=&get_symb($r);
 9304:     if (!$symb) {return '';}
 9305: # See which part we are saving to
 9306:     my $res_error;
 9307:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9308:     if ($res_error) {
 9309:         return &navmap_errormsg();
 9310:     }
 9311: # FIXME: This should probably look for the first handgradeable part
 9312:     my $part=$$partlist[0];
 9313: # Start screen output
 9314:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9315: 
 9316:     my $heading=&mt('Assigning grades based on clicker file');
 9317:     $result.=(<<ENDHEADER);
 9318: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9319: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9320: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9321: ENDHEADER
 9322: # Get correct result
 9323: # FIXME: Possibly need delimiter other than ":"
 9324:     my @correct=();
 9325:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9326:     my $number=$env{'form.number'};
 9327:     if ($gradingmechanism ne 'attendance') {
 9328:        foreach my $key (keys(%env)) {
 9329:           if ($key=~/^form\.correct\:/) {
 9330:              my @input=split(/\,/,$env{$key});
 9331:              for (my $i=0;$i<=$#input;$i++) {
 9332:                  if (($correct[$i]) && ($input[$i]) &&
 9333:                      ($correct[$i] ne $input[$i])) {
 9334:                     $result.='<br /><span class="LC_warning">'.
 9335:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9336:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9337:                  } elsif ($input[$i]) {
 9338:                     $correct[$i]=$input[$i];
 9339:                  }
 9340:              }
 9341:           }
 9342:        }
 9343:        for (my $i=0;$i<$number;$i++) {
 9344:           if (!$correct[$i]) {
 9345:              $result.='<br /><span class="LC_error">'.
 9346:                       &mt('No correct result given for question "[_1]"!',
 9347:                           $env{'form.question:'.$i}).'</span>';
 9348:           }
 9349:        }
 9350:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9351:     }
 9352: # Start grading
 9353:     my $pcorrect=$env{'form.pcorrect'};
 9354:     my $pincorrect=$env{'form.pincorrect'};
 9355:     my $storecount=0;
 9356:     foreach my $key (keys(%env)) {
 9357:        my $user='';
 9358:        if ($key=~/^form\.student\:(.*)$/) {
 9359:           $user=$1;
 9360:        }
 9361:        if ($key=~/^form\.unknown\:(.*)$/) {
 9362:           my $id=$1;
 9363:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9364:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9365:           } elsif ($env{'form.multi'.$id}) {
 9366:              $user=$env{'form.multi'.$id};
 9367:           }
 9368:        }
 9369:        if ($user) { 
 9370:           my @answer=split(/\,/,$env{$key});
 9371:           my $sum=0;
 9372:           my $realnumber=$number;
 9373:           for (my $i=0;$i<$number;$i++) {
 9374:              if  ($correct[$i] eq '-') {
 9375:                 $realnumber--;
 9376:              } elsif ($answer[$i]) {
 9377:                 if ($gradingmechanism eq 'attendance') {
 9378:                    $sum+=$pcorrect;
 9379:                 } elsif ($correct[$i] eq '*') {
 9380:                    $sum+=$pcorrect;
 9381:                 } else {
 9382:                    if ($answer[$i] eq $correct[$i]) {
 9383:                       $sum+=$pcorrect;
 9384:                    } else {
 9385:                       $sum+=$pincorrect;
 9386:                    }
 9387:                 }
 9388:              }
 9389:           }
 9390:           my $ave=$sum/(100*$realnumber);
 9391: # Store
 9392:           my ($username,$domain)=split(/\:/,$user);
 9393:           my %grades=();
 9394:           $grades{"resource.$part.solved"}='correct_by_override';
 9395:           $grades{"resource.$part.awarded"}=$ave;
 9396:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9397:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9398:                                                  $env{'request.course.id'},
 9399:                                                  $domain,$username);
 9400:           if ($returncode ne 'ok') {
 9401:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9402:           } else {
 9403:              $storecount++;
 9404:           }
 9405:        }
 9406:     }
 9407: # We are done
 9408:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9409:              '</td></tr></table>'."\n".
 9410:              '</td></tr></table><br /><br />'."\n";
 9411:     return $result.&show_grading_menu_form($symb);
 9412: }
 9413: 
 9414: sub navmap_errormsg {
 9415:     return '<div class="LC_error">'.
 9416:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9417:            &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>').
 9418:            '</div>';
 9419: }
 9420: 
 9421: sub handler {
 9422:     my $request=$_[0];
 9423:     &reset_caches();
 9424:     if ($env{'browser.mathml'}) {
 9425: 	&Apache::loncommon::content_type($request,'text/xml');
 9426:     } else {
 9427: 	&Apache::loncommon::content_type($request,'text/html');
 9428:     }
 9429:     $request->send_http_header;
 9430:     return '' if $request->header_only;
 9431:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9432:     my $symb=&get_symb($request,1);
 9433:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9434:     my $command=$commands[0];
 9435: 
 9436:     if ($#commands > 0) {
 9437: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9438:     }
 9439: 
 9440:     $ssi_error = 0;
 9441:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9442:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9443:                                           {'bread_crumbs' => $brcrum}));
 9444:     if ($symb eq '' && $command eq '') {
 9445: 	if ($env{'user.adv'}) {
 9446: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9447: 		($env{'form.codethree'})) {
 9448: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9449: 		    $env{'form.codethree'};
 9450: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9451: 		    &Apache::lonnet::checkin($token);
 9452: 		if ($tsymb) {
 9453: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9454: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9455: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9456: 					  ('grade_username' => $tuname,
 9457: 					   'grade_domain' => $tudom,
 9458: 					   'grade_courseid' => $tcrsid,
 9459: 					   'grade_symb' => $tsymb)));
 9460: 		    } else {
 9461: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9462: 		    }
 9463: 		} else {
 9464: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9465: 		}
 9466: 	    } else {
 9467: 		$request->print(&Apache::lonxml::tokeninputfield());
 9468: 	    }
 9469: 	}
 9470:     } else {
 9471: 	&init_perm();
 9472: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9473: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9474: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9475: 	    &pickStudentPage($request);
 9476: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9477: 	    &displayPage($request);
 9478: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9479: 	    &updateGradeByPage($request);
 9480: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9481: 	    &processGroup($request);
 9482: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9483: 	    $request->print(&grading_menu($request));
 9484: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9485: 	    $request->print(&submit_options($request));
 9486: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9487: 	    $request->print(&viewgrades($request));
 9488: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9489: 	    $request->print(&processHandGrade($request));
 9490: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9491: 	    $request->print(&editgrades($request));
 9492: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9493: 	    $request->print(&verifyreceipt($request));
 9494:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9495:             $request->print(&process_clicker($request));
 9496:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9497:             $request->print(&process_clicker_file($request));
 9498:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9499:             $request->print(&assign_clicker_grades($request));
 9500: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9501: 	    $request->print(&upcsvScores_form($request));
 9502: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9503: 	    $request->print(&csvupload($request));
 9504: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9505: 	    $request->print(&csvuploadmap($request));
 9506: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9507: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9508: 		$request->print(&csvuploadoptions($request));
 9509: 	    } else {
 9510: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9511: 		    $env{'form.upfile_associate'} = 'reverse';
 9512: 		} else {
 9513: 		    $env{'form.upfile_associate'} = 'forward';
 9514: 		}
 9515: 		$request->print(&csvuploadmap($request));
 9516: 	    }
 9517: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9518: 	    $request->print(&csvuploadassign($request));
 9519: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9520: 	    $request->print(&scantron_selectphase($request));
 9521:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9522:  	    $request->print(&scantron_do_warning($request));
 9523: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9524: 	    $request->print(&scantron_validate_file($request));
 9525: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9526: 	    $request->print(&scantron_process_students($request));
 9527:  	} elsif ($command eq 'scantronupload' && 
 9528:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9529: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9530:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9531:  	} elsif ($command eq 'scantronupload_save' &&
 9532:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9533: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9534:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9535:  	} elsif ($command eq 'scantron_download' &&
 9536: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9537:  	    $request->print(&scantron_download_scantron_data($request));
 9538:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9539:             $request->print(&checkscantron_results($request));     
 9540: 	} elsif ($command) {
 9541: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9542: 	}
 9543:     }
 9544:     if ($ssi_error) {
 9545: 	&ssi_print_error($request);
 9546:     }
 9547:     $request->print(&Apache::loncommon::end_page());
 9548:     &reset_caches();
 9549:     return '';
 9550: }
 9551: 
 9552: 1;
 9553: 
 9554: __END__;
 9555: 
 9556: 
 9557: =head1 NAME
 9558: 
 9559: Apache::grades
 9560: 
 9561: =head1 SYNOPSIS
 9562: 
 9563: Handles the viewing of grades.
 9564: 
 9565: This is part of the LearningOnline Network with CAPA project
 9566: described at http://www.lon-capa.org.
 9567: 
 9568: =head1 OVERVIEW
 9569: 
 9570: Do an ssi with retries:
 9571: While I'd love to factor out this with the vesrion in lonprintout,
 9572: 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
 9573: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9574: 
 9575: At least the logic that drives this has been pulled out into loncommon.
 9576: 
 9577: 
 9578: 
 9579: ssi_with_retries - Does the server side include of a resource.
 9580:                      if the ssi call returns an error we'll retry it up to
 9581:                      the number of times requested by the caller.
 9582:                      If we still have a proble, no text is appended to the
 9583:                      output and we set some global variables.
 9584:                      to indicate to the caller an SSI error occurred.  
 9585:                      All of this is supposed to deal with the issues described
 9586:                      in LonCAPA BZ 5631 see:
 9587:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9588:                      by informing the user that this happened.
 9589: 
 9590: Parameters:
 9591:   resource   - The resource to include.  This is passed directly, without
 9592:                interpretation to lonnet::ssi.
 9593:   form       - The form hash parameters that guide the interpretation of the resource
 9594:                
 9595:   retries    - Number of retries allowed before giving up completely.
 9596: Returns:
 9597:   On success, returns the rendered resource identified by the resource parameter.
 9598: Side Effects:
 9599:   The following global variables can be set:
 9600:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9601:                               It is up to the caller to initialize this to false
 9602:                               if desired.
 9603:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9604:                               of the resource that could not be rendered by the ssi
 9605:                               call.
 9606:    ssi_error_message   - The error string fetched from the ssi response
 9607:                               in the event of an error.
 9608: 
 9609: 
 9610: =head1 HANDLER SUBROUTINE
 9611: 
 9612: ssi_with_retries()
 9613: 
 9614: =head1 SUBROUTINES
 9615: 
 9616: =over
 9617: 
 9618: =item scantron_get_correction() : 
 9619: 
 9620:    Builds the interface screen to interact with the operator to fix a
 9621:    specific error condition in a specific scanline
 9622: 
 9623:  Arguments:
 9624:     $r           - Apache request object
 9625:     $i           - number of the current scanline
 9626:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9627:     $scan_config - hash ref as returned from &get_scantron_config()
 9628:     $line        - full contents of the current scanline
 9629:     $error       - error condition, valid values are
 9630:                    'incorrectCODE', 'duplicateCODE',
 9631:                    'doublebubble', 'missingbubble',
 9632:                    'duplicateID', 'incorrectID'
 9633:     $arg         - extra information needed
 9634:        For errors:
 9635:          - duplicateID   - paper number that this studentID was seen before on
 9636:          - duplicateCODE - array ref of the paper numbers this CODE was
 9637:                            seen on before
 9638:          - incorrectCODE - current incorrect CODE 
 9639:          - doublebubble  - array ref of the bubble lines that have double
 9640:                            bubble errors
 9641:          - missingbubble - array ref of the bubble lines that have missing
 9642:                            bubble errors
 9643: 
 9644: =item  scantron_get_maxbubble() : 
 9645: 
 9646:    Arguments:
 9647:        $nav_error  - Reference to scalar which is a flag to indicate a
 9648:                       failure to retrieve a navmap object.
 9649:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9650:        calling routine should trap the error condition and display the warning
 9651:        found in &navmap_errormsg().
 9652: 
 9653:    Returns the maximum number of bubble lines that are expected to
 9654:    occur. Does this by walking the selected sequence rendering the
 9655:    resource and then checking &Apache::lonxml::get_problem_counter()
 9656:    for what the current value of the problem counter is.
 9657: 
 9658:    Caches the results to $env{'form.scantron_maxbubble'},
 9659:    $env{'form.scantron.bubble_lines.n'}, 
 9660:    $env{'form.scantron.first_bubble_line.n'} and
 9661:    $env{"form.scantron.sub_bubblelines.n"}
 9662:    which are the total number of bubble, lines, the number of bubble
 9663:    lines for response n and number of the first bubble line for response n,
 9664:    and a comma separated list of numbers of bubble lines for sub-questions
 9665:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9666: 
 9667: 
 9668: =item  scantron_validate_missingbubbles() : 
 9669: 
 9670:    Validates all scanlines in the selected file to not have any
 9671:     answers that don't have bubbles that have not been verified
 9672:     to be bubble free.
 9673: 
 9674: =item  scantron_process_students() : 
 9675: 
 9676:    Routine that does the actual grading of the bubble sheet information.
 9677: 
 9678:    The parsed scanline hash is added to %env 
 9679: 
 9680:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9681:    foreach resource , with the form data of
 9682: 
 9683: 	'submitted'     =>'scantron' 
 9684: 	'grade_target'  =>'grade',
 9685: 	'grade_username'=> username of student
 9686: 	'grade_domain'  => domain of student
 9687: 	'grade_courseid'=> of course
 9688: 	'grade_symb'    => symb of resource to grade
 9689: 
 9690:     This triggers a grading pass. The problem grading code takes care
 9691:     of converting the bubbled letter information (now in %env) into a
 9692:     valid submission.
 9693: 
 9694: =item  scantron_upload_scantron_data() :
 9695: 
 9696:     Creates the screen for adding a new bubble sheet data file to a course.
 9697: 
 9698: =item  scantron_upload_scantron_data_save() : 
 9699: 
 9700:    Adds a provided bubble information data file to the course if user
 9701:    has the correct privileges to do so. 
 9702: 
 9703: =item  valid_file() :
 9704: 
 9705:    Validates that the requested bubble data file exists in the course.
 9706: 
 9707: =item  scantron_download_scantron_data() : 
 9708: 
 9709:    Shows a list of the three internal files (original, corrected,
 9710:    skipped) for a specific bubble sheet data file that exists in the
 9711:    course.
 9712: 
 9713: =item  scantron_validate_ID() : 
 9714: 
 9715:    Validates all scanlines in the selected file to not have any
 9716:    invalid or underspecified student/employee IDs
 9717: 
 9718: =item navmap_errormsg() :
 9719: 
 9720:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9721:    Should be called whenever the request to instantiate a navmap object fails.  
 9722: 
 9723: =back
 9724: 
 9725: =cut

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