File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.588: download - view: text, annotated - select for diffs
Fri Jan 15 16:41:43 2010 UTC (14 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Screen layout consistency and floating enhancements:
- Replaced some special styles by standard boxes and headlines
(work in progress)

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.588 2010/01/15 16:41:43 bisitz 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:     my $partlist = $res->parts();
  164:     my %vPart = 
  165: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  166:     my (%response_types,%handgrade);
  167:     foreach my $part (@{ $partlist }) {
  168: 	next if (%vPart && !exists($vPart{$part}));
  169: 
  170: 	my @types = $res->responseType($part);
  171: 	my @ids = $res->responseIds($part);
  172: 	for (my $i=0; $i < scalar(@ids); $i++) {
  173: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  174: 	    $handgrade{$part.'_'.$ids[$i]} = 
  175: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  176: 				     '.handgrade',$symb);
  177: 	}
  178:     }
  179:     return ($partlist,\%handgrade,\%response_types);
  180: }
  181: 
  182: sub flatten_responseType {
  183:     my ($responseType) = @_;
  184:     my @part_response_id =
  185: 	map { 
  186: 	    my $part = $_;
  187: 	    map {
  188: 		[$part,$_]
  189: 		} sort(keys(%{ $responseType->{$part} }));
  190: 	} sort(keys(%$responseType));
  191:     return @part_response_id;
  192: }
  193: 
  194: sub get_display_part {
  195:     my ($partID,$symb)=@_;
  196:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  197:     if (defined($display) and $display ne '') {
  198:         $display.= ' (<span class="LC_internal_info">'
  199:                   .&mt('Part ID: [_1]',$partID).'</span>)';
  200:     } else {
  201: 	$display=$partID;
  202:     }
  203:     return $display;
  204: }
  205: 
  206: #--- Show resource title
  207: #--- and parts and response type
  208: sub showResourceInfo {
  209:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  210:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  211:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  212:     if (ref($res_error)) {
  213:         if ($$res_error) {
  214:             return;
  215:         }
  216:     }
  217:     $result.=&Apache::loncommon::start_data_table()
  218:             .&Apache::loncommon::start_data_table_header_row();
  219:     if ($checkboxes) {
  220:         $result.='<th>&nbsp;</th>';
  221:     }
  222:     $result.='<th>'.&mt('Problem Part').'</th>'
  223:             .'<th>'.&mt('Res. ID').'</th>'
  224:             .'<th>'.&mt('Type').'</th>'
  225:             .&Apache::loncommon::end_data_table_header_row();
  226:     my %resptype = ();
  227:     my $hdgrade='no';
  228:     my %partsseen;
  229:     foreach my $partID (sort(keys(%$responseType))) {
  230:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  231:             my $handgrade=$$handgrade{$partID.'_'.$resID};
  232:             my $responsetype = $responseType->{$partID}->{$resID};
  233:             $hdgrade = $handgrade if ($handgrade eq 'yes');
  234:             $result.=&Apache::loncommon::start_data_table_row();
  235:             if ($checkboxes) {
  236:                 if (exists($partsseen{$partID})) {
  237:                     $result.="<td>&nbsp;</td>";
  238:                 } else {
  239:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  240:                 }
  241:                 $partsseen{$partID}=1;
  242:             }
  243:             my $display_part=&get_display_part($partID,$symb);
  244:             $result.='<td>'.$display_part.'</td>'
  245:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
  246:                     .'<td>'.&mt($responsetype).'</td>'
  247: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
  248:                     .&Apache::loncommon::end_data_table_row();
  249:         }
  250:     }
  251:     $result.=&Apache::loncommon::end_data_table();
  252:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  253: }
  254: 
  255: sub reset_caches {
  256:     &reset_analyze_cache();
  257:     &reset_perm();
  258: }
  259: 
  260: {
  261:     my %analyze_cache;
  262:     my %analyze_cache_formkeys;
  263: 
  264:     sub reset_analyze_cache {
  265: 	undef(%analyze_cache);
  266:         undef(%analyze_cache_formkeys);
  267:     }
  268: 
  269:     sub get_analyze {
  270: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  271: 	my $key = "$symb\0$uname\0$udom";
  272: 	if (exists($analyze_cache{$key})) {
  273:             my $getupdate = 0;
  274:             if (ref($add_to_hash) eq 'HASH') {
  275:                 foreach my $item (keys(%{$add_to_hash})) {
  276:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  277:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  278:                             $getupdate = 1;
  279:                             last;
  280:                         }
  281:                     } else {
  282:                         $getupdate = 1;
  283:                     }
  284:                 }
  285:             }
  286:             if (!$getupdate) {
  287:                 return $analyze_cache{$key};
  288:             }
  289:         }
  290: 
  291: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  292: 	$url=&Apache::lonnet::clutter($url);
  293:         my %form = ('grade_target'      => 'analyze',
  294:                     'grade_domain'      => $udom,
  295:                     'grade_symb'        => $symb,
  296:                     'grade_courseid'    =>  $env{'request.course.id'},
  297:                     'grade_username'    => $uname,
  298:                     'grade_noincrement' => $no_increment);
  299:         if (ref($add_to_hash)) {
  300:             %form = (%form,%{$add_to_hash});
  301:         } 
  302: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  303: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  304: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  305:         if (ref($add_to_hash) eq 'HASH') {
  306:             $analyze_cache_formkeys{$key} = $add_to_hash;
  307:         } else {
  308:             $analyze_cache_formkeys{$key} = {};
  309:         }
  310: 	return $analyze_cache{$key} = \%analyze;
  311:     }
  312: 
  313:     sub get_order {
  314: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  315: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  316: 	return $analyze->{"$partid.$respid.shown"};
  317:     }
  318: 
  319:     sub get_radiobutton_correct_foil {
  320: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  321: 	my $analyze = &get_analyze($symb,$uname,$udom);
  322:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  323:         if (ref($foils) eq 'ARRAY') {
  324: 	    foreach my $foil (@{$foils}) {
  325: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  326: 		    return $foil;
  327: 	        }
  328: 	    }
  329: 	}
  330:     }
  331: 
  332:     sub scantron_partids_tograde {
  333:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  334:         my (%analysis,@parts);
  335:         if (ref($resource)) {
  336:             my $symb = $resource->symb();
  337:             my $add_to_form;
  338:             if ($check_for_randomlist) {
  339:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  340:             }
  341:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  342:             if (ref($analyze) eq 'HASH') {
  343:                 %analysis = %{$analyze};
  344:             }
  345:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  346:                 foreach my $part (@{$analysis{'parts'}}) {
  347:                     my ($id,$respid) = split(/\./,$part);
  348:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  349:                         push(@parts,$part);
  350:                     }
  351:                 }
  352:             }
  353:         }
  354:         return (\%analysis,\@parts);
  355:     }
  356: 
  357: }
  358: 
  359: #--- Clean response type for display
  360: #--- Currently filters option/rank/radiobutton/match/essay/Task
  361: #        response types only.
  362: sub cleanRecord {
  363:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  364: 	$uname,$udom) = @_;
  365:     my $grayFont = '<span class="LC_internal_info">';
  366:     if ($response =~ /^(option|rank)$/) {
  367: 	my %answer=&Apache::lonnet::str2hash($answer);
  368: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  369: 	my ($toprow,$bottomrow);
  370: 	foreach my $foil (@$order) {
  371: 	    if ($grading{$foil} == 1) {
  372: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  373: 	    } else {
  374: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  375: 	    }
  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  377: 	}
  378: 	return '<blockquote><table border="1">'.
  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  381: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  382:     } elsif ($response eq 'match') {
  383: 	my %answer=&Apache::lonnet::str2hash($answer);
  384: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  385: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  386: 	my ($toprow,$middlerow,$bottomrow);
  387: 	foreach my $foil (@$order) {
  388: 	    my $item=shift(@items);
  389: 	    if ($grading{$foil} == 1) {
  390: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  391: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  392: 	    } else {
  393: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  394: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  395: 	    }
  396: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  397: 	}
  398: 	return '<blockquote><table border="1">'.
  399: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  400: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  401: 	    $middlerow.'</tr>'.
  402: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  403: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  404:     } elsif ($response eq 'radiobutton') {
  405: 	my %answer=&Apache::lonnet::str2hash($answer);
  406: 	my ($toprow,$bottomrow);
  407: 	my $correct = 
  408: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  409: 	foreach my $foil (@$order) {
  410: 	    if (exists($answer{$foil})) {
  411: 		if ($foil eq $correct) {
  412: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  413: 		} else {
  414: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  415: 		}
  416: 	    } else {
  417: 		$toprow.='<td>'.&mt('false').'</td>';
  418: 	    }
  419: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  420: 	}
  421: 	return '<blockquote><table border="1">'.
  422: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  423: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  424: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  425:     } elsif ($response eq 'essay') {
  426: 	if (! exists ($env{'form.'.$symb})) {
  427: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  428: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  429: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  430: 
  431: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  432: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  433: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  434: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  435: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  436: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  437: 	}
  438: 	$answer =~ s-\n-<br />-g;
  439: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  440:     } elsif ( $response eq 'organic') {
  441: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  442: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  443: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  444: 	return $result;
  445:     } elsif ( $response eq 'Task') {
  446: 	if ( $answer eq 'SUBMITTED') {
  447: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  448: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  449: 	    return $result;
  450: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  451: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  452: 			       keys(%{$record}));
  453: 	    return join('<br />',($version,@matches));
  454: 			       
  455: 			       
  456: 	} else {
  457: 	    my $result =
  458: 		'<p>'
  459: 		.&mt('Overall result: [_1]',
  460: 		     $record->{$version."resource.$respid.$partid.status"})
  461: 		.'</p>';
  462: 	    
  463: 	    $result .= '<ul>';
  464: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  465: 			     keys(%{$record}));
  466: 	    foreach my $grade (sort(@grade)) {
  467: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  468: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  469: 				     $dim, $record->{$grade}).
  470: 			  '</li>';
  471: 	    }
  472: 	    $result.='</ul>';
  473: 	    return $result;
  474: 	}
  475:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  476: 	$answer = 
  477: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  478: 							      $answer);
  479:     }
  480:     return $answer;
  481: }
  482: 
  483: #-- A couple of common js functions
  484: sub commonJSfunctions {
  485:     my $request = shift;
  486:     $request->print(<<COMMONJSFUNCTIONS);
  487: <script type="text/javascript" language="javascript">
  488:     function radioSelection(radioButton) {
  489: 	var selection=null;
  490: 	if (radioButton.length > 1) {
  491: 	    for (var i=0; i<radioButton.length; i++) {
  492: 		if (radioButton[i].checked) {
  493: 		    return radioButton[i].value;
  494: 		}
  495: 	    }
  496: 	} else {
  497: 	    if (radioButton.checked) return radioButton.value;
  498: 	}
  499: 	return selection;
  500:     }
  501: 
  502:     function pullDownSelection(selectOne) {
  503: 	var selection="";
  504: 	if (selectOne.length > 1) {
  505: 	    for (var i=0; i<selectOne.length; i++) {
  506: 		if (selectOne[i].selected) {
  507: 		    return selectOne[i].value;
  508: 		}
  509: 	    }
  510: 	} else {
  511:             // only one value it must be the selected one
  512: 	    return selectOne.value;
  513: 	}
  514:     }
  515: </script>
  516: COMMONJSFUNCTIONS
  517: }
  518: 
  519: #--- Dumps the class list with usernames,list of sections,
  520: #--- section, ids and fullnames for each user.
  521: sub getclasslist {
  522:     my ($getsec,$filterlist,$getgroup) = @_;
  523:     my @getsec;
  524:     my @getgroup;
  525:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  526:     if (!ref($getsec)) {
  527: 	if ($getsec ne '' && $getsec ne 'all') {
  528: 	    @getsec=($getsec);
  529: 	}
  530:     } else {
  531: 	@getsec=@{$getsec};
  532:     }
  533:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  534:     if (!ref($getgroup)) {
  535: 	if ($getgroup ne '' && $getgroup ne 'all') {
  536: 	    @getgroup=($getgroup);
  537: 	}
  538:     } else {
  539: 	@getgroup=@{$getgroup};
  540:     }
  541:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  542: 
  543:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  544:     # Bail out if we were unable to get the classlist
  545:     return if (! defined($classlist));
  546:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  547:     #
  548:     my %sections;
  549:     my %fullnames;
  550:     foreach my $student (keys(%$classlist)) {
  551:         my $end      = 
  552:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  553:         my $start    = 
  554:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  555:         my $id       = 
  556:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  557:         my $section  = 
  558:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  559:         my $fullname = 
  560:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  561:         my $status   = 
  562:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  563:         my $group   = 
  564:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  565: 	# filter students according to status selected
  566: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  567: 	    if (!($stu_status =~ $status)) {
  568: 		delete($classlist->{$student});
  569: 		next;
  570: 	    }
  571: 	}
  572: 	# filter students according to groups selected
  573: 	my @stu_groups = split(/,/,$group);
  574: 	if (@getgroup) {
  575: 	    my $exclude = 1;
  576: 	    foreach my $grp (@getgroup) {
  577: 	        foreach my $stu_group (@stu_groups) {
  578: 	            if ($stu_group eq $grp) {
  579: 	                $exclude = 0;
  580:     	            } 
  581: 	        }
  582:     	        if (($grp eq 'none') && !$group) {
  583:         	        $exclude = 0;
  584:         	}
  585: 	    }
  586: 	    if ($exclude) {
  587: 	        delete($classlist->{$student});
  588: 	    }
  589: 	}
  590: 	$section = ($section ne '' ? $section : 'none');
  591: 	if (&canview($section)) {
  592: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  593: 		$sections{$section}++;
  594: 		if ($classlist->{$student}) {
  595: 		    $fullnames{$student}=$fullname;
  596: 		}
  597: 	    } else {
  598: 		delete($classlist->{$student});
  599: 	    }
  600: 	} else {
  601: 	    delete($classlist->{$student});
  602: 	}
  603:     }
  604:     my %seen = ();
  605:     my @sections = sort(keys(%sections));
  606:     return ($classlist,\@sections,\%fullnames);
  607: }
  608: 
  609: sub canmodify {
  610:     my ($sec)=@_;
  611:     if ($perm{'mgr'}) {
  612: 	if (!defined($perm{'mgr_section'})) {
  613: 	    # can modify whole class
  614: 	    return 1;
  615: 	} else {
  616: 	    if ($sec eq $perm{'mgr_section'}) {
  617: 		#can modify the requested section
  618: 		return 1;
  619: 	    } else {
  620: 		# can't modify the request section
  621: 		return 0;
  622: 	    }
  623: 	}
  624:     }
  625:     #can't modify
  626:     return 0;
  627: }
  628: 
  629: sub canview {
  630:     my ($sec)=@_;
  631:     if ($perm{'vgr'}) {
  632: 	if (!defined($perm{'vgr_section'})) {
  633: 	    # can modify whole class
  634: 	    return 1;
  635: 	} else {
  636: 	    if ($sec eq $perm{'vgr_section'}) {
  637: 		#can modify the requested section
  638: 		return 1;
  639: 	    } else {
  640: 		# can't modify the request section
  641: 		return 0;
  642: 	    }
  643: 	}
  644:     }
  645:     #can't modify
  646:     return 0;
  647: }
  648: 
  649: #--- Retrieve the grade status of a student for all the parts
  650: sub student_gradeStatus {
  651:     my ($symb,$udom,$uname,$partlist) = @_;
  652:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  653:     my %partstatus = ();
  654:     foreach (@$partlist) {
  655: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  656: 	$status              = 'nothing' if ($status eq '');
  657: 	$partstatus{$_}      = $status;
  658: 	my $subkey           = "resource.$_.submitted_by";
  659: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  660:     }
  661:     return %partstatus;
  662: }
  663: 
  664: # hidden form and javascript that calls the form
  665: # Use by verifyscript and viewgrades
  666: # Shows a student's view of problem and submission
  667: sub jscriptNform {
  668:     my ($symb) = @_;
  669:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  670:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  671: 	'    function viewOneStudent(user,domain) {'."\n".
  672: 	'	document.onestudent.student.value = user;'."\n".
  673: 	'	document.onestudent.userdom.value = domain;'."\n".
  674: 	'	document.onestudent.submit();'."\n".
  675: 	'    }'."\n".
  676: 	'</script>'."\n";
  677:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  678: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  679: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  680: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  681: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  682: 	'<input type="hidden" name="command" value="submission" />'."\n".
  683: 	'<input type="hidden" name="student" value="" />'."\n".
  684: 	'<input type="hidden" name="userdom" value="" />'."\n".
  685: 	'</form>'."\n";
  686:     return $jscript;
  687: }
  688: 
  689: 
  690: 
  691: # Given the score (as a number [0-1] and the weight) what is the final
  692: # point value? This function will round to the nearest tenth, third,
  693: # or quarter if one of those is within the tolerance of .00001.
  694: sub compute_points {
  695:     my ($score, $weight) = @_;
  696:     
  697:     my $tolerance = .00001;
  698:     my $points = $score * $weight;
  699: 
  700:     # Check for nearness to 1/x.
  701:     my $check_for_nearness = sub {
  702:         my ($factor) = @_;
  703:         my $num = ($points * $factor) + $tolerance;
  704:         my $floored_num = floor($num);
  705:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  706:             return $floored_num / $factor;
  707:         }
  708:         return $points;
  709:     };
  710: 
  711:     $points = $check_for_nearness->(10);
  712:     $points = $check_for_nearness->(3);
  713:     $points = $check_for_nearness->(4);
  714:     
  715:     return $points;
  716: }
  717: 
  718: #------------------ End of general use routines --------------------
  719: 
  720: #
  721: # Find most similar essay
  722: #
  723: 
  724: sub most_similar {
  725:     my ($uname,$udom,$uessay,$old_essays)=@_;
  726: 
  727: # ignore spaces and punctuation
  728: 
  729:     $uessay=~s/\W+/ /gs;
  730: 
  731: # ignore empty submissions (occuring when only files are sent)
  732: 
  733:     unless ($uessay=~/\w+/) { return ''; }
  734: 
  735: # these will be returned. Do not care if not at least 50 percent similar
  736:     my $limit=0.6;
  737:     my $sname='';
  738:     my $sdom='';
  739:     my $scrsid='';
  740:     my $sessay='';
  741: # go through all essays ...
  742:     foreach my $tkey (keys(%$old_essays)) {
  743: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  744: # ... except the same student
  745:         next if (($tname eq $uname) && ($tdom eq $udom));
  746: 	my $tessay=$old_essays->{$tkey};
  747: 	$tessay=~s/\W+/ /gs;
  748: # String similarity gives up if not even limit
  749: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  750: # Found one
  751: 	if ($tsimilar>$limit) {
  752: 	    $limit=$tsimilar;
  753: 	    $sname=$tname;
  754: 	    $sdom=$tdom;
  755: 	    $scrsid=$tcrsid;
  756: 	    $sessay=$old_essays->{$tkey};
  757: 	}
  758:     }
  759:     if ($limit>0.6) {
  760:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  761:     } else {
  762:        return ('','','','',0);
  763:     }
  764: }
  765: 
  766: #-------------------------------------------------------------------
  767: 
  768: #------------------------------------ Receipt Verification Routines
  769: #
  770: #--- Check whether a receipt number is valid.---
  771: sub verifyreceipt {
  772:     my $request  = shift;
  773: 
  774:     my $courseid = $env{'request.course.id'};
  775:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  776: 	$env{'form.receipt'};
  777:     $receipt     =~ s/[^\-\d]//g;
  778:     my ($symb)   = &get_symb($request);
  779: 
  780:     my $title.=
  781: 	'<h3><span class="LC_info">'.
  782: 	&mt('Verifying Receipt No. [_1]',$receipt).
  783: 	'</span></h3>'."\n".
  784: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  785: 	'</h4>'."\n";
  786: 
  787:     my ($string,$contents,$matches) = ('','',0);
  788:     my (undef,undef,$fullname) = &getclasslist('all','0');
  789:     
  790:     my $receiptparts=0;
  791:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  792: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  793:     my $parts=['0'];
  794:     if ($receiptparts) {
  795:         my $res_error; 
  796:         ($parts)=&response_type($symb,\$res_error);
  797:         if ($res_error) {
  798:             return &navmap_errormsg();
  799:         } 
  800:     }
  801:     
  802:     my $header = 
  803: 	&Apache::loncommon::start_data_table().
  804: 	&Apache::loncommon::start_data_table_header_row().
  805: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  806: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  807: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  808:     if ($receiptparts) {
  809: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  810:     }
  811:     $header.=
  812: 	&Apache::loncommon::end_data_table_header_row();
  813: 
  814:     foreach (sort 
  815: 	     {
  816: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  817: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  818: 		 }
  819: 		 return $a cmp $b;
  820: 	     } (keys(%$fullname))) {
  821: 	my ($uname,$udom)=split(/\:/);
  822: 	foreach my $part (@$parts) {
  823: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  824: 		$contents.=
  825: 		    &Apache::loncommon::start_data_table_row().
  826: 		    '<td>&nbsp;'."\n".
  827: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  828: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  829: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  830: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  831: 		if ($receiptparts) {
  832: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  833: 		}
  834: 		$contents.= 
  835: 		    &Apache::loncommon::end_data_table_row()."\n";
  836: 		
  837: 		$matches++;
  838: 	    }
  839: 	}
  840:     }
  841:     if ($matches == 0) {
  842:         $string = $title
  843:                  .'<p class="LC_warning">'
  844:                  .&mt('No match found for the above receipt number.')
  845:                  .'</p>';
  846:     } else {
  847: 	$string = &jscriptNform($symb).$title.
  848: 	    '<p>'.
  849: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
  850: 	    '</p>'.
  851: 	    $header.
  852: 	    $contents.
  853: 	    &Apache::loncommon::end_data_table()."\n";
  854:     }
  855:     return $string.&show_grading_menu_form($symb);
  856: }
  857: 
  858: #--- This is called by a number of programs.
  859: #--- Called from the Grading Menu - View/Grade an individual student
  860: #--- Also called directly when one clicks on the subm button 
  861: #    on the problem page.
  862: sub listStudents {
  863:     my ($request) = shift;
  864: 
  865:     my ($symb) = &get_symb($request);
  866:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  867:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  868:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  869:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  870:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  871:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  872:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  873: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  874: 
  875:     my $result='<h3><span class="LC_info">&nbsp;'
  876: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  877: 	.'</span></h3>';
  878: 
  879:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  880: 
  881:     my %lt = &Apache::lonlocal::texthash (
  882: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  883: 		'single'   => 'Please select the student before clicking on the Next button.',
  884: 	     );
  885:     $request->print(<<LISTJAVASCRIPT);
  886: <script type="text/javascript" language="javascript">
  887:     function checkSelect(checkBox) {
  888: 	var ctr=0;
  889: 	var sense="";
  890: 	if (checkBox.length > 1) {
  891: 	    for (var i=0; i<checkBox.length; i++) {
  892: 		if (checkBox[i].checked) {
  893: 		    ctr++;
  894: 		}
  895: 	    }
  896: 	    sense = '$lt{'multiple'}';
  897: 	} else {
  898: 	    if (checkBox.checked) {
  899: 		ctr = 1;
  900: 	    }
  901: 	    sense = '$lt{'single'}';
  902: 	}
  903: 	if (ctr == 0) {
  904: 	    alert(sense);
  905: 	    return false;
  906: 	}
  907: 	document.gradesub.submit();
  908:     }
  909: 
  910:     function reLoadList(formname) {
  911: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  912: 	formname.command.value = 'submission';
  913: 	formname.submit();
  914:     }
  915: </script>
  916: LISTJAVASCRIPT
  917: 
  918:     &commonJSfunctions($request);
  919:     $request->print($result);
  920: 
  921:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  922:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  923:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  924: 	"\n".$table;
  925: 	
  926:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  928:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  929:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  930:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  931:                   .&Apache::lonhtmlcommon::row_closure();
  932:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  933:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  934:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  935:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  936:                   .&Apache::lonhtmlcommon::row_closure();
  937: 
  938:     my $submission_options;
  939:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  940: 	$submission_options.=
  941: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  942:     }
  943:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  944:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  945:     $env{'form.Status'} = $saveStatus;
  946:     $submission_options.=
  947: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  948: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  949: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  950: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  951:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  952:                   .$submission_options
  953:                   .&Apache::lonhtmlcommon::row_closure();
  954: 
  955:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  956:                   .'<select name="increment">'
  957:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  958:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  959:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  960:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  961:                   .'</select>'
  962:                   .&Apache::lonhtmlcommon::row_closure();
  963: 
  964:     $gradeTable .= 
  965:         &build_section_inputs().
  966: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  967: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  968: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  969: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  970: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  971: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  972: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  973: 
  974:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  975: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  976:     } else {
  977:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  978:                       .&Apache::lonhtmlcommon::StatusOptions(
  979:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  980:                       .&Apache::lonhtmlcommon::row_closure();
  981:     }
  982: 
  983:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  984:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  985:                   .&Apache::lonhtmlcommon::row_closure(1)
  986:                   .&Apache::lonhtmlcommon::end_pick_box();
  987: 
  988:     $gradeTable .= '<p>'
  989:                   .&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"
  990:                   .'<input type="hidden" name="command" value="processGroup" />'
  991:                   .'</p>';
  992: 
  993: # checkall buttons
  994:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  995:     $gradeTable.='<input type="button" '."\n".
  996: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  997: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  998:     $gradeTable.=&check_buttons();
  999:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1000:     $gradeTable.= &Apache::loncommon::start_data_table().
 1001: 	&Apache::loncommon::start_data_table_header_row();
 1002:     my $loop = 0;
 1003:     while ($loop < 2) {
 1004: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1005: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1006: 	if ($env{'form.showgrading'} eq 'yes' 
 1007: 	    && $submitonly ne 'queued'
 1008: 	    && $submitonly ne 'all') {
 1009: 	    foreach my $part (sort(@$partlist)) {
 1010: 		my $display_part=
 1011: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1012: 		$gradeTable.=
 1013: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1014: 	    }
 1015: 	} elsif ($submitonly eq 'queued') {
 1016: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1017: 	}
 1018: 	$loop++;
 1019: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1020:     }
 1021:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1022: 
 1023:     my $ctr = 0;
 1024:     foreach my $student (sort 
 1025: 			 {
 1026: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1027: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1028: 			     }
 1029: 			     return $a cmp $b;
 1030: 			 }
 1031: 			 (keys(%$fullname))) {
 1032: 	my ($uname,$udom) = split(/:/,$student);
 1033: 
 1034: 	my %status = ();
 1035: 
 1036: 	if ($submitonly eq 'queued') {
 1037: 	    my %queue_status = 
 1038: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1039: 							$udom,$uname);
 1040: 	    next if (!defined($queue_status{'gradingqueue'}));
 1041: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1042: 	}
 1043: 
 1044: 	if ($env{'form.showgrading'} eq 'yes' 
 1045: 	    && $submitonly ne 'queued'
 1046: 	    && $submitonly ne 'all') {
 1047: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1048: 	    my $submitted = 0;
 1049: 	    my $graded = 0;
 1050: 	    my $incorrect = 0;
 1051: 	    foreach (keys(%status)) {
 1052: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1053: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1054: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1055: 		
 1056: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1057: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1058: 		    $submitted = 0;
 1059: 		    my ($part)=split(/\./,$partid);
 1060: 		    $gradeTable.='<input type="hidden" name="'.
 1061: 			$student.':'.$part.':submitted_by" value="'.
 1062: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1063: 		}
 1064: 	    }
 1065: 	    
 1066: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1067: 				     $submitonly eq 'incorrect' ||
 1068: 				     $submitonly eq 'graded'));
 1069: 	    next if (!$graded && ($submitonly eq 'graded'));
 1070: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1071: 	}
 1072: 
 1073: 	$ctr++;
 1074: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1075:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1076: 	if ( $perm{'vgr'} eq 'F' ) {
 1077: 	    if ($ctr%2 ==1) {
 1078: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1079: 	    }
 1080: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1081:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1082:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1083: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1084: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1085: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1086: 
 1087: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1088: 		foreach (sort(keys(%status))) {
 1089: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1090: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1091: 		}
 1092: 	    }
 1093: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1094: 	    if ($ctr%2 ==0) {
 1095: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1096: 	    }
 1097: 	}
 1098:     }
 1099:     if ($ctr%2 ==1) {
 1100: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1101: 	    if ($env{'form.showgrading'} eq 'yes' 
 1102: 		&& $submitonly ne 'queued'
 1103: 		&& $submitonly ne 'all') {
 1104: 		foreach (@$partlist) {
 1105: 		    $gradeTable.='<td>&nbsp;</td>';
 1106: 		}
 1107: 	    } elsif ($submitonly eq 'queued') {
 1108: 		$gradeTable.='<td>&nbsp;</td>';
 1109: 	    }
 1110: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1111:     }
 1112: 
 1113:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1114: 	'<input type="button" '.
 1115: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1116: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1117:     if ($ctr == 0) {
 1118: 	my $num_students=(scalar(keys(%$fullname)));
 1119: 	if ($num_students eq 0) {
 1120: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1121: 	} else {
 1122: 	    my $submissions='submissions';
 1123: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1124: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1125: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1126: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1127: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1128: 		    $num_students).
 1129: 		'</span><br />';
 1130: 	}
 1131:     } elsif ($ctr == 1) {
 1132: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1133:     }
 1134:     $gradeTable.=&show_grading_menu_form($symb);
 1135:     $request->print($gradeTable);
 1136:     return '';
 1137: }
 1138: 
 1139: #---- Called from the listStudents routine
 1140: 
 1141: sub check_script {
 1142:     my ($form, $type)=@_;
 1143:     my $chkallscript='<script type="text/javascript">
 1144:     function checkall() {
 1145:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1146:             ele = document.forms.'.$form.'.elements[i];
 1147:             if (ele.name == "'.$type.'") {
 1148:             document.forms.'.$form.'.elements[i].checked=true;
 1149:                                        }
 1150:         }
 1151:     }
 1152: 
 1153:     function checksec() {
 1154:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1155:             ele = document.forms.'.$form.'.elements[i];
 1156:            string = document.forms.'.$form.'.chksec.value;
 1157:            if
 1158:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1159:               document.forms.'.$form.'.elements[i].checked=true;
 1160:             }
 1161:         }
 1162:     }
 1163: 
 1164: 
 1165:     function uncheckall() {
 1166:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1167:             ele = document.forms.'.$form.'.elements[i];
 1168:             if (ele.name == "'.$type.'") {
 1169:             document.forms.'.$form.'.elements[i].checked=false;
 1170:                                        }
 1171:         }
 1172:     }
 1173: 
 1174: </script>'."\n";
 1175:     return $chkallscript;
 1176: }
 1177: 
 1178: sub check_buttons {
 1179:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1180:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1181:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1182:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1183:     return $buttons;
 1184: }
 1185: 
 1186: #     Displays the submissions for one student or a group of students
 1187: sub processGroup {
 1188:     my ($request)  = shift;
 1189:     my $ctr        = 0;
 1190:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1191:     my $total      = scalar(@stuchecked)-1;
 1192: 
 1193:     foreach my $student (@stuchecked) {
 1194: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1195: 	$env{'form.student'}        = $uname;
 1196: 	$env{'form.userdom'}        = $udom;
 1197: 	$env{'form.fullname'}       = $fullname;
 1198: 	&submission($request,$ctr,$total);
 1199: 	$ctr++;
 1200:     }
 1201:     return '';
 1202: }
 1203: 
 1204: #------------------------------------------------------------------------------------
 1205: #
 1206: #-------------------------- Next few routines handles grading by student, essentially
 1207: #                           handles essay response type problem/part
 1208: #
 1209: #--- Javascript to handle the submission page functionality ---
 1210: sub sub_page_js {
 1211:     my $request = shift;
 1212: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1213:     $request->print(<<SUBJAVASCRIPT);
 1214: <script type="text/javascript" language="javascript">
 1215:     function updateRadio(formname,id,weight) {
 1216: 	var gradeBox = formname["GD_BOX"+id];
 1217: 	var radioButton = formname["RADVAL"+id];
 1218: 	var oldpts = formname["oldpts"+id].value;
 1219: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1220: 	gradeBox.value = pts;
 1221: 	var resetbox = false;
 1222: 	if (isNaN(pts) || pts < 0) {
 1223: 	    alert("$alertmsg"+pts);
 1224: 	    for (var i=0; i<radioButton.length; i++) {
 1225: 		if (radioButton[i].checked) {
 1226: 		    gradeBox.value = i;
 1227: 		    resetbox = true;
 1228: 		}
 1229: 	    }
 1230: 	    if (!resetbox) {
 1231: 		formtextbox.value = "";
 1232: 	    }
 1233: 	    return;
 1234: 	}
 1235: 
 1236: 	if (pts > weight) {
 1237: 	    var resp = confirm("You entered a value ("+pts+
 1238: 			       ") greater than the weight for the part. Accept?");
 1239: 	    if (resp == false) {
 1240: 		gradeBox.value = oldpts;
 1241: 		return;
 1242: 	    }
 1243: 	}
 1244: 
 1245: 	for (var i=0; i<radioButton.length; i++) {
 1246: 	    radioButton[i].checked=false;
 1247: 	    if (pts == i && pts != "") {
 1248: 		radioButton[i].checked=true;
 1249: 	    }
 1250: 	}
 1251: 	updateSelect(formname,id);
 1252: 	formname["stores"+id].value = "0";
 1253:     }
 1254: 
 1255:     function writeBox(formname,id,pts) {
 1256: 	var gradeBox = formname["GD_BOX"+id];
 1257: 	if (checkSolved(formname,id) == 'update') {
 1258: 	    gradeBox.value = pts;
 1259: 	} else {
 1260: 	    var oldpts = formname["oldpts"+id].value;
 1261: 	    gradeBox.value = oldpts;
 1262: 	    var radioButton = formname["RADVAL"+id];
 1263: 	    for (var i=0; i<radioButton.length; i++) {
 1264: 		radioButton[i].checked=false;
 1265: 		if (i == oldpts) {
 1266: 		    radioButton[i].checked=true;
 1267: 		}
 1268: 	    }
 1269: 	}
 1270: 	formname["stores"+id].value = "0";
 1271: 	updateSelect(formname,id);
 1272: 	return;
 1273:     }
 1274: 
 1275:     function clearRadBox(formname,id) {
 1276: 	if (checkSolved(formname,id) == 'noupdate') {
 1277: 	    updateSelect(formname,id);
 1278: 	    return;
 1279: 	}
 1280: 	gradeSelect = formname["GD_SEL"+id];
 1281: 	for (var i=0; i<gradeSelect.length; i++) {
 1282: 	    if (gradeSelect[i].selected) {
 1283: 		var selectx=i;
 1284: 	    }
 1285: 	}
 1286: 	var stores = formname["stores"+id];
 1287: 	if (selectx == stores.value) { return };
 1288: 	var gradeBox = formname["GD_BOX"+id];
 1289: 	gradeBox.value = "";
 1290: 	var radioButton = formname["RADVAL"+id];
 1291: 	for (var i=0; i<radioButton.length; i++) {
 1292: 	    radioButton[i].checked=false;
 1293: 	}
 1294: 	stores.value = selectx;
 1295:     }
 1296: 
 1297:     function checkSolved(formname,id) {
 1298: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1299: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1300: 	    if (!reply) {return "noupdate";}
 1301: 	    formname.overRideScore.value = 'yes';
 1302: 	}
 1303: 	return "update";
 1304:     }
 1305: 
 1306:     function updateSelect(formname,id) {
 1307: 	formname["GD_SEL"+id][0].selected = true;
 1308: 	return;
 1309:     }
 1310: 
 1311: //=========== Check that a point is assigned for all the parts  ============
 1312:     function checksubmit(formname,val,total,parttot) {
 1313: 	formname.gradeOpt.value = val;
 1314: 	if (val == "Save & Next") {
 1315: 	    for (i=0;i<=total;i++) {
 1316: 		for (j=0;j<parttot;j++) {
 1317: 		    var partid = formname["partid"+i+"_"+j].value;
 1318: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1319: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1320: 			if (points == "") {
 1321: 			    var name = formname["name"+i].value;
 1322: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1323: 			    var resp = confirm("You did not assign a score for "+studentID+
 1324: 					       ", part "+partid+". Continue?");
 1325: 			    if (resp == false) {
 1326: 				formname["GD_BOX"+i+"_"+partid].focus();
 1327: 				return false;
 1328: 			    }
 1329: 			}
 1330: 		    }
 1331: 		    
 1332: 		}
 1333: 	    }
 1334: 	    
 1335: 	}
 1336: 	if (val == "Grade Student") {
 1337: 	    formname.showgrading.value = "yes";
 1338: 	    if (formname.Status.value == "") {
 1339: 		formname.Status.value = "Active";
 1340: 	    }
 1341: 	    formname.studentNo.value = total;
 1342: 	}
 1343: 	formname.submit();
 1344:     }
 1345: 
 1346: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1347:     function checkSubmitPage(formname,total) {
 1348: 	noscore = new Array(100);
 1349: 	var ptr = 0;
 1350: 	for (i=1;i<total;i++) {
 1351: 	    var partid = formname["q_"+i].value;
 1352: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1353: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1354: 		var status = formname["solved"+i+"_"+partid].value;
 1355: 		if (points == "" && status != "correct_by_student") {
 1356: 		    noscore[ptr] = i;
 1357: 		    ptr++;
 1358: 		}
 1359: 	    }
 1360: 	}
 1361: 	if (ptr != 0) {
 1362: 	    var sense = ptr == 1 ? ": " : "s: ";
 1363: 	    var prolist = "";
 1364: 	    if (ptr == 1) {
 1365: 		prolist = noscore[0];
 1366: 	    } else {
 1367: 		var i = 0;
 1368: 		while (i < ptr-1) {
 1369: 		    prolist += noscore[i]+", ";
 1370: 		    i++;
 1371: 		}
 1372: 		prolist += "and "+noscore[i];
 1373: 	    }
 1374: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1375: 	    if (resp == false) {
 1376: 		return false;
 1377: 	    }
 1378: 	}
 1379: 
 1380: 	formname.submit();
 1381:     }
 1382: </script>
 1383: SUBJAVASCRIPT
 1384: }
 1385: 
 1386: #--- javascript for essay type problem --
 1387: sub sub_page_kw_js {
 1388:     my $request = shift;
 1389:     my $iconpath = $request->dir_config('lonIconsURL');
 1390:     &commonJSfunctions($request);
 1391: 
 1392:     my $inner_js_msg_central=<<INNERJS;
 1393:     <script text="text/javascript">
 1394:     function checkInput() {
 1395:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1396:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1397:       var usrctr = document.msgcenter.usrctr.value;
 1398:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1399:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1400: 
 1401:       var msgchk = "";
 1402:       if (document.msgcenter.subchk.checked) {
 1403:          msgchk = "msgsub,";
 1404:       }
 1405:       var includemsg = 0;
 1406:       for (var i=1; i<=nmsg; i++) {
 1407:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1408:           var frmmsg = document.msgcenter["msg"+i];
 1409:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1410:           var showflg = opener.document.SCORE["shownOnce"+i];
 1411:           showflg.value = "1";
 1412:           var chkbox = document.msgcenter["msgn"+i];
 1413:           if (chkbox.checked) {
 1414:              msgchk += "savemsg"+i+",";
 1415:              includemsg = 1;
 1416:           }
 1417:       }
 1418:       if (document.msgcenter.newmsgchk.checked) {
 1419:          msgchk += "newmsg"+usrctr;
 1420:          includemsg = 1;
 1421:       }
 1422:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1423:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1424:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1425:       includemsg.value = msgchk;
 1426: 
 1427:       self.close()
 1428: 
 1429:     }
 1430:     </script>
 1431: INNERJS
 1432: 
 1433:     my $inner_js_highlight_central=<<INNERJS;
 1434:  <script type="text/javascript">
 1435:     function updateChoice(flag) {
 1436:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1437:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1438:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1439:       opener.document.SCORE.refresh.value = "on";
 1440:       if (opener.document.SCORE.keywords.value!=""){
 1441:          opener.document.SCORE.submit();
 1442:       }
 1443:       self.close()
 1444:     }
 1445: </script>
 1446: INNERJS
 1447: 
 1448:     my $start_page_msg_central = 
 1449:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1450: 				       {'js_ready'  => 1,
 1451: 					'only_body' => 1,
 1452: 					'bgcolor'   =>'#FFFFFF',});
 1453:     my $end_page_msg_central = 
 1454: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1455: 
 1456: 
 1457:     my $start_page_highlight_central = 
 1458:         &Apache::loncommon::start_page('Highlight Central',
 1459: 				       $inner_js_highlight_central,
 1460: 				       {'js_ready'  => 1,
 1461: 					'only_body' => 1,
 1462: 					'bgcolor'   =>'#FFFFFF',});
 1463:     my $end_page_highlight_central = 
 1464: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1465: 
 1466:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1467:     $docopen=~s/^document\.//;
 1468:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1469:     $request->print(<<SUBJAVASCRIPT);
 1470: <script type="text/javascript" language="javascript">
 1471: 
 1472: //===================== Show list of keywords ====================
 1473:   function keywords(formname) {
 1474:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1475:     if (nret==null) return;
 1476:     formname.keywords.value = nret;
 1477: 
 1478:     if (formname.keywords.value != "") {
 1479: 	formname.refresh.value = "on";
 1480: 	formname.submit();
 1481:     }
 1482:     return;
 1483:   }
 1484: 
 1485: //===================== Script to view submitted by ==================
 1486:   function viewSubmitter(submitter) {
 1487:     document.SCORE.refresh.value = "on";
 1488:     document.SCORE.NCT.value = "1";
 1489:     document.SCORE.unamedom0.value = submitter;
 1490:     document.SCORE.submit();
 1491:     return;
 1492:   }
 1493: 
 1494: //===================== Script to add keyword(s) ==================
 1495:   function getSel() {
 1496:     if (document.getSelection) txt = document.getSelection();
 1497:     else if (document.selection) txt = document.selection.createRange().text;
 1498:     else return;
 1499:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1500:     if (cleantxt=="") {
 1501: 	alert("$alertmsg");
 1502: 	return;
 1503:     }
 1504:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1505:     if (nret==null) return;
 1506:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1507:     if (document.SCORE.keywords.value != "") {
 1508: 	document.SCORE.refresh.value = "on";
 1509: 	document.SCORE.submit();
 1510:     }
 1511:     return;
 1512:   }
 1513: 
 1514: //====================== Script for composing message ==============
 1515:    // preload images
 1516:    img1 = new Image();
 1517:    img1.src = "$iconpath/mailbkgrd.gif";
 1518:    img2 = new Image();
 1519:    img2.src = "$iconpath/mailto.gif";
 1520: 
 1521:   function msgCenter(msgform,usrctr,fullname) {
 1522:     var Nmsg  = msgform.savemsgN.value;
 1523:     savedMsgHeader(Nmsg,usrctr,fullname);
 1524:     var subject = msgform.msgsub.value;
 1525:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1526:     re = /msgsub/;
 1527:     var shwsel = "";
 1528:     if (re.test(msgchk)) { shwsel = "checked" }
 1529:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1530:     displaySubject(checkEntities(subject),shwsel);
 1531:     for (var i=1; i<=Nmsg; i++) {
 1532: 	var testmsg = "savemsg"+i+",";
 1533: 	re = new RegExp(testmsg,"g");
 1534: 	shwsel = "";
 1535: 	if (re.test(msgchk)) { shwsel = "checked" }
 1536: 	var message = document.SCORE["savemsg"+i].value;
 1537: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1538: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1539: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1540:     }
 1541:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1542:     shwsel = "";
 1543:     re = /newmsg/;
 1544:     if (re.test(msgchk)) { shwsel = "checked" }
 1545:     newMsg(newmsg,shwsel);
 1546:     msgTail(); 
 1547:     return;
 1548:   }
 1549: 
 1550:   function checkEntities(strx) {
 1551:     if (strx.length == 0) return strx;
 1552:     var orgStr = ["&", "<", ">", '"']; 
 1553:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1554:     var counter = 0;
 1555:     while (counter < 4) {
 1556: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1557: 	counter++;
 1558:     }
 1559:     return strx;
 1560:   }
 1561: 
 1562:   function strReplace(strx, orgStr, newStr) {
 1563:     return strx.split(orgStr).join(newStr);
 1564:   }
 1565: 
 1566:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1567:     var height = 70*Nmsg+250;
 1568:     var scrollbar = "no";
 1569:     if (height > 600) {
 1570: 	height = 600;
 1571: 	scrollbar = "yes";
 1572:     }
 1573:     var xpos = (screen.width-600)/2;
 1574:     xpos = (xpos < 0) ? '0' : xpos;
 1575:     var ypos = (screen.height-height)/2-30;
 1576:     ypos = (ypos < 0) ? '0' : ypos;
 1577: 
 1578:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1579:     pWin.focus();
 1580:     pDoc = pWin.document;
 1581:     pDoc.$docopen;
 1582:     pDoc.write('$start_page_msg_central');
 1583: 
 1584:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1585:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1586:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1587: 
 1588:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1589:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1590:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1591: }
 1592:     function displaySubject(msg,shwsel) {
 1593:     pDoc = pWin.document;
 1594:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1595:     pDoc.write("<td>Subject<\\/td>");
 1596:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1597:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1598: }
 1599: 
 1600:   function displaySavedMsg(ctr,msg,shwsel) {
 1601:     pDoc = pWin.document;
 1602:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1603:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1604:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1605:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1606: }
 1607: 
 1608:   function newMsg(newmsg,shwsel) {
 1609:     pDoc = pWin.document;
 1610:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1611:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1612:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1613:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1614: }
 1615: 
 1616:   function msgTail() {
 1617:     pDoc = pWin.document;
 1618:     pDoc.write("<\\/table>");
 1619:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1620:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1621:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1622:     pDoc.write("<\\/form>");
 1623:     pDoc.write('$end_page_msg_central');
 1624:     pDoc.close();
 1625: }
 1626: 
 1627: //====================== Script for keyword highlight options ==============
 1628:   function kwhighlight() {
 1629:     var kwclr    = document.SCORE.kwclr.value;
 1630:     var kwsize   = document.SCORE.kwsize.value;
 1631:     var kwstyle  = document.SCORE.kwstyle.value;
 1632:     var redsel = "";
 1633:     var grnsel = "";
 1634:     var blusel = "";
 1635:     if (kwclr=="red")   {var redsel="checked"};
 1636:     if (kwclr=="green") {var grnsel="checked"};
 1637:     if (kwclr=="blue")  {var blusel="checked"};
 1638:     var sznsel = "";
 1639:     var sz1sel = "";
 1640:     var sz2sel = "";
 1641:     if (kwsize=="0")  {var sznsel="checked"};
 1642:     if (kwsize=="+1") {var sz1sel="checked"};
 1643:     if (kwsize=="+2") {var sz2sel="checked"};
 1644:     var synsel = "";
 1645:     var syisel = "";
 1646:     var sybsel = "";
 1647:     if (kwstyle=="")    {var synsel="checked"};
 1648:     if (kwstyle=="<i>") {var syisel="checked"};
 1649:     if (kwstyle=="<b>") {var sybsel="checked"};
 1650:     highlightCentral();
 1651:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1652:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1653:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1654:     highlightend();
 1655:     return;
 1656:   }
 1657: 
 1658:   function highlightCentral() {
 1659: //    if (window.hwdWin) window.hwdWin.close();
 1660:     var xpos = (screen.width-400)/2;
 1661:     xpos = (xpos < 0) ? '0' : xpos;
 1662:     var ypos = (screen.height-330)/2-30;
 1663:     ypos = (ypos < 0) ? '0' : ypos;
 1664: 
 1665:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1666:     hwdWin.focus();
 1667:     var hDoc = hwdWin.document;
 1668:     hDoc.$docopen;
 1669:     hDoc.write('$start_page_highlight_central');
 1670:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1671:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1672: 
 1673:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1674:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1675:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1676:   }
 1677: 
 1678:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1679:     var hDoc = hwdWin.document;
 1680:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1681:     hDoc.write("<td align=\\"left\\">");
 1682:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1683:     hDoc.write("<td align=\\"left\\">");
 1684:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1685:     hDoc.write("<td align=\\"left\\">");
 1686:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1687:     hDoc.write("<\\/tr>");
 1688:   }
 1689: 
 1690:   function highlightend() { 
 1691:     var hDoc = hwdWin.document;
 1692:     hDoc.write("<\\/table>");
 1693:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1694:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1695:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1696:     hDoc.write("<\\/form>");
 1697:     hDoc.write('$end_page_highlight_central');
 1698:     hDoc.close();
 1699:   }
 1700: 
 1701: </script>
 1702: SUBJAVASCRIPT
 1703: }
 1704: 
 1705: sub get_increment {
 1706:     my $increment = $env{'form.increment'};
 1707:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1708:         $increment != .1) {
 1709:         $increment = 1;
 1710:     }
 1711:     return $increment;
 1712: }
 1713: 
 1714: sub gradeBox_start {
 1715:     return (
 1716:         &Apache::loncommon::start_data_table()
 1717:        .&Apache::loncommon::start_data_table_header_row()
 1718:        .'<th>'.&mt('Part').'</th>'
 1719:        .'<th>'.&mt('Points').'</th>'
 1720:        .'<th>&nbsp;</th>'
 1721:        .'<th>'.&mt('Assign Grade').'</th>'
 1722:        .'<th>'.&mt('Weight').'</th>'
 1723:        .'<th>'.&mt('Grade Status').'</th>'
 1724:        .&Apache::loncommon::end_data_table_header_row()
 1725:     );
 1726: }
 1727: 
 1728: sub gradeBox_end {
 1729:     return (
 1730:         &Apache::loncommon::end_data_table()
 1731:     );
 1732: }
 1733: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1734: sub gradeBox {
 1735:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1736:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1737: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1738:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1739:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1740:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1741:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1742:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1743: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1744:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1745:     my $display_part= &get_display_part($partid,$symb);
 1746:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1747: 				       [$partid]);
 1748:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1749:     if ($last_resets{$partid}) {
 1750:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1751:     }
 1752:     $result.=&Apache::loncommon::start_data_table_row();
 1753:     my $ctr = 0;
 1754:     my $thisweight = 0;
 1755:     my $increment = &get_increment();
 1756: 
 1757:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1758:     while ($thisweight<=$wgt) {
 1759: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1760: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1761: 	    $thisweight.')" value="'.$thisweight.'" '.
 1762: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1763: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1764:         $thisweight += $increment;
 1765: 	$ctr++;
 1766:     }
 1767:     $radio.='</tr></table>';
 1768: 
 1769:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1770: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1771: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1772: 	$wgt.')" /></td>'."\n";
 1773:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1774: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1775: 	' </td>'."\n";
 1776:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1777: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1778:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1779: 	$line.='<option></option>'.
 1780: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1781:     } else {
 1782: 	$line.='<option selected="selected"></option>'.
 1783: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1784:     }
 1785:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1786: 
 1787: 
 1788: 	#&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);
 1789:     $result .= 
 1790: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1791:     $result.=&Apache::loncommon::end_data_table_row();
 1792:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1793: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1794: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1795: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1796:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1797:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1798:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1799:         $aggtries.'" />'."\n";
 1800:     my $res_error;
 1801:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1802:     if ($res_error) {
 1803:         return &navmap_errormsg();
 1804:     }
 1805:     return $result;
 1806: }
 1807: 
 1808: sub handback_box {
 1809:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1810:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1811:     my (@respids);
 1812:      my @part_response_id = &flatten_responseType($responseType);
 1813:     foreach my $part_response_id (@part_response_id) {
 1814:     	my ($part,$resp) = @{ $part_response_id };
 1815:         if ($part eq $partid) {
 1816:             push(@respids,$resp);
 1817:         }
 1818:     }
 1819:     my $result;
 1820:     foreach my $respid (@respids) {
 1821: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1822: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1823: 	next if (!@$files);
 1824: 	my $file_counter = 1;
 1825: 	foreach my $file (@$files) {
 1826: 	    if ($file =~ /\/portfolio\//) {
 1827:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1828:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1829:     	        $file_disp = "$name.$ext";
 1830:     	        $file = $file_path.$file_disp;
 1831:     	        $result.=&mt('Return commented version of [_1] to student.',
 1832:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1833:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1834:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1835:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1836:     	        $file_counter++;
 1837: 	    }
 1838: 	}
 1839:     }
 1840:     return $result;    
 1841: }
 1842: 
 1843: sub show_problem {
 1844:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1845:     my $rendered;
 1846:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1847:     &Apache::lonxml::remember_problem_counter();
 1848:     if ($mode eq 'both' or $mode eq 'text') {
 1849: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1850: 						       $env{'request.course.id'},
 1851: 						       undef,\%form);
 1852:     }
 1853:     if ($removeform) {
 1854: 	$rendered=~s|<form(.*?)>||g;
 1855: 	$rendered=~s|</form>||g;
 1856: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1857:     }
 1858:     my $companswer;
 1859:     if ($mode eq 'both' or $mode eq 'answer') {
 1860: 	&Apache::lonxml::restore_problem_counter();
 1861: 	$companswer=
 1862: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1863: 						    $env{'request.course.id'},
 1864: 						    %form);
 1865:     }
 1866:     if ($removeform) {
 1867: 	$companswer=~s|<form(.*?)>||g;
 1868: 	$companswer=~s|</form>||g;
 1869: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1870:     }
 1871:     $rendered=
 1872:         '<div class="LC_Box">'
 1873:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
 1874:        .$rendered
 1875:        .'</div>';
 1876:     $companswer=
 1877:         '<div class="LC_Box">'
 1878:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
 1879:        .$companswer
 1880:        .'</div>';
 1881:     my $result;
 1882:     if ($mode eq 'both') {
 1883:         $result=$rendered.$companswer;
 1884:     } elsif ($mode eq 'text') {
 1885:         $result=$rendered;
 1886:     } elsif ($mode eq 'answer') {
 1887:         $result=$companswer;
 1888:     }
 1889:     return $result;
 1890: }
 1891: 
 1892: sub files_exist {
 1893:     my ($r, $symb) = @_;
 1894:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1895: 
 1896:     foreach my $student (@students) {
 1897:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1898:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1899: 					      $udom,$uname);
 1900:         my ($string,$timestamp)= &get_last_submission(\%record);
 1901:         foreach my $submission (@$string) {
 1902:             my ($partid,$respid) =
 1903: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1904:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1905: 					   \%record);
 1906:             return 1 if (@$files);
 1907:         }
 1908:     }
 1909:     return 0;
 1910: }
 1911: 
 1912: sub download_all_link {
 1913:     my ($r,$symb) = @_;
 1914:     my $all_students = 
 1915: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1916: 
 1917:     my $parts =
 1918: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1919: 
 1920:     my $identifier = &Apache::loncommon::get_cgi_id();
 1921:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1922:                              'cgi.'.$identifier.'.symb' => $symb,
 1923:                              'cgi.'.$identifier.'.parts' => $parts,});
 1924:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1925: 	      &mt('Download All Submitted Documents').'</a>');
 1926:     return
 1927: }
 1928: 
 1929: sub build_section_inputs {
 1930:     my $section_inputs;
 1931:     if ($env{'form.section'} eq '') {
 1932:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1933:     } else {
 1934:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1935:         foreach my $section (@sections) {
 1936:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1937:         }
 1938:     }
 1939:     return $section_inputs;
 1940: }
 1941: 
 1942: # --------------------------- show submissions of a student, option to grade 
 1943: sub submission {
 1944:     my ($request,$counter,$total) = @_;
 1945:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1946:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1947:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1948:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1949:     my $symb = &get_symb($request); 
 1950:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1951: 
 1952:     if (!&canview($usec)) {
 1953: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1954: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1955: 			$env{'request.course.id'}.')</span>');
 1956: 	$request->print(&show_grading_menu_form($symb));
 1957: 	return;
 1958:     }
 1959: 
 1960:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1961:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1962:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1963:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1964:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1965: 	'" src="'.$request->dir_config('lonIconsURL').
 1966: 	'/check.gif" height="16" border="0" />';
 1967: 
 1968:     my %old_essays;
 1969:     # header info
 1970:     if ($counter == 0) {
 1971: 	&sub_page_js($request);
 1972: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1973: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1974: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1975: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1976: 	    &download_all_link($request, $symb);
 1977: 	}
 1978: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1979: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1980: 
 1981: 	# option to display problem, only once else it cause problems 
 1982:         # with the form later since the problem has a form.
 1983: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1984: 	    my $mode;
 1985: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1986: 		$mode='both';
 1987: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1988: 		$mode='text';
 1989: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1990: 		$mode='answer';
 1991: 	    }
 1992: 	    &Apache::lonxml::clear_problem_counter();
 1993: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1994: 	}
 1995: 
 1996: 	# kwclr is the only variable that is guaranteed to be non blank 
 1997:         # if this subroutine has been called once.
 1998: 	my %keyhash = ();
 1999: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2000: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2001: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2002: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2003: 
 2004: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2005: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2006: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2007: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2008: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2009: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2010: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2011: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2012: 	}
 2013: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2014: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2015: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2016: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2017: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2018: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2019: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2020: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2021: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2022: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2023: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2024: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2025: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2026: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2027: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2028: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2029: 			&build_section_inputs().
 2030: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2031: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2032: 			'<input type="hidden" name="NCT"'.
 2033: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2034: 	if ($env{'form.handgrade'} eq 'yes') {
 2035: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2036: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2037: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2038: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2039: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2040: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2041: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2042: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2043: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2044: 	    }
 2045: 	}
 2046: 	
 2047: 	my ($cts,$prnmsg) = (1,'');
 2048: 	while ($cts <= $env{'form.savemsgN'}) {
 2049: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2050: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2051: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2052: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2053: 		'" />'."\n".
 2054: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2055: 	    $cts++;
 2056: 	}
 2057: 	$request->print($prnmsg);
 2058: 
 2059: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2060: #
 2061: # Print out the keyword options line
 2062: #
 2063: 	    $request->print(<<KEYWORDS);
 2064: &nbsp;<b>Keyword Options:</b>&nbsp;
 2065: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2066: <a href="#" onMouseDown="javascript:getSel(); return false"
 2067:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2068: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2069: KEYWORDS
 2070: #
 2071: # Load the other essays for similarity check
 2072: #
 2073:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2074: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2075: 	    $apath=&escape($apath);
 2076: 	    $apath=~s/\W/\_/gs;
 2077: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2078:         }
 2079:     }
 2080: 
 2081: # This is where output for one specific student would start
 2082:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2083:     $request->print("\n\n".
 2084:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2085: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2086: 		    '<div class="LC_grade_show_user_body">'."\n");
 2087: 
 2088:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2089: 	my $mode;
 2090: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2091: 	    $mode='both';
 2092: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2093: 	    $mode='text';
 2094: 	} elsif ($env{'form.vAns'} eq 'all') {
 2095: 	    $mode='answer';
 2096: 	}
 2097: 	&Apache::lonxml::clear_problem_counter();
 2098: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2099:     }
 2100: 
 2101:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2102:     my $res_error;
 2103:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2104:     if ($res_error) {
 2105:         $request->print(&navmap_errormsg());
 2106:         return;
 2107:     }
 2108: 
 2109:     # Display student info
 2110:     $request->print(($counter == 0 ? '' : '<br />'));
 2111:     my $result='<div class="LC_grade_submissions">';
 2112:     
 2113:     $result.='<div class="LC_Box">'
 2114:             .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
 2115:     $result.='<input type="hidden" name="name'.$counter.
 2116:              '" value="'.$env{'form.fullname'}.'" />'."\n";
 2117:     if ($env{'form.handgrade'} eq 'no') {
 2118:         $result.='<p class="LC_info">'
 2119:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
 2120:                 ."</p>\n";
 2121:     }
 2122: 
 2123:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2124:     my $fullname;
 2125:     my $col_fullnames = [];
 2126:     if ($env{'form.handgrade'} eq 'yes') {
 2127: 	(my $sub_result,$fullname,$col_fullnames)=
 2128: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2129: 				 $counter);
 2130: 	$result.=$sub_result;
 2131:     }
 2132:     $request->print($result."\n");
 2133: 
 2134:     # print student answer/submission
 2135:     # Options are (1) Handgraded submission only
 2136:     #             (2) Last submission, includes submission that is not handgraded 
 2137:     #                  (for multi-response type part)
 2138:     #             (3) Last submission plus the parts info
 2139:     #             (4) The whole record for this student
 2140:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2141: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2142: 	
 2143: 	my $lastsubonly;
 2144: 
 2145:         if ($$timestamp eq '') {
 2146:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2147:         } else {
 2148:             $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2149: 
 2150: 	    my %seenparts;
 2151: 	    my @part_response_id = &flatten_responseType($responseType);
 2152: 	    foreach my $part (@part_response_id) {
 2153: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2154: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2155: 
 2156: 		my ($partid,$respid) = @{ $part };
 2157: 		my $display_part=&get_display_part($partid,$symb);
 2158: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2159: 		    if (exists($seenparts{$partid})) { next; }
 2160: 		    $seenparts{$partid}=1;
 2161: 		    my $submitby='<b>Part:</b> '.$display_part.
 2162: 			' <b>Collaborative submission by:</b> '.
 2163: 			'<a href="javascript:viewSubmitter(\''.
 2164: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2165: 			'\');" target="_self">'.
 2166: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2167: 		    $request->print($submitby);
 2168: 		    next;
 2169: 		}
 2170: 		my $responsetype = $responseType->{$partid}->{$respid};
 2171: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2172:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2173:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2174:                         ' <span class="LC_internal_info">'.
 2175:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2176:                         '</span>&nbsp; &nbsp;'.
 2177: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2178: 		    next;
 2179: 		}
 2180: 		foreach my $submission (@$string) {
 2181: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2182: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2183: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2184: 		    # Similarity check
 2185: 		    my $similar='';
 2186: 		    if($env{'form.checkPlag'}){
 2187: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2188: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2189: 			if ($osim) {
 2190: 			    $osim=int($osim*100.0);
 2191: 			    my %old_course_desc = 
 2192: 				&Apache::lonnet::coursedescription($ocrsid,
 2193: 								   {'one_time' => 1});
 2194: 
 2195: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2196: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2197: 				    $osim,
 2198: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2199: 				    $old_course_desc{'description'},
 2200: 				    $old_course_desc{'num'},
 2201: 				    $old_course_desc{'domain'}).
 2202: 				'</span></h3><blockquote><i>'.
 2203: 				&keywords_highlight($oessay).
 2204: 				'</i></blockquote><hr />';
 2205: 			}
 2206: 		    }
 2207: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2208: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2209: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2210: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2211: 			my $display_part=&get_display_part($partid,$symb);
 2212:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2213:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2214:                             ' <span class="LC_internal_info">'.
 2215:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2216:                             '</b></span>&nbsp; &nbsp;';
 2217: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2218: 			if (@$files) {
 2219: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2220: 			    my $file_counter = 0;
 2221: 			    foreach my $file (@$files) {
 2222: 			        $file_counter++;
 2223: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2224: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2225: 			    }
 2226: 			    $lastsubonly.='<br />';
 2227: 			}
 2228: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2229: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2230: 					 $respid,\%record,$order,undef,$uname,$udom);
 2231: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2232: 			$lastsubonly.='</div>';
 2233: 		    }
 2234: 		}
 2235: 	    }
 2236: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
 2237: 	}
 2238: 	$request->print($lastsubonly);
 2239:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2240: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2241: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2242:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2243: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2244: 								 $env{'request.course.id'},
 2245: 								 $last,'.submission',
 2246: 								 'Apache::grades::keywords_highlight'));
 2247:     }
 2248: 
 2249:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2250: 	.$udom.'" />'."\n");
 2251:     # return if view submission with no grading option
 2252:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2253: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2254: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2255: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2256: 	$toGrade.='</div>'."\n";
 2257: 	if (($env{'form.command'} eq 'submission') || 
 2258: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2259: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2260: 	}
 2261: 	$request->print($toGrade);
 2262: 	return;
 2263:     } else {
 2264: 	$request->print('</div>'."\n");
 2265:     }
 2266: 
 2267:     # essay grading message center
 2268:     if ($env{'form.handgrade'} eq 'yes') {
 2269: 	my $result='<div class="LC_grade_message_center">';
 2270:     
 2271: 	$result.='<div class="LC_grade_message_center_header">'.
 2272: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2273: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2274: 	my $msgfor = $givenn.' '.$lastname;
 2275: 	if (scalar(@$col_fullnames) > 0) {
 2276: 	    my $lastone = pop(@$col_fullnames);
 2277: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2278: 	}
 2279: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2280: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2281: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2282: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2283: 	    ',\''.$msgfor.'\');" target="_self">'.
 2284: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2285: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2286: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2287: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2288: 	    '<br />&nbsp;('.
 2289: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2290: 	$result.='</div></div>';
 2291: 	$request->print($result);
 2292:     }
 2293: 
 2294:     my %seen = ();
 2295:     my @partlist;
 2296:     my @gradePartRespid;
 2297:     my @part_response_id = &flatten_responseType($responseType);
 2298:     $request->print(
 2299:         '<div class="LC_Box">'
 2300:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
 2301:     );
 2302:     $request->print(&gradeBox_start()); # <div class="LC_grade_assign_body">
 2303:     foreach my $part_response_id (@part_response_id) {
 2304:     	my ($partid,$respid) = @{ $part_response_id };
 2305: 	my $part_resp = join('_',@{ $part_response_id });
 2306: 	next if ($seen{$partid} > 0);
 2307: 	$seen{$partid}++;
 2308: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2309: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2310: 	push(@partlist,$partid);
 2311: 	push(@gradePartRespid,$partid.'.'.$respid);
 2312: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2313:     }
 2314:     $request->print(&gradeBox_end()); # </div>
 2315:     $request->print('</div>');
 2316: 
 2317:     $request->print('<div class="LC_grade_info_links">');
 2318:     if ($perm{'vgr'}) {
 2319: 	$request->print(
 2320: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2321: 						   $uname,$udom,'check'));
 2322:     }
 2323:     if ($perm{'opa'}) {
 2324: 	$request->print(
 2325: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2326: 					 $uname,$udom,$symb,'check'));
 2327:     }
 2328:     $request->print('</div>');
 2329: 
 2330:     $result='<input type="hidden" name="partlist'.$counter.
 2331: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2332:     $result.='<input type="hidden" name="gradePartRespid'.
 2333: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2334:     my $ctr = 0;
 2335:     while ($ctr < scalar(@partlist)) {
 2336: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2337: 	    $partlist[$ctr].'" />'."\n";
 2338: 	$ctr++;
 2339:     }
 2340:     $request->print($result.''."\n");
 2341: 
 2342: # Done with printing info for one student
 2343: 
 2344:     $request->print('</div>');#LC_grade_show_user_body
 2345:     $request->print('</div>');#LC_grade_show_user
 2346: 
 2347: 
 2348:     # print end of form
 2349:     if ($counter == $total) {
 2350: 	my $endform='<table border="0"><tr><td>'."\n";
 2351: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2352: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2353: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2354: 	my $ntstu ='<select name="NTSTU">'.
 2355: 	    '<option>1</option><option>2</option>'.
 2356: 	    '<option>3</option><option>5</option>'.
 2357: 	    '<option>7</option><option>10</option></select>'."\n";
 2358: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2359: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2360:         $endform.=&mt('[_1]student(s)',$ntstu);
 2361: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2362: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2363: 	    '<input type="button" value="'.&mt('Next').'" '.
 2364: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2365: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2366:         $endform.="<input type='hidden' value='".&get_increment().
 2367:             "' name='increment' />";
 2368: 	$endform.='</td></tr></table></form>';
 2369: 	$endform.=&show_grading_menu_form($symb);
 2370: 	$request->print($endform);
 2371:     }
 2372:     return '';
 2373: }
 2374: 
 2375: sub check_collaborators {
 2376:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2377:     my ($result,@col_fullnames);
 2378:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2379:     foreach my $part (keys(%$handgrade)) {
 2380: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2381: 					'.maxcollaborators',
 2382: 					$symb,$udom,$uname);
 2383: 	next if ($ncol <= 0);
 2384: 	$part =~ s/\_/\./g;
 2385: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2386: 	my (@good_collaborators, @bad_collaborators);
 2387: 	foreach my $possible_collaborator
 2388: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2389: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2390: 	    next if ($possible_collaborator eq '');
 2391: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2392: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2393: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2394: 	    # Doing this grep allows 'fuzzy' specification
 2395: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2396: 			       keys(%$classlist));
 2397: 	    if (! scalar(@matches)) {
 2398: 		push(@bad_collaborators, $possible_collaborator);
 2399: 	    } else {
 2400: 		push(@good_collaborators, @matches);
 2401: 	    }
 2402: 	}
 2403: 	if (scalar(@good_collaborators) != 0) {
 2404: 	    $result.='<br />'.&mt('Collaborators: ');
 2405: 	    foreach my $name (@good_collaborators) {
 2406: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2407: 		push(@col_fullnames, $givenn.' '.$lastname);
 2408: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2409: 	    }
 2410: 	    $result.='<br />'."\n";
 2411: 	    my ($part)=split(/\./,$part);
 2412: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2413: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2414: 		"\n";
 2415: 	}
 2416: 	if (scalar(@bad_collaborators) > 0) {
 2417: 	    $result.='<div class="LC_warning">';
 2418: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2419: 	    $result .= '</div>';
 2420: 	}         
 2421: 	if (scalar(@bad_collaborators > $ncol)) {
 2422: 	    $result .= '<div class="LC_warning">';
 2423: 	    $result .= &mt('This student has submitted too many '.
 2424: 		'collaborators.  Maximum is [_1].',$ncol);
 2425: 	    $result .= '</div>';
 2426: 	}
 2427:     }
 2428:     return ($result,$fullname,\@col_fullnames);
 2429: }
 2430: 
 2431: #--- Retrieve the last submission for all the parts
 2432: sub get_last_submission {
 2433:     my ($returnhash)=@_;
 2434:     my (@string,$timestamp);
 2435:     if ($$returnhash{'version'}) {
 2436: 	my %lasthash=();
 2437: 	my ($version);
 2438: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2439: 	    foreach my $key (sort(split(/\:/,
 2440: 					$$returnhash{$version.':keys'}))) {
 2441: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2442: 		$timestamp = 
 2443: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2444: 	    }
 2445: 	}
 2446: 	foreach my $key (keys(%lasthash)) {
 2447: 	    next if ($key !~ /\.submission$/);
 2448: 
 2449: 	    my ($partid,$foo) = split(/submission$/,$key);
 2450: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2451: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2452: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2453: 	}
 2454:     }
 2455:     if (!@string) {
 2456: 	$string[0] =
 2457: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2458:     }
 2459:     return (\@string,\$timestamp);
 2460: }
 2461: 
 2462: #--- High light keywords, with style choosen by user.
 2463: sub keywords_highlight {
 2464:     my $string    = shift;
 2465:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2466:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2467:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2468:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2469:     foreach my $keyword (@keylist) {
 2470: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2471:     }
 2472:     return $string;
 2473: }
 2474: 
 2475: #--- Called from submission routine
 2476: sub processHandGrade {
 2477:     my ($request) = shift;
 2478:     my $symb   = &get_symb($request);
 2479:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2480:     my $button = $env{'form.gradeOpt'};
 2481:     my $ngrade = $env{'form.NCT'};
 2482:     my $ntstu  = $env{'form.NTSTU'};
 2483:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2484:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2485: 
 2486:     if ($button eq 'Save & Next') {
 2487: 	my $ctr = 0;
 2488: 	while ($ctr < $ngrade) {
 2489: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2490: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2491: 	    if ($errorflag eq 'no_score') {
 2492: 		$ctr++;
 2493: 		next;
 2494: 	    }
 2495: 	    if ($errorflag eq 'not_allowed') {
 2496: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2497: 		$ctr++;
 2498: 		next;
 2499: 	    }
 2500: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2501: 	    my ($subject,$message,$msgstatus) = ('','','');
 2502: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2503:             my ($feedurl,$showsymb) =
 2504: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2505: 	    my $messagetail;
 2506: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2507: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2508: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2509: 		$subject.=' ['.$restitle.']';
 2510: 		my (@msgnum) = split(/,/,$includemsg);
 2511: 		foreach (@msgnum) {
 2512: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2513: 		}
 2514: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2515: 		if ($env{'form.withgrades'.$ctr}) {
 2516: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2517: 		    $messagetail = " for <a href=\"".
 2518: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2519: 		}
 2520: 		$msgstatus = 
 2521:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2522: 						     $message.$messagetail,
 2523:                                                      undef,$feedurl,undef,
 2524:                                                      undef,undef,$showsymb,
 2525:                                                      $restitle);
 2526: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2527: 				$msgstatus);
 2528: 	    }
 2529: 	    if ($env{'form.collaborator'.$ctr}) {
 2530: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2531: 		foreach my $collabstr (@collabstrs) {
 2532: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2533: 		    foreach my $collaborator (@collaborators) {
 2534: 			my ($errorflag,$pts,$wgt) = 
 2535: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2536: 					   $env{'form.unamedom'.$ctr},$part);
 2537: 			if ($errorflag eq 'not_allowed') {
 2538: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2539: 			    next;
 2540: 			} elsif ($message ne '') {
 2541: 			    my ($baseurl,$showsymb) = 
 2542: 				&get_feedurl_and_symb($symb,$collaborator,
 2543: 						      $udom);
 2544: 			    if ($env{'form.withgrades'.$ctr}) {
 2545: 				$messagetail = " for <a href=\"".
 2546:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2547: 			    }
 2548: 			    $msgstatus = 
 2549: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2550: 			}
 2551: 		    }
 2552: 		}
 2553: 	    }
 2554: 	    $ctr++;
 2555: 	}
 2556:     }
 2557: 
 2558:     if ($env{'form.handgrade'} eq 'yes') {
 2559: 	# Keywords sorted in alphabatical order
 2560: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2561: 	my %keyhash = ();
 2562: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2563: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2564: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2565: 	$env{'form.keywords'} = join(' ',@keywords);
 2566: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2567: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2568: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2569: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2570: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2571: 
 2572: 	# message center - Order of message gets changed. Blank line is eliminated.
 2573: 	# New messages are saved in env for the next student.
 2574: 	# All messages are saved in nohist_handgrade.db
 2575: 	my ($ctr,$idx) = (1,1);
 2576: 	while ($ctr <= $env{'form.savemsgN'}) {
 2577: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2578: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2579: 		$idx++;
 2580: 	    }
 2581: 	    $ctr++;
 2582: 	}
 2583: 	$ctr = 0;
 2584: 	while ($ctr < $ngrade) {
 2585: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2586: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2587: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2588: 		$idx++;
 2589: 	    }
 2590: 	    $ctr++;
 2591: 	}
 2592: 	$env{'form.savemsgN'} = --$idx;
 2593: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2594: 	my $putresult = &Apache::lonnet::put
 2595: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2596:     }
 2597:     # Called by Save & Refresh from Highlight Attribute Window
 2598:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2599:     if ($env{'form.refresh'} eq 'on') {
 2600: 	my ($ctr,$total) = (0,0);
 2601: 	while ($ctr < $ngrade) {
 2602: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2603: 	    $ctr++;
 2604: 	}
 2605: 	$env{'form.NTSTU'}=$ngrade;
 2606: 	$ctr = 0;
 2607: 	while ($ctr < $total) {
 2608: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2609: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2610: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2611: 	    &submission($request,$ctr,$total-1);
 2612: 	    $ctr++;
 2613: 	}
 2614: 	return '';
 2615:     }
 2616: 
 2617: # Go directly to grade student - from submission or link from chart page
 2618:     if ($button eq 'Grade Student') {
 2619: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2620: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2621: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2622: 	$env{'form.fullname'} = $$fullname{$processUser};
 2623: 	&submission($request,0,0);
 2624: 	return '';
 2625:     }
 2626: 
 2627:     # Get the next/previous one or group of students
 2628:     my $firststu = $env{'form.unamedom0'};
 2629:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2630:     my $ctr = 2;
 2631:     while ($laststu eq '') {
 2632: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2633: 	$ctr++;
 2634: 	$laststu = $firststu if ($ctr > $ngrade);
 2635:     }
 2636: 
 2637:     my (@parsedlist,@nextlist);
 2638:     my ($nextflg) = 0;
 2639:     foreach my $item (sort 
 2640: 	     {
 2641: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2642: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2643: 		 }
 2644: 		 return $a cmp $b;
 2645: 	     } (keys(%$fullname))) {
 2646: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2647: 	    push(@parsedlist,$item);
 2648: 	}
 2649: 	$nextflg = 1 if ($item eq $laststu);
 2650: 	if ($button eq 'Previous') {
 2651: 	    last if ($item eq $firststu);
 2652: 	    push(@parsedlist,$item);
 2653: 	}
 2654:     }
 2655:     $ctr = 0;
 2656:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2657:     my $res_error;
 2658:     my ($partlist) = &response_type($symb,\$res_error);
 2659:     if ($res_error) {
 2660:         $request->print(&navmap_errormsg());
 2661:         return;
 2662:     }
 2663:     foreach my $student (@parsedlist) {
 2664: 	my $submitonly=$env{'form.submitonly'};
 2665: 	my ($uname,$udom) = split(/:/,$student);
 2666: 	
 2667: 	if ($submitonly eq 'queued') {
 2668: 	    my %queue_status = 
 2669: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2670: 							$udom,$uname);
 2671: 	    next if (!defined($queue_status{'gradingqueue'}));
 2672: 	}
 2673: 
 2674: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2675: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2676: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2677: 	    my $submitted = 0;
 2678: 	    my $ungraded = 0;
 2679: 	    my $incorrect = 0;
 2680: 	    foreach my $item (keys(%status)) {
 2681: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2682: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2683: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2684: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2685: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2686: 		    $submitted = 0;
 2687: 		}
 2688: 	    }
 2689: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2690: 				     $submitonly eq 'incorrect' ||
 2691: 				     $submitonly eq 'graded'));
 2692: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2693: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2694: 	}
 2695: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2696: 	last if ($ctr == $ntstu);
 2697: 	$ctr++;
 2698:     }
 2699: 
 2700:     $ctr = 0;
 2701:     my $total = scalar(@nextlist)-1;
 2702: 
 2703:     foreach (sort(@nextlist)) {
 2704: 	my ($uname,$udom,$submitter) = split(/:/);
 2705: 	$env{'form.student'}  = $uname;
 2706: 	$env{'form.userdom'}  = $udom;
 2707: 	$env{'form.fullname'} = $$fullname{$_};
 2708: 	&submission($request,$ctr,$total);
 2709: 	$ctr++;
 2710:     }
 2711:     if ($total < 0) {
 2712: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2713: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2714: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2715: 	$the_end.=&show_grading_menu_form($symb);
 2716: 	$request->print($the_end);
 2717:     }
 2718:     return '';
 2719: }
 2720: 
 2721: #---- Save the score and award for each student, if changed
 2722: sub saveHandGrade {
 2723:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2724:     my @version_parts;
 2725:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2726: 					   $env{'request.course.id'});
 2727:     if (!&canmodify($usec)) { return('not_allowed'); }
 2728:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2729:     my @parts_graded;
 2730:     my %newrecord  = ();
 2731:     my ($pts,$wgt) = ('','');
 2732:     my %aggregate = ();
 2733:     my $aggregateflag = 0;
 2734:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2735:     foreach my $new_part (@parts) {
 2736: 	#collaborator ($submi may vary for different parts
 2737: 	if ($submitter && $new_part ne $part) { next; }
 2738: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2739: 	if ($dropMenu eq 'excused') {
 2740: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2741: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2742: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2743: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2744: 		}
 2745: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2746: 	    }
 2747: 	} elsif ($dropMenu eq 'reset status'
 2748: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2749: 	    foreach my $key (keys(%record)) {
 2750: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2751: 	    }
 2752: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2753: 		"$env{'user.name'}:$env{'user.domain'}";
 2754:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2755: 
 2756:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2757: 					       [$new_part]);
 2758:             my $aggtries =$totaltries;
 2759:             if ($last_resets{$new_part}) {
 2760:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2761: 					   $new_part);
 2762:             }
 2763: 
 2764:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2765:             if ($aggtries > 0) {
 2766:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2767:                 $aggregateflag = 1;
 2768:             }
 2769: 	} elsif ($dropMenu eq '') {
 2770: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2771: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2772: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2773: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2774: 		next;
 2775: 	    }
 2776: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2777: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2778: 	    my $partial= $pts/$wgt;
 2779: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2780: 		#do not update score for part if not changed.
 2781:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2782: 		next;
 2783: 	    } else {
 2784: 	        push(@parts_graded,$new_part);
 2785: 	    }
 2786: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2787: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2788: 	    }
 2789: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2790: 	    if ($partial == 0) {
 2791: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2792: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2793: 		}
 2794: 	    } else {
 2795: 		if ($record{$reckey} ne 'correct_by_override') {
 2796: 		    $newrecord{$reckey} = 'correct_by_override';
 2797: 		}
 2798: 	    }	    
 2799: 	    if ($submitter && 
 2800: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2801: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2802: 	    }
 2803: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2804: 		"$env{'user.name'}:$env{'user.domain'}";
 2805: 	}
 2806: 	# unless problem has been graded, set flag to version the submitted files
 2807: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2808: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2809: 	        $dropMenu eq 'reset status')
 2810: 	   {
 2811: 	    push(@version_parts,$new_part);
 2812: 	}
 2813:     }
 2814:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2815:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2816: 
 2817:     if (%newrecord) {
 2818:         if (@version_parts) {
 2819:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2820:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2821: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2822: 	    foreach my $new_part (@version_parts) {
 2823: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2824: 				$new_part,\%newrecord);
 2825: 	    }
 2826:         }
 2827: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2828: 				$env{'request.course.id'},$domain,$stuname);
 2829: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2830: 				     $cdom,$cnum,$domain,$stuname);
 2831:     }
 2832:     if ($aggregateflag) {
 2833:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2834: 			      $cdom,$cnum);
 2835:     }
 2836:     return ('',$pts,$wgt);
 2837: }
 2838: 
 2839: sub check_and_remove_from_queue {
 2840:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2841:     my @ungraded_parts;
 2842:     foreach my $part (@{$parts}) {
 2843: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2844: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2845: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2846: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2847: 		) {
 2848: 	    push(@ungraded_parts, $part);
 2849: 	}
 2850:     }
 2851:     if ( !@ungraded_parts ) {
 2852: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2853: 					       $cnum,$domain,$stuname);
 2854:     }
 2855: }
 2856: 
 2857: sub handback_files {
 2858:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2859:     my $portfolio_root = '/userfiles/portfolio';
 2860:     my $res_error;
 2861:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2862:     if ($res_error) {
 2863:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2864:         return;
 2865:     }
 2866:     my @part_response_id = &flatten_responseType($responseType);
 2867:     foreach my $part_response_id (@part_response_id) {
 2868:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2869: 	my $part_resp = join('_',@{ $part_response_id });
 2870:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2871:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2872:                 my $file_counter = 1;
 2873: 		my $file_msg;
 2874:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2875:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2876:                     my ($directory,$answer_file) = 
 2877:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2878:                     my ($answer_name,$answer_ver,$answer_ext) =
 2879: 		        &file_name_version_ext($answer_file);
 2880: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2881:                     my $getpropath = 1;
 2882: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2883: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2884:                     # fix file name
 2885:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2886:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2887:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2888:             	                                $save_file_name);
 2889:                     if ($result !~ m|^/uploaded/|) {
 2890:                         $request->print('<br /><span class="LC_error">'.
 2891:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2892:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2893:                                         '</span>');
 2894:                     } else {
 2895:                         # mark the file as read only
 2896:                         my @files = ($save_file_name);
 2897:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2898:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2899: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2900: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2901: 			}
 2902:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2903: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2904: 
 2905:                     }
 2906:                     $request->print("<br />".$fname." will be the uploaded file name");
 2907:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2908:                     $file_counter++;
 2909:                 }
 2910: 		my $subject = "File Handed Back by Instructor ";
 2911: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2912: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2913: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2914: 		$message .= " and can be found in your portfolio space.";
 2915: 		my ($feedurl,$showsymb) = 
 2916: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2917:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2918: 		my $msgstatus = 
 2919:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2920: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2921:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2922:             }
 2923:         }
 2924:     return;
 2925: }
 2926: 
 2927: sub get_feedurl_and_symb {
 2928:     my ($symb,$uname,$udom) = @_;
 2929:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2930:     $url = &Apache::lonnet::clutter($url);
 2931:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2932: 					$symb,$udom,$uname);
 2933:     if ($encrypturl =~ /^yes$/i) {
 2934: 	&Apache::lonenc::encrypted(\$url,1);
 2935: 	&Apache::lonenc::encrypted(\$symb,1);
 2936:     }
 2937:     return ($url,$symb);
 2938: }
 2939: 
 2940: sub get_submitted_files {
 2941:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2942:     my @files;
 2943:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2944:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2945:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2946:     	    push(@files,$file_url.$file);
 2947:         }
 2948:     }
 2949:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2950:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2951:     }
 2952:     return (\@files);
 2953: }
 2954: 
 2955: # ----------- Provides number of tries since last reset.
 2956: sub get_num_tries {
 2957:     my ($record,$last_reset,$part) = @_;
 2958:     my $timestamp = '';
 2959:     my $num_tries = 0;
 2960:     if ($$record{'version'}) {
 2961:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2962:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2963:                 $timestamp = $$record{$version.':timestamp'};
 2964:                 if ($timestamp > $last_reset) {
 2965:                     $num_tries ++;
 2966:                 } else {
 2967:                     last;
 2968:                 }
 2969:             }
 2970:         }
 2971:     }
 2972:     return $num_tries;
 2973: }
 2974: 
 2975: # ----------- Determine decrements required in aggregate totals 
 2976: sub decrement_aggs {
 2977:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2978:     my %decrement = (
 2979:                         attempts => 0,
 2980:                         users => 0,
 2981:                         correct => 0
 2982:                     );
 2983:     $decrement{'attempts'} = $aggtries;
 2984:     if ($solvedstatus =~ /^correct/) {
 2985:         $decrement{'correct'} = 1;
 2986:     }
 2987:     if ($aggtries == $totaltries) {
 2988:         $decrement{'users'} = 1;
 2989:     }
 2990:     foreach my $type (keys(%decrement)) {
 2991:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2992:     }
 2993:     return;
 2994: }
 2995: 
 2996: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2997: sub get_last_resets {
 2998:     my ($symb,$courseid,$partids) =@_;
 2999:     my %last_resets;
 3000:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3001:     my $cname = $env{'course.'.$courseid.'.num'};
 3002:     my @keys;
 3003:     foreach my $part (@{$partids}) {
 3004: 	push(@keys,"$symb\0$part\0resettime");
 3005:     }
 3006:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3007: 				     $cdom,$cname);
 3008:     foreach my $part (@{$partids}) {
 3009: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3010:     }
 3011:     return %last_resets;
 3012: }
 3013: 
 3014: # ----------- Handles creating versions for portfolio files as answers
 3015: sub version_portfiles {
 3016:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3017:     my $version_parts = join('|',@$v_flag);
 3018:     my @returned_keys;
 3019:     my $parts = join('|', @$parts_graded);
 3020:     my $portfolio_root = '/userfiles/portfolio';
 3021:     foreach my $key (keys(%$record)) {
 3022:         my $new_portfiles;
 3023:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3024:             my @versioned_portfiles;
 3025:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3026:             foreach my $file (@portfiles) {
 3027:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3028:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3029: 		my ($answer_name,$answer_ver,$answer_ext) =
 3030: 		    &file_name_version_ext($answer_file);
 3031:                 my $getpropath = 1;    
 3032:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3033:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3034:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3035:                 if ($new_answer ne 'problem getting file') {
 3036:                     push(@versioned_portfiles, $directory.$new_answer);
 3037:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3038:                         [$directory.$new_answer],
 3039:                         [$symb,$env{'request.course.id'},'graded']);
 3040:                 }
 3041:             }
 3042:             $$record{$key} = join(',',@versioned_portfiles);
 3043:             push(@returned_keys,$key);
 3044:         }
 3045:     } 
 3046:     return (@returned_keys);   
 3047: }
 3048: 
 3049: sub get_next_version {
 3050:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3051:     my $version;
 3052:     foreach my $row (@$dir_list) {
 3053:         my ($file) = split(/\&/,$row,2);
 3054:         my ($file_name,$file_version,$file_ext) =
 3055: 	    &file_name_version_ext($file);
 3056:         if (($file_name eq $answer_name) && 
 3057: 	    ($file_ext eq $answer_ext)) {
 3058:                 # gets here if filename and extension match, regardless of version
 3059:                 if ($file_version ne '') {
 3060:                 # a versioned file is found  so save it for later
 3061:                 if ($file_version > $version) {
 3062: 		    $version = $file_version;
 3063: 	        }
 3064:             }
 3065:         }
 3066:     } 
 3067:     $version ++;
 3068:     return($version);
 3069: }
 3070: 
 3071: sub version_selected_portfile {
 3072:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3073:     my ($answer_name,$answer_ver,$answer_ext) =
 3074:         &file_name_version_ext($file_name);
 3075:     my $new_answer;
 3076:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3077:     if($env{'form.copy'} eq '-1') {
 3078:         $new_answer = 'problem getting file';
 3079:     } else {
 3080:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3081:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3082:                             $stu_name,$domain,'copy',
 3083: 		        '/portfolio'.$directory.$new_answer);
 3084:     }    
 3085:     return ($new_answer);
 3086: }
 3087: 
 3088: sub file_name_version_ext {
 3089:     my ($file)=@_;
 3090:     my @file_parts = split(/\./, $file);
 3091:     my ($name,$version,$ext);
 3092:     if (@file_parts > 1) {
 3093: 	$ext=pop(@file_parts);
 3094: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3095: 	    $version=pop(@file_parts);
 3096: 	}
 3097: 	$name=join('.',@file_parts);
 3098:     } else {
 3099: 	$name=join('.',@file_parts);
 3100:     }
 3101:     return($name,$version,$ext);
 3102: }
 3103: 
 3104: #--------------------------------------------------------------------------------------
 3105: #
 3106: #-------------------------- Next few routines handles grading by section or whole class
 3107: #
 3108: #--- Javascript to handle grading by section or whole class
 3109: sub viewgrades_js {
 3110:     my ($request) = shift;
 3111: 
 3112:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3113:     $request->print(<<VIEWJAVASCRIPT);
 3114: <script type="text/javascript" language="javascript">
 3115:    function writePoint(partid,weight,point) {
 3116: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3117: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3118: 	if (point == "textval") {
 3119: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3120: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3121: 		alert("$alertmsg"+parseFloat(point));
 3122: 		var resetbox = false;
 3123: 		for (var i=0; i<radioButton.length; i++) {
 3124: 		    if (radioButton[i].checked) {
 3125: 			textbox.value = i;
 3126: 			resetbox = true;
 3127: 		    }
 3128: 		}
 3129: 		if (!resetbox) {
 3130: 		    textbox.value = "";
 3131: 		}
 3132: 		return;
 3133: 	    }
 3134: 	    if (parseFloat(point) > parseFloat(weight)) {
 3135: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3136: 				   ") greater than the weight for the part. Accept?");
 3137: 		if (resp == false) {
 3138: 		    textbox.value = "";
 3139: 		    return;
 3140: 		}
 3141: 	    }
 3142: 	    for (var i=0; i<radioButton.length; i++) {
 3143: 		radioButton[i].checked=false;
 3144: 		if (parseFloat(point) == i) {
 3145: 		    radioButton[i].checked=true;
 3146: 		}
 3147: 	    }
 3148: 
 3149: 	} else {
 3150: 	    textbox.value = parseFloat(point);
 3151: 	}
 3152: 	for (i=0;i<document.classgrade.total.value;i++) {
 3153: 	    var user = document.classgrade["ctr"+i].value;
 3154: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3155: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3156: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3157: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3158: 	    if (saveval != "correct") {
 3159: 		scorename.value = point;
 3160: 		if (selname[0].selected != true) {
 3161: 		    selname[0].selected = true;
 3162: 		}
 3163: 	    }
 3164: 	}
 3165: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3166:     }
 3167: 
 3168:     function writeRadText(partid,weight) {
 3169: 	var selval   = document.classgrade["SELVAL_"+partid];
 3170: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3171:         var override = document.classgrade["FORCE_"+partid].checked;
 3172: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3173: 	if (selval[1].selected || selval[2].selected) {
 3174: 	    for (var i=0; i<radioButton.length; i++) {
 3175: 		radioButton[i].checked=false;
 3176: 
 3177: 	    }
 3178: 	    textbox.value = "";
 3179: 
 3180: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3181: 		var user = document.classgrade["ctr"+i].value;
 3182: 		user = user.replace(new RegExp(':', 'g'),"_");
 3183: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3184: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3185: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3186: 		if ((saveval != "correct") || override) {
 3187: 		    scorename.value = "";
 3188: 		    if (selval[1].selected) {
 3189: 			selname[1].selected = true;
 3190: 		    } else {
 3191: 			selname[2].selected = true;
 3192: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3193: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3194: 		    }
 3195: 		}
 3196: 	    }
 3197: 	} else {
 3198: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3199: 		var user = document.classgrade["ctr"+i].value;
 3200: 		user = user.replace(new RegExp(':', 'g'),"_");
 3201: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3202: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3203: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3204: 		if ((saveval != "correct") || override) {
 3205: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3206: 		    selname[0].selected = true;
 3207: 		}
 3208: 	    }
 3209: 	}	    
 3210:     }
 3211: 
 3212:     function changeSelect(partid,user) {
 3213: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3214: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3215: 	var point  = textbox.value;
 3216: 	var weight = document.classgrade["weight_"+partid].value;
 3217: 
 3218: 	if (isNaN(point) || parseFloat(point) < 0) {
 3219: 	    alert("$alertmsg"+parseFloat(point));
 3220: 	    textbox.value = "";
 3221: 	    return;
 3222: 	}
 3223: 	if (parseFloat(point) > parseFloat(weight)) {
 3224: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3225: 			       ") greater than the weight of the part. Accept?");
 3226: 	    if (resp == false) {
 3227: 		textbox.value = "";
 3228: 		return;
 3229: 	    }
 3230: 	}
 3231: 	selval[0].selected = true;
 3232:     }
 3233: 
 3234:     function changeOneScore(partid,user) {
 3235: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3236: 	if (selval[1].selected || selval[2].selected) {
 3237: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3238: 	    if (selval[2].selected) {
 3239: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3240: 	    }
 3241:         }
 3242:     }
 3243: 
 3244:     function resetEntry(numpart) {
 3245: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3246: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3247: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3248: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3249: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3250: 	    for (var i=0; i<radioButton.length; i++) {
 3251: 		radioButton[i].checked=false;
 3252: 
 3253: 	    }
 3254: 	    textbox.value = "";
 3255: 	    selval[0].selected = true;
 3256: 
 3257: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3258: 		var user = document.classgrade["ctr"+i].value;
 3259: 		user = user.replace(new RegExp(':', 'g'),"_");
 3260: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3261: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3262: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3263: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3264: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3265: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3266: 		if (saveselval == "excused") {
 3267: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3268: 		} else {
 3269: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3270: 		}
 3271: 	    }
 3272: 	}
 3273:     }
 3274: 
 3275: </script>
 3276: VIEWJAVASCRIPT
 3277: }
 3278: 
 3279: #--- show scores for a section or whole class w/ option to change/update a score
 3280: sub viewgrades {
 3281:     my ($request) = shift;
 3282:     &viewgrades_js($request);
 3283: 
 3284:     my ($symb) = &get_symb($request);
 3285:     #need to make sure we have the correct data for later EXT calls, 
 3286:     #thus invalidate the cache
 3287:     &Apache::lonnet::devalidatecourseresdata(
 3288:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3289:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3290:     &Apache::lonnet::clear_EXT_cache_status();
 3291: 
 3292:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3293:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3294: 
 3295:     #view individual student submission form - called using Javascript viewOneStudent
 3296:     $result.=&jscriptNform($symb);
 3297: 
 3298:     #beginning of class grading form
 3299:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3300:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3301: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3302: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3303: 	&build_section_inputs().
 3304: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3305: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3306: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3307: 
 3308:     my ($common_header,$specific_header);
 3309:     if ($env{'form.section'} eq 'all') {
 3310: 	$common_header = &mt('Assign Common Grade to Class');
 3311:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3312:     } elsif ($env{'form.section'} eq 'none') {
 3313:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3314: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3315:     } else {
 3316:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3317:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3318: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3319:     }
 3320:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3321:     #radio buttons/text box for assigning points for a section or class.
 3322:     #handles different parts of a problem
 3323:     my $res_error;
 3324:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3325:     if ($res_error) {
 3326:         return &navmap_errormsg();
 3327:     }
 3328:     my %weight = ();
 3329:     my $ctsparts = 0;
 3330:     my %seen = ();
 3331:     my @part_response_id = &flatten_responseType($responseType);
 3332:     foreach my $part_response_id (@part_response_id) {
 3333:     	my ($partid,$respid) = @{ $part_response_id };
 3334: 	my $part_resp = join('_',@{ $part_response_id });
 3335: 	next if $seen{$partid};
 3336: 	$seen{$partid}++;
 3337: 	my $handgrade=$$handgrade{$part_resp};
 3338: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3339: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3340: 
 3341: 	my $display_part=&get_display_part($partid,$symb);
 3342: 	my $radio.='<table border="0"><tr>';  
 3343: 	my $ctr = 0;
 3344: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3345: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3346: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3347: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3348: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3349: 	    $ctr++;
 3350: 	}
 3351: 	$radio.='</tr></table>';
 3352: 	my $line = '<input type="text" name="TEXTVAL_'.
 3353: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3354: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3355: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3356: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3357: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3358: 		$weight{$partid}.')"> '.
 3359: 	    '<option selected="selected"> </option>'.
 3360: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3361: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3362: 	    '</select></td>'.
 3363:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3364: 	$line.='<input type="hidden" name="partid_'.
 3365: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3366: 	$line.='<input type="hidden" name="weight_'.
 3367: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3368: 
 3369: 	$result.=
 3370: 	    &Apache::loncommon::start_data_table_row()."\n".
 3371: 	    '<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>'.
 3372: 	    &Apache::loncommon::end_data_table_row()."\n";
 3373: 	$ctsparts++;
 3374:     }
 3375:     $result.=&Apache::loncommon::end_data_table()."\n".
 3376: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3377:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3378: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3379: 
 3380:     #table listing all the students in a section/class
 3381:     #header of table
 3382:     $result.= '<h3>'.$specific_header.'</h3>'.
 3383:               &Apache::loncommon::start_data_table().
 3384: 	      &Apache::loncommon::start_data_table_header_row().
 3385: 	      '<th>'.&mt('No.').'</th>'.
 3386: 	      '<th>'.&nameUserString('header')."</th>\n";
 3387:     my $partserror;
 3388:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3389:     if ($partserror) {
 3390:         return &navmap_errormsg();
 3391:     }
 3392:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3393:     my @partids = ();
 3394:     foreach my $part (@parts) {
 3395: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3396:         my $narrowtext = &mt('Tries');
 3397: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3398: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3399: 	my ($partid) = &split_part_type($part);
 3400:         push(@partids,$partid);
 3401: 	my $display_part=&get_display_part($partid,$symb);
 3402: 	if ($display =~ /^Partial Credit Factor/) {
 3403: 	    $result.='<th>'.
 3404: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3405: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3406: 	    next;
 3407: 	    
 3408: 	} else {
 3409: 	    if ($display =~ /Problem Status/) {
 3410: 		my $grade_status_mt = &mt('Grade Status');
 3411: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3412: 	    }
 3413: 	    my $part_mt = &mt('Part:');
 3414: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3415: 	}
 3416: 
 3417: 	$result.='<th>'.$display.'</th>'."\n";
 3418:     }
 3419:     $result.=&Apache::loncommon::end_data_table_header_row();
 3420: 
 3421:     my %last_resets = 
 3422: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3423: 
 3424:     #get info for each student
 3425:     #list all the students - with points and grade status
 3426:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3427:     my $ctr = 0;
 3428:     foreach (sort 
 3429: 	     {
 3430: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3431: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3432: 		 }
 3433: 		 return $a cmp $b;
 3434: 	     } (keys(%$fullname))) {
 3435: 	$ctr++;
 3436: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3437: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3438:     }
 3439:     $result.=&Apache::loncommon::end_data_table();
 3440:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3441:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3442: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3443:     if (scalar(%$fullname) eq 0) {
 3444: 	my $colspan=3+scalar(@parts);
 3445: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3446:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3447: 	$result='<span class="LC_warning">'.
 3448: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3449: 	        $section_display, $stu_status).
 3450: 	    '</span>';
 3451:     }
 3452:     $result.=&show_grading_menu_form($symb);
 3453:     return $result;
 3454: }
 3455: 
 3456: #--- call by previous routine to display each student
 3457: sub viewstudentgrade {
 3458:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3459:     my ($uname,$udom) = split(/:/,$student);
 3460:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3461:     my %aggregates = (); 
 3462:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3463: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3464: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3465: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3466: 	'\');" target="_self">'.$fullname.'</a> '.
 3467: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3468:     $student=~s/:/_/; # colon doen't work in javascript for names
 3469:     foreach my $apart (@$parts) {
 3470: 	my ($part,$type) = &split_part_type($apart);
 3471: 	my $score=$record{"resource.$part.$type"};
 3472:         $result.='<td align="center">';
 3473:         my ($aggtries,$totaltries);
 3474:         unless (exists($aggregates{$part})) {
 3475: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3476: 
 3477: 	    $aggtries = $totaltries;
 3478:             if ($$last_resets{$part}) {  
 3479:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3480: 					   $part);
 3481:             }
 3482:             $result.='<input type="hidden" name="'.
 3483:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3484:             $result.='<input type="hidden" name="'.
 3485:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3486:             $aggregates{$part} = 1;
 3487:         }
 3488: 	if ($type eq 'awarded') {
 3489: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3490: 	    $result.='<input type="hidden" name="'.
 3491: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3492: 	    $result.='<input type="text" name="'.
 3493: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3494: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3495: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3496: 	} elsif ($type eq 'solved') {
 3497: 	    my ($status,$foo)=split(/_/,$score,2);
 3498: 	    $status = 'nothing' if ($status eq '');
 3499: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3500: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3501: 	    $result.='&nbsp;<select name="'.
 3502: 		'GD_'.$student.'_'.$part.'_solved" '.
 3503: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3504: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3505: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3506: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3507: 	    $result.="</select>&nbsp;</td>\n";
 3508: 	} else {
 3509: 	    $result.='<input type="hidden" name="'.
 3510: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3511: 		    "\n";
 3512: 	    $result.='<input type="text" name="'.
 3513: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3514: 		'value="'.$score.'" size="4" /></td>'."\n";
 3515: 	}
 3516:     }
 3517:     $result.=&Apache::loncommon::end_data_table_row();
 3518:     return $result;
 3519: }
 3520: 
 3521: #--- change scores for all the students in a section/class
 3522: #    record does not get update if unchanged
 3523: sub editgrades {
 3524:     my ($request) = @_;
 3525: 
 3526:     my $symb=&get_symb($request);
 3527:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3528:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3529:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3530:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3531: 
 3532:     my $result= &Apache::loncommon::start_data_table().
 3533: 	&Apache::loncommon::start_data_table_header_row().
 3534: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3535: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3536:     my %scoreptr = (
 3537: 		    'correct'  =>'correct_by_override',
 3538: 		    'incorrect'=>'incorrect_by_override',
 3539: 		    'excused'  =>'excused',
 3540: 		    'ungraded' =>'ungraded_attempted',
 3541: 		    'nothing'  => '',
 3542: 		    );
 3543:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3544: 
 3545:     my (@partid);
 3546:     my %weight = ();
 3547:     my %columns = ();
 3548:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3549: 
 3550:     my $partserror;
 3551:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3552:     if ($partserror) {
 3553:         return &navmap_errormsg();
 3554:     }
 3555:     my $header;
 3556:     while ($ctr < $env{'form.totalparts'}) {
 3557: 	my $partid = $env{'form.partid_'.$ctr};
 3558: 	push(@partid,$partid);
 3559: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3560: 	$ctr++;
 3561:     }
 3562:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3563:     foreach my $partid (@partid) {
 3564: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3565: 	    '<th align="center">'.&mt('New Score').'</th>';
 3566: 	$columns{$partid}=2;
 3567: 	foreach my $stores (@parts) {
 3568: 	    my ($part,$type) = &split_part_type($stores);
 3569: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3570: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3571: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3572: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3573:             my $narrowtext = &mt('Tries');
 3574: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3575: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3576: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3577: 	    $columns{$partid}+=2;
 3578: 	}
 3579:     }
 3580:     foreach my $partid (@partid) {
 3581: 	my $display_part=&get_display_part($partid,$symb);
 3582: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3583: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3584: 	    '</th>';
 3585: 
 3586:     }
 3587:     $result .= &Apache::loncommon::end_data_table_header_row().
 3588: 	&Apache::loncommon::start_data_table_header_row().
 3589: 	$header.
 3590: 	&Apache::loncommon::end_data_table_header_row();
 3591:     my @noupdate;
 3592:     my ($updateCtr,$noupdateCtr) = (1,1);
 3593:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3594: 	my $line;
 3595: 	my $user = $env{'form.ctr'.$i};
 3596: 	my ($uname,$udom)=split(/:/,$user);
 3597: 	my %newrecord;
 3598: 	my $updateflag = 0;
 3599: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3600: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3601: 	if (!&canmodify($usec)) {
 3602: 	    my $numcols=scalar(@partid)*4+2;
 3603: 	    push(@noupdate,
 3604: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3605: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3606: 	    next;
 3607: 	}
 3608:         my %aggregate = ();
 3609:         my $aggregateflag = 0;
 3610: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3611: 	foreach (@partid) {
 3612: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3613: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3614: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3615: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3616: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3617: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3618: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3619: 	    my $score;
 3620: 	    if ($partial eq '') {
 3621: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3622: 	    } elsif ($partial > 0) {
 3623: 		$score = 'correct_by_override';
 3624: 	    } elsif ($partial == 0) {
 3625: 		$score = 'incorrect_by_override';
 3626: 	    }
 3627: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3628: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3629: 
 3630: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3631: 		"$env{'user.name'}:$env{'user.domain'}";
 3632: 	    if ($dropMenu eq 'reset status' &&
 3633: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3634: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3635: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3636: 		$newrecord{'resource.'.$_.'.award'} = '';
 3637: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3638: 		$updateflag = 1;
 3639:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3640:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3641:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3642:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3643:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3644:                     $aggregateflag = 1;
 3645:                 }
 3646: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3647: 		$updateflag = 1;
 3648: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3649: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3650: 		$rec_update++;
 3651: 	    }
 3652: 
 3653: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3654: 		'<td align="center">'.$awarded.
 3655: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3656: 
 3657: 
 3658: 	    my $partid=$_;
 3659: 	    foreach my $stores (@parts) {
 3660: 		my ($part,$type) = &split_part_type($stores);
 3661: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3662: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3663: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3664: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3665: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3666: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3667: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3668: 		    $updateflag=1;
 3669: 		}
 3670: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3671: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3672: 	    }
 3673: 	}
 3674: 	$line.="\n";
 3675: 
 3676: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3677: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3678: 
 3679: 	if ($updateflag) {
 3680: 	    $count++;
 3681: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3682: 				    $udom,$uname);
 3683: 
 3684: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3685: 					      $cnum,$udom,$uname)) {
 3686: 		# need to figure out if should be in queue.
 3687: 		my %record =  
 3688: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3689: 					     $udom,$uname);
 3690: 		my $all_graded = 1;
 3691: 		my $none_graded = 1;
 3692: 		foreach my $part (@parts) {
 3693: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3694: 			$all_graded = 0;
 3695: 		    } else {
 3696: 			$none_graded = 0;
 3697: 		    }
 3698: 		}
 3699: 
 3700: 		if ($all_graded || $none_graded) {
 3701: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3702: 							   $symb,$cdom,$cnum,
 3703: 							   $udom,$uname);
 3704: 		}
 3705: 	    }
 3706: 
 3707: 	    $result.=&Apache::loncommon::start_data_table_row().
 3708: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3709: 		&Apache::loncommon::end_data_table_row();
 3710: 	    $updateCtr++;
 3711: 	} else {
 3712: 	    push(@noupdate,
 3713: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3714: 	    $noupdateCtr++;
 3715: 	}
 3716:         if ($aggregateflag) {
 3717:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3718: 				  $cdom,$cnum);
 3719:         }
 3720:     }
 3721:     if (@noupdate) {
 3722: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3723: 	my $numcols=scalar(@partid)*4+2;
 3724: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3725: 	    '<td align="center" colspan="'.$numcols.'">'.
 3726: 	    &mt('No Changes Occurred For the Students Below').
 3727: 	    '</td>'.
 3728: 	    &Apache::loncommon::end_data_table_row();
 3729: 	foreach my $line (@noupdate) {
 3730: 	    $result.=
 3731: 		&Apache::loncommon::start_data_table_row().
 3732: 		$line.
 3733: 		&Apache::loncommon::end_data_table_row();
 3734: 	}
 3735:     }
 3736:     $result .= &Apache::loncommon::end_data_table().
 3737: 	&show_grading_menu_form($symb);
 3738:     my $msg = '<p><b>'.
 3739: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3740: 	    $rec_update,$count).'</b><br />'.
 3741: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3742: 	'</b></p>';
 3743:     return $title.$msg.$result;
 3744: }
 3745: 
 3746: sub split_part_type {
 3747:     my ($partstr) = @_;
 3748:     my ($temp,@allparts)=split(/_/,$partstr);
 3749:     my $type=pop(@allparts);
 3750:     my $part=join('_',@allparts);
 3751:     return ($part,$type);
 3752: }
 3753: 
 3754: #------------- end of section for handling grading by section/class ---------
 3755: #
 3756: #----------------------------------------------------------------------------
 3757: 
 3758: 
 3759: #----------------------------------------------------------------------------
 3760: #
 3761: #-------------------------- Next few routines handles grading by csv upload
 3762: #
 3763: #--- Javascript to handle csv upload
 3764: sub csvupload_javascript_reverse_associate {
 3765:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3766:     my $error2=&mt('You need to specify at least one grading field');
 3767:   return(<<ENDPICK);
 3768:   function verify(vf) {
 3769:     var foundsomething=0;
 3770:     var founduname=0;
 3771:     var foundID=0;
 3772:     for (i=0;i<=vf.nfields.value;i++) {
 3773:       tw=eval('vf.f'+i+'.selectedIndex');
 3774:       if (i==0 && tw!=0) { foundID=1; }
 3775:       if (i==1 && tw!=0) { founduname=1; }
 3776:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3777:     }
 3778:     if (founduname==0 && foundID==0) {
 3779: 	alert('$error1');
 3780: 	return;
 3781:     }
 3782:     if (foundsomething==0) {
 3783: 	alert('$error2');
 3784: 	return;
 3785:     }
 3786:     vf.submit();
 3787:   }
 3788:   function flip(vf,tf) {
 3789:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3790:     var i;
 3791:     for (i=0;i<=vf.nfields.value;i++) {
 3792:       //can not pick the same destination field for both name and domain
 3793:       if (((i ==0)||(i ==1)) && 
 3794:           ((tf==0)||(tf==1)) && 
 3795:           (i!=tf) &&
 3796:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3797:         eval('vf.f'+i+'.selectedIndex=0;')
 3798:       }
 3799:     }
 3800:   }
 3801: ENDPICK
 3802: }
 3803: 
 3804: sub csvupload_javascript_forward_associate {
 3805:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3806:     my $error2=&mt('You need to specify at least one grading field');
 3807:   return(<<ENDPICK);
 3808:   function verify(vf) {
 3809:     var foundsomething=0;
 3810:     var founduname=0;
 3811:     var foundID=0;
 3812:     for (i=0;i<=vf.nfields.value;i++) {
 3813:       tw=eval('vf.f'+i+'.selectedIndex');
 3814:       if (tw==1) { foundID=1; }
 3815:       if (tw==2) { founduname=1; }
 3816:       if (tw>3) { foundsomething=1; }
 3817:     }
 3818:     if (founduname==0 && foundID==0) {
 3819: 	alert('$error1');
 3820: 	return;
 3821:     }
 3822:     if (foundsomething==0) {
 3823: 	alert('$error2');
 3824: 	return;
 3825:     }
 3826:     vf.submit();
 3827:   }
 3828:   function flip(vf,tf) {
 3829:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3830:     var i;
 3831:     //can not pick the same destination field twice
 3832:     for (i=0;i<=vf.nfields.value;i++) {
 3833:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3834:         eval('vf.f'+i+'.selectedIndex=0;')
 3835:       }
 3836:     }
 3837:   }
 3838: ENDPICK
 3839: }
 3840: 
 3841: sub csvuploadmap_header {
 3842:     my ($request,$symb,$datatoken,$distotal)= @_;
 3843:     my $javascript;
 3844:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3845: 	$javascript=&csvupload_javascript_reverse_associate();
 3846:     } else {
 3847: 	$javascript=&csvupload_javascript_forward_associate();
 3848:     }
 3849: 
 3850:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3851:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3852:     my $ignore=&mt('Ignore First Line');
 3853:     $symb = &Apache::lonenc::check_encrypt($symb);
 3854:     $request->print(<<ENDPICK);
 3855: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3856: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3857: $result
 3858: <hr />
 3859: <h3>Identify fields</h3>
 3860: Total number of records found in file: $distotal <hr />
 3861: Enter as many fields as you can. The system will inform you and bring you back
 3862: to this page if the data selected is insufficient to run your class.<hr />
 3863: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3864: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3865: <input type="hidden" name="associate"  value="" />
 3866: <input type="hidden" name="phase"      value="three" />
 3867: <input type="hidden" name="datatoken"  value="$datatoken" />
 3868: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3869: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3870: <input type="hidden" name="upfile_associate" 
 3871:                                        value="$env{'form.upfile_associate'}" />
 3872: <input type="hidden" name="symb"       value="$symb" />
 3873: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3874: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3875: <input type="hidden" name="command"    value="csvuploadoptions" />
 3876: <hr />
 3877: <script type="text/javascript" language="Javascript">
 3878: $javascript
 3879: </script>
 3880: ENDPICK
 3881:     return '';
 3882: 
 3883: }
 3884: 
 3885: sub csvupload_fields {
 3886:     my ($symb,$errorref) = @_;
 3887:     my (@parts) = &getpartlist($symb,$errorref);
 3888:     if (ref($errorref)) {
 3889:         if ($$errorref) {
 3890:             return;
 3891:         }
 3892:     }
 3893: 
 3894:     my @fields=(['ID','Student/Employee ID'],
 3895: 		['username','Student Username'],
 3896: 		['domain','Student Domain']);
 3897:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3898:     foreach my $part (sort(@parts)) {
 3899: 	my @datum;
 3900: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3901: 	my $name=$part;
 3902: 	if  (!$display) { $display = $name; }
 3903: 	@datum=($name,$display);
 3904: 	if ($name=~/^stores_(.*)_awarded/) {
 3905: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3906: 	}
 3907: 	push(@fields,\@datum);
 3908:     }
 3909:     return (@fields);
 3910: }
 3911: 
 3912: sub csvuploadmap_footer {
 3913:     my ($request,$i,$keyfields) =@_;
 3914:     $request->print(<<ENDPICK);
 3915: </table>
 3916: <input type="hidden" name="nfields" value="$i" />
 3917: <input type="hidden" name="keyfields" value="$keyfields" />
 3918: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3919: </form>
 3920: ENDPICK
 3921: }
 3922: 
 3923: sub checkforfile_js {
 3924:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3925:     my $result =<<CSVFORMJS;
 3926: <script type="text/javascript" language="javascript">
 3927:     function checkUpload(formname) {
 3928: 	if (formname.upfile.value == "") {
 3929: 	    alert("$alertmsg");
 3930: 	    return false;
 3931: 	}
 3932: 	formname.submit();
 3933:     }
 3934:     </script>
 3935: CSVFORMJS
 3936:     return $result;
 3937: }
 3938: 
 3939: sub upcsvScores_form {
 3940:     my ($request) = shift;
 3941:     my ($symb)=&get_symb($request);
 3942:     if (!$symb) {return '';}
 3943:     my $result=&checkforfile_js();
 3944:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3945:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3946:     $result.=$table;
 3947:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3948:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3949:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3950: 	'</b></td></tr>'."\n";
 3951:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3952:     my $upload=&mt("Upload Scores");
 3953:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3954:     my $ignore=&mt('Ignore First Line');
 3955:     $symb = &Apache::lonenc::check_encrypt($symb);
 3956:     $result.=<<ENDUPFORM;
 3957: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3958: <input type="hidden" name="symb" value="$symb" />
 3959: <input type="hidden" name="command" value="csvuploadmap" />
 3960: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3961: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3962: $upfile_select
 3963: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3964: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3965: </form>
 3966: ENDUPFORM
 3967:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3968:                            &mt("How do I create a CSV file from a spreadsheet"))
 3969:     .'</td></tr></table>'."\n";
 3970:     $result.='</td></tr></table><br /><br />'."\n";
 3971:     $result.=&show_grading_menu_form($symb);
 3972:     return $result;
 3973: }
 3974: 
 3975: 
 3976: sub csvuploadmap {
 3977:     my ($request)= @_;
 3978:     my ($symb)=&get_symb($request);
 3979:     if (!$symb) {return '';}
 3980: 
 3981:     my $datatoken;
 3982:     if (!$env{'form.datatoken'}) {
 3983: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3984:     } else {
 3985: 	$datatoken=$env{'form.datatoken'};
 3986: 	&Apache::loncommon::load_tmp_file($request);
 3987:     }
 3988:     my @records=&Apache::loncommon::upfile_record_sep();
 3989:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3990:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3991:     my ($i,$keyfields);
 3992:     if (@records) {
 3993:         my $fieldserror;
 3994: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3995:         if ($fieldserror) {
 3996:             $request->print(&navmap_errormsg());
 3997:             return;
 3998:         }
 3999: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4000: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4001: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4002: 							  \@fields);
 4003: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4004: 	    chop($keyfields);
 4005: 	} else {
 4006: 	    unshift(@fields,['none','']);
 4007: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4008: 							    \@fields);
 4009:             foreach my $rec (@records) {
 4010:                 my %temp = &Apache::loncommon::record_sep($rec);
 4011:                 if (%temp) {
 4012:                     $keyfields=join(',',sort(keys(%temp)));
 4013:                     last;
 4014:                 }
 4015:             }
 4016: 	}
 4017:     }
 4018:     &csvuploadmap_footer($request,$i,$keyfields);
 4019:     $request->print(&show_grading_menu_form($symb));
 4020: 
 4021:     return '';
 4022: }
 4023: 
 4024: sub csvuploadoptions {
 4025:     my ($request)= @_;
 4026:     my ($symb)=&get_symb($request);
 4027:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4028:     my $ignore=&mt('Ignore First Line');
 4029:     $request->print(<<ENDPICK);
 4030: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4031: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4032: <input type="hidden" name="command"    value="csvuploadassign" />
 4033: <!--
 4034: <p>
 4035: <label>
 4036:    <input type="checkbox" name="show_full_results" />
 4037:    Show a table of all changes
 4038: </label>
 4039: </p>
 4040: -->
 4041: <p>
 4042: <label>
 4043:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4044:    Overwrite any existing score
 4045: </label>
 4046: </p>
 4047: ENDPICK
 4048:     my %fields=&get_fields();
 4049:     if (!defined($fields{'domain'})) {
 4050: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4051: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4052:     }
 4053:     foreach my $key (sort(keys(%env))) {
 4054: 	if ($key !~ /^form\.(.*)$/) { next; }
 4055: 	my $cleankey=$1;
 4056: 	if ($cleankey eq 'command') { next; }
 4057: 	$request->print('<input type="hidden" name="'.$cleankey.
 4058: 			'"  value="'.$env{$key}.'" />'."\n");
 4059:     }
 4060:     # FIXME do a check for any duplicated user ids...
 4061:     # FIXME do a check for any invalid user ids?...
 4062:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4063: <hr /></form>'."\n");
 4064:     $request->print(&show_grading_menu_form($symb));
 4065:     return '';
 4066: }
 4067: 
 4068: sub get_fields {
 4069:     my %fields;
 4070:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4071:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4072: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4073: 	    if ($env{'form.f'.$i} ne 'none') {
 4074: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4075: 	    }
 4076: 	} else {
 4077: 	    if ($env{'form.f'.$i} ne 'none') {
 4078: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4079: 	    }
 4080: 	}
 4081:     }
 4082:     return %fields;
 4083: }
 4084: 
 4085: sub csvuploadassign {
 4086:     my ($request)= @_;
 4087:     my ($symb)=&get_symb($request);
 4088:     if (!$symb) {return '';}
 4089:     my $error_msg = '';
 4090:     &Apache::loncommon::load_tmp_file($request);
 4091:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4092:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4093:     my %fields=&get_fields();
 4094:     $request->print('<h3>Assigning Grades</h3>');
 4095:     my $courseid=$env{'request.course.id'};
 4096:     my ($classlist) = &getclasslist('all',0);
 4097:     my @notallowed;
 4098:     my @skipped;
 4099:     my $countdone=0;
 4100:     foreach my $grade (@gradedata) {
 4101: 	my %entries=&Apache::loncommon::record_sep($grade);
 4102: 	my $domain;
 4103: 	if ($entries{$fields{'domain'}}) {
 4104: 	    $domain=$entries{$fields{'domain'}};
 4105: 	} else {
 4106: 	    $domain=$env{'form.default_domain'};
 4107: 	}
 4108: 	$domain=~s/\s//g;
 4109: 	my $username=$entries{$fields{'username'}};
 4110: 	$username=~s/\s//g;
 4111: 	if (!$username) {
 4112: 	    my $id=$entries{$fields{'ID'}};
 4113: 	    $id=~s/\s//g;
 4114: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4115: 	    $username=$ids{$id};
 4116: 	}
 4117: 	if (!exists($$classlist{"$username:$domain"})) {
 4118: 	    my $id=$entries{$fields{'ID'}};
 4119: 	    $id=~s/\s//g;
 4120: 	    if ($id) {
 4121: 		push(@skipped,"$id:$domain");
 4122: 	    } else {
 4123: 		push(@skipped,"$username:$domain");
 4124: 	    }
 4125: 	    next;
 4126: 	}
 4127: 	my $usec=$classlist->{"$username:$domain"}[5];
 4128: 	if (!&canmodify($usec)) {
 4129: 	    push(@notallowed,"$username:$domain");
 4130: 	    next;
 4131: 	}
 4132: 	my %points;
 4133: 	my %grades;
 4134: 	foreach my $dest (keys(%fields)) {
 4135: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4136: 		$dest eq 'domain') { next; }
 4137: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4138: 	    if ($dest=~/stores_(.*)_points/) {
 4139: 		my $part=$1;
 4140: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4141: 					      $symb,$domain,$username);
 4142:                 if ($wgt) {
 4143:                     $entries{$fields{$dest}}=~s/\s//g;
 4144:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4145:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4146:                                           : 'correct_by_override';
 4147:                     $grades{"resource.$part.awarded"}=$pcr;
 4148:                     $grades{"resource.$part.solved"}=$award;
 4149:                     $points{$part}=1;
 4150:                 } else {
 4151:                     $error_msg = "<br />" .
 4152:                         &mt("Some point values were assigned"
 4153:                             ." for problems with a weight "
 4154:                             ."of zero. These values were "
 4155:                             ."ignored.");
 4156:                 }
 4157: 	    } else {
 4158: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4159: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4160: 		my $store_key=$dest;
 4161: 		$store_key=~s/^stores/resource/;
 4162: 		$store_key=~s/_/\./g;
 4163: 		$grades{$store_key}=$entries{$fields{$dest}};
 4164: 	    }
 4165: 	}
 4166: 	if (! %grades) { 
 4167:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4168:         } else {
 4169: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4170: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4171: 					   $env{'request.course.id'},
 4172: 					   $domain,$username);
 4173: 	   if ($result eq 'ok') {
 4174: 	      $request->print('.');
 4175: 	   } else {
 4176: 	      $request->print("<p><span class=\"LC_error\">".
 4177:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4178:                                   "$username:$domain",$result)."</span></p>");
 4179: 	   }
 4180: 	   $request->rflush();
 4181: 	   $countdone++;
 4182:         }
 4183:     }
 4184:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4185:     if (@skipped) {
 4186: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4187:         $request->print(join(', ',@skipped));
 4188:     }
 4189:     if (@notallowed) {
 4190: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4191: 	$request->print(join(', ',@notallowed));
 4192:     }
 4193:     $request->print("<br />\n");
 4194:     $request->print(&show_grading_menu_form($symb));
 4195:     return $error_msg;
 4196: }
 4197: #------------- end of section for handling csv file upload ---------
 4198: #
 4199: #-------------------------------------------------------------------
 4200: #
 4201: #-------------- Next few routines handle grading by page/sequence
 4202: #
 4203: #--- Select a page/sequence and a student to grade
 4204: sub pickStudentPage {
 4205:     my ($request) = shift;
 4206: 
 4207:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4208:     $request->print(<<LISTJAVASCRIPT);
 4209: <script type="text/javascript" language="javascript">
 4210: 
 4211: function checkPickOne(formname) {
 4212:     if (radioSelection(formname.student) == null) {
 4213: 	alert("$alertmsg");
 4214: 	return;
 4215:     }
 4216:     ptr = pullDownSelection(formname.selectpage);
 4217:     formname.page.value = formname["page"+ptr].value;
 4218:     formname.title.value = formname["title"+ptr].value;
 4219:     formname.submit();
 4220: }
 4221: 
 4222: </script>
 4223: LISTJAVASCRIPT
 4224:     &commonJSfunctions($request);
 4225:     my ($symb) = &get_symb($request);
 4226:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4227:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4228:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4229: 
 4230:     my $result='<h3><span class="LC_info">&nbsp;'.
 4231: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4232: 
 4233:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4234:     my $map_error;
 4235:     my ($titles,$symbx) = &getSymbMap($map_error);
 4236:     if ($map_error) {
 4237:         $request->print(&navmap_errormsg());
 4238:         return; 
 4239:     }
 4240:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4241: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4242: #    my $type=($curpage =~ /\.(page|sequence)/);
 4243:     my $select = '<select name="selectpage">'."\n";
 4244:     my $ctr=0;
 4245:     foreach (@$titles) {
 4246: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4247: 	$select.='<option value="'.$ctr.'" '.
 4248: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4249: 	    '>'.$showtitle.'</option>'."\n";
 4250: 	$ctr++;
 4251:     }
 4252:     $select.= '</select>';
 4253:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4254: 
 4255:     $ctr=0;
 4256:     foreach (@$titles) {
 4257: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4258: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4259: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4260: 	$ctr++;
 4261:     }
 4262:     $result.='<input type="hidden" name="page" />'."\n".
 4263: 	'<input type="hidden" name="title" />'."\n";
 4264: 
 4265:     my $options =
 4266: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4267: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4268:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4269: 
 4270:     $options =
 4271: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4272: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4273: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4274:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4275:     
 4276:     $result.=&build_section_inputs();
 4277:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4278:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4279: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4281: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4282: 
 4283:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4284: 
 4285:     $result.='&nbsp;<input type="button" '.
 4286: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4287: 
 4288:     $request->print($result);
 4289: 
 4290:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4291: 	&Apache::loncommon::start_data_table().
 4292: 	&Apache::loncommon::start_data_table_header_row().
 4293: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4294: 	'<th>'.&nameUserString('header').'</th>'.
 4295: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4296: 	'<th>'.&nameUserString('header').'</th>'.
 4297: 	&Apache::loncommon::end_data_table_header_row();
 4298:  
 4299:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4300:     my $ptr = 1;
 4301:     foreach my $student (sort 
 4302: 			 {
 4303: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4304: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4305: 			     }
 4306: 			     return $a cmp $b;
 4307: 			 } (keys(%$fullname))) {
 4308: 	my ($uname,$udom) = split(/:/,$student);
 4309: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4310:                                   : '</td>');
 4311: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4312: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4313: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4314: 	$studentTable.=
 4315: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4316:                          : '');
 4317: 	$ptr++;
 4318:     }
 4319:     if ($ptr%2 == 0) {
 4320: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4321: 	    &Apache::loncommon::end_data_table_row();
 4322:     }
 4323:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4324:     $studentTable.='<input type="button" '.
 4325: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4326: 
 4327:     $studentTable.=&show_grading_menu_form($symb);
 4328:     $request->print($studentTable);
 4329: 
 4330:     return '';
 4331: }
 4332: 
 4333: sub getSymbMap {
 4334:     my ($map_error) = @_;
 4335:     my $navmap = Apache::lonnavmaps::navmap->new();
 4336:     unless (ref($navmap)) {
 4337:         if (ref($map_error)) {
 4338:             $$map_error = 'navmap';
 4339:         }
 4340:         return;
 4341:     }
 4342:     my %symbx = ();
 4343:     my @titles = ();
 4344:     my $minder = 0;
 4345: 
 4346:     # Gather every sequence that has problems.
 4347:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4348: 					       1,0,1);
 4349:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4350: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4351: 	    my $title = $minder.'.'.
 4352: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4353: 	    push(@titles, $title); # minder in case two titles are identical
 4354: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4355: 	    $minder++;
 4356: 	}
 4357:     }
 4358:     return \@titles,\%symbx;
 4359: }
 4360: 
 4361: #
 4362: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4363: sub displayPage {
 4364:     my ($request) = shift;
 4365: 
 4366:     my ($symb) = &get_symb($request);
 4367:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4368:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4369:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4370:     my $pageTitle = $env{'form.page'};
 4371:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4372:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4373:     my $usec=$classlist->{$env{'form.student'}}[5];
 4374: 
 4375:     #need to make sure we have the correct data for later EXT calls, 
 4376:     #thus invalidate the cache
 4377:     &Apache::lonnet::devalidatecourseresdata(
 4378:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4379:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4380:     &Apache::lonnet::clear_EXT_cache_status();
 4381: 
 4382:     if (!&canview($usec)) {
 4383: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4384: 	$request->print(&show_grading_menu_form($symb));
 4385: 	return;
 4386:     }
 4387:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4388:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4389: 	'</h3>'."\n";
 4390:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4391:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4392: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4393:     } else {
 4394: 	delete($env{'form.CODE'});
 4395:     }
 4396:     &sub_page_js($request);
 4397:     $request->print($result);
 4398: 
 4399:     my $navmap = Apache::lonnavmaps::navmap->new();
 4400:     unless (ref($navmap)) {
 4401:         $request->print(&navmap_errormsg());
 4402:         $request->print(&show_grading_menu_form($symb));
 4403:         return;
 4404:     }
 4405:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4406:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4407:     if (!$map) {
 4408: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4409: 	$request->print(&show_grading_menu_form($symb));
 4410: 	return; 
 4411:     }
 4412:     my $iterator = $navmap->getIterator($map->map_start(),
 4413: 					$map->map_finish());
 4414: 
 4415:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4416: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4417: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4418: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4419: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4420: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4421: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4422: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4423: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4424: 
 4425:     if (defined($env{'form.CODE'})) {
 4426: 	$studentTable.=
 4427: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4428:     }
 4429:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4430: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4431: 
 4432:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4433: 	&Apache::loncommon::start_data_table().
 4434: 	&Apache::loncommon::start_data_table_header_row().
 4435: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4436: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4437: 	&Apache::loncommon::end_data_table_header_row();
 4438: 
 4439:     &Apache::lonxml::clear_problem_counter();
 4440:     my ($depth,$question,$prob) = (1,1,1);
 4441:     $iterator->next(); # skip the first BEGIN_MAP
 4442:     my $curRes = $iterator->next(); # for "current resource"
 4443:     while ($depth > 0) {
 4444:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4445:         if($curRes == $iterator->END_MAP) { $depth--; }
 4446: 
 4447:         if (ref($curRes) && $curRes->is_problem()) {
 4448: 	    my $parts = $curRes->parts();
 4449:             my $title = $curRes->compTitle();
 4450: 	    my $symbx = $curRes->symb();
 4451: 	    $studentTable.=
 4452: 		&Apache::loncommon::start_data_table_row().
 4453: 		'<td align="center" valign="top" >'.$prob.
 4454: 		(scalar(@{$parts}) == 1 ? '' 
 4455: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4456: 							scalar(@{$parts}))
 4457: 		 ).
 4458: 		 '</td>';
 4459: 	    $studentTable.='<td valign="top">';
 4460: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4461: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4462: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4463: 					     undef,'both',\%form);
 4464: 	    } else {
 4465: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4466: 		$companswer =~ s|<form(.*?)>||g;
 4467: 		$companswer =~ s|</form>||g;
 4468: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4469: #		    $companswer =~ s/$1/ /ms;
 4470: #		    $request->print('match='.$1."<br />\n");
 4471: #		}
 4472: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4473: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4474: 	    }
 4475: 
 4476: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4477: 
 4478: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4479: 		if ($record{'version'} eq '') {
 4480: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4481: 		} else {
 4482: 		    my %responseType = ();
 4483: 		    foreach my $partid (@{$parts}) {
 4484: 			my @responseIds =$curRes->responseIds($partid);
 4485: 			my @responseType =$curRes->responseType($partid);
 4486: 			my %responseIds;
 4487: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4488: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4489: 			}
 4490: 			$responseType{$partid} = \%responseIds;
 4491: 		    }
 4492: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4493: 
 4494: 		}
 4495: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4496: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4497: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4498: 									$env{'request.course.id'},
 4499: 									'','.submission');
 4500:  
 4501: 	    }
 4502: 	    if (&canmodify($usec)) {
 4503:             $studentTable.=&gradeBox_start();
 4504: 		foreach my $partid (@{$parts}) {
 4505: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4506: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4507: 		    $question++;
 4508: 		}
 4509:             $studentTable.=&gradeBox_end();
 4510: 		$prob++;
 4511: 	    }
 4512: 	    $studentTable.='</td></tr>';
 4513: 
 4514: 	}
 4515:         $curRes = $iterator->next();
 4516:     }
 4517: 
 4518:     $studentTable.='</table>'."\n".
 4519: 	'<input type="button" value="'.&mt('Save').'" '.
 4520: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4521: 	'</form>'."\n";
 4522:     $studentTable.=&show_grading_menu_form($symb);
 4523:     $request->print($studentTable);
 4524: 
 4525:     return '';
 4526: }
 4527: 
 4528: sub displaySubByDates {
 4529:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4530:     my $isCODE=0;
 4531:     my $isTask = ($symb =~/\.task$/);
 4532:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4533:     my $studentTable=&Apache::loncommon::start_data_table().
 4534: 	&Apache::loncommon::start_data_table_header_row().
 4535: 	'<th>'.&mt('Date/Time').'</th>'.
 4536: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4537: 	'<th>'.&mt('Submission').'</th>'.
 4538: 	'<th>'.&mt('Status').'</th>'.
 4539: 	&Apache::loncommon::end_data_table_header_row();
 4540:     my ($version);
 4541:     my %mark;
 4542:     my %orders;
 4543:     $mark{'correct_by_student'} = $checkIcon;
 4544:     if (!exists($$record{'1:timestamp'})) {
 4545: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4546:     }
 4547: 
 4548:     my $interaction;
 4549:     my $no_increment = 1;
 4550:     for ($version=1;$version<=$$record{'version'};$version++) {
 4551: 	my $timestamp = 
 4552: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4553: 	if (exists($$record{$version.':resource.0.version'})) {
 4554: 	    $interaction = $$record{$version.':resource.0.version'};
 4555: 	}
 4556: 
 4557: 	my $where = ($isTask ? "$version:resource.$interaction"
 4558: 		             : "$version:resource");
 4559: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4560: 	    '<td>'.$timestamp.'</td>';
 4561: 	if ($isCODE) {
 4562: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4563: 	}
 4564: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4565: 	my @displaySub = ();
 4566: 	foreach my $partid (@{$parts}) {
 4567: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4568: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4569: 	    
 4570: 
 4571: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4572: 	    my $display_part=&get_display_part($partid,$symb);
 4573: 	    foreach my $matchKey (@matchKey) {
 4574: 		if (exists($$record{$version.':'.$matchKey}) &&
 4575: 		    $$record{$version.':'.$matchKey} ne '') {
 4576: 
 4577: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4578: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4579:                     $displaySub[0].='<span class="LC_nobreak"';
 4580:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4581:                                    .' <span class="LC_internal_info">'
 4582:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4583:                                    .'</span>'
 4584:                                    .' <b>';
 4585: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4586: 			$displaySub[0].=&mt('Trial not counted');
 4587: 		    } else {
 4588: 			$displaySub[0].=&mt('Trial: [_1]',
 4589: 					    $$record{"$where.$partid.tries"});
 4590: 		    }
 4591: 		    my $responseType=($isTask ? 'Task'
 4592:                                               : $responseType->{$partid}->{$responseId});
 4593: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4594: 		    if (!exists($orders{$partid}->{$responseId})) {
 4595: 			$orders{$partid}->{$responseId}=
 4596: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4597:                                        $no_increment);
 4598: 		    }
 4599: 		    $displaySub[0].='</b></span>'; # /nobreak
 4600: 		    $displaySub[0].='&nbsp; '.
 4601: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4602: 		}
 4603: 	    }
 4604: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4605: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4606: 				    $$record{"$where.$partid.checkedin"},
 4607: 				    $$record{"$where.$partid.checkedin.slot"}).
 4608: 					'<br />';
 4609: 	    }
 4610: 	    if (exists $$record{"$where.$partid.award"}) {
 4611: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4612: 		    lc($$record{"$where.$partid.award"}).' '.
 4613: 		    $mark{$$record{"$where.$partid.solved"}}.
 4614: 		    '<br />';
 4615: 	    }
 4616: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4617: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4618: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4619: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4620: 		$displaySub[2].=
 4621: 		    $$record{"$version:resource.$partid.regrader"}.
 4622: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4623: 	    }
 4624: 	}
 4625: 	# needed because old essay regrader has not parts info
 4626: 	if (exists $$record{"$version:resource.regrader"}) {
 4627: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4628: 	}
 4629: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4630: 	if ($displaySub[2]) {
 4631: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4632: 	}
 4633: 	$studentTable.='&nbsp;</td>'.
 4634: 	    &Apache::loncommon::end_data_table_row();
 4635:     }
 4636:     $studentTable.=&Apache::loncommon::end_data_table();
 4637:     return $studentTable;
 4638: }
 4639: 
 4640: sub updateGradeByPage {
 4641:     my ($request) = shift;
 4642: 
 4643:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4644:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4645:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4646:     my $pageTitle = $env{'form.page'};
 4647:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4648:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4649:     my $usec=$classlist->{$env{'form.student'}}[5];
 4650:     if (!&canmodify($usec)) {
 4651: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4652: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4653: 	return;
 4654:     }
 4655:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4656:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4657: 	'</h3>'."\n";
 4658: 
 4659:     $request->print($result);
 4660: 
 4661: 
 4662:     my $navmap = Apache::lonnavmaps::navmap->new();
 4663:     unless (ref($navmap)) {
 4664:         $request->print(&navmap_errormsg());
 4665:         return;
 4666:     }
 4667:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4668:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4669:     if (!$map) {
 4670: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4671: 	my ($symb)=&get_symb($request);
 4672: 	$request->print(&show_grading_menu_form($symb));
 4673: 	return; 
 4674:     }
 4675:     my $iterator = $navmap->getIterator($map->map_start(),
 4676: 					$map->map_finish());
 4677: 
 4678:     my $studentTable=
 4679: 	&Apache::loncommon::start_data_table().
 4680: 	&Apache::loncommon::start_data_table_header_row().
 4681: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4682: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4683: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4684: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4685: 	&Apache::loncommon::end_data_table_header_row();
 4686: 
 4687:     $iterator->next(); # skip the first BEGIN_MAP
 4688:     my $curRes = $iterator->next(); # for "current resource"
 4689:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4690:     while ($depth > 0) {
 4691:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4692:         if($curRes == $iterator->END_MAP) { $depth--; }
 4693: 
 4694:         if (ref($curRes) && $curRes->is_problem()) {
 4695: 	    my $parts = $curRes->parts();
 4696:             my $title = $curRes->compTitle();
 4697: 	    my $symbx = $curRes->symb();
 4698: 	    $studentTable.=
 4699: 		&Apache::loncommon::start_data_table_row().
 4700: 		'<td align="center" valign="top" >'.$prob.
 4701: 		(scalar(@{$parts}) == 1 ? '' 
 4702:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4703: 		.')').'</td>';
 4704: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4705: 
 4706: 	    my %newrecord=();
 4707: 	    my @displayPts=();
 4708:             my %aggregate = ();
 4709:             my $aggregateflag = 0;
 4710: 	    foreach my $partid (@{$parts}) {
 4711: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4712: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4713: 
 4714: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4715: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4716: 		my $partial = $newpts/$wgt;
 4717: 		my $score;
 4718: 		if ($partial > 0) {
 4719: 		    $score = 'correct_by_override';
 4720: 		} elsif ($newpts ne '') { #empty is taken as 0
 4721: 		    $score = 'incorrect_by_override';
 4722: 		}
 4723: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4724: 		if ($dropMenu eq 'excused') {
 4725: 		    $partial = '';
 4726: 		    $score = 'excused';
 4727: 		} elsif ($dropMenu eq 'reset status'
 4728: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4729: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4730: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4731: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4732: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4733: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4734: 		    $changeflag++;
 4735: 		    $newpts = '';
 4736:                     
 4737:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4738:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4739:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4740:                     if ($aggtries > 0) {
 4741:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4742:                         $aggregateflag = 1;
 4743:                     }
 4744: 		}
 4745: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4746: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4747: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4748: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4749: 		    '&nbsp;<br />';
 4750: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4751: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4752: 		    '&nbsp;<br />';
 4753: 		$question++;
 4754: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4755: 
 4756: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4757: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4758: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4759: 		    if (scalar(keys(%newrecord)) > 0);
 4760: 
 4761: 		$changeflag++;
 4762: 	    }
 4763: 	    if (scalar(keys(%newrecord)) > 0) {
 4764: 		my %record = 
 4765: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4766: 					     $udom,$uname);
 4767: 
 4768: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4769: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4770: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4771: 		    $newrecord{'resource.CODE'} = '';
 4772: 		}
 4773: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4774: 					$udom,$uname);
 4775: 		%record = &Apache::lonnet::restore($symbx,
 4776: 						   $env{'request.course.id'},
 4777: 						   $udom,$uname);
 4778: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4779: 					     $cdom,$cnum,$udom,$uname);
 4780: 	    }
 4781: 	    
 4782:             if ($aggregateflag) {
 4783:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4784:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4785:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4786:             }
 4787: 
 4788: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4789: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4790: 		&Apache::loncommon::end_data_table_row();
 4791: 
 4792: 	    $prob++;
 4793: 	}
 4794:         $curRes = $iterator->next();
 4795:     }
 4796: 
 4797:     $studentTable.=&Apache::loncommon::end_data_table();
 4798:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4799:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4800: 		  &mt('The scores were changed for [quant,_1,problem].',
 4801: 		  $changeflag));
 4802:     $request->print($grademsg.$studentTable);
 4803: 
 4804:     return '';
 4805: }
 4806: 
 4807: #-------- end of section for handling grading by page/sequence ---------
 4808: #
 4809: #-------------------------------------------------------------------
 4810: 
 4811: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4812: #
 4813: #------ start of section for handling grading by page/sequence ---------
 4814: 
 4815: =pod
 4816: 
 4817: =head1 Bubble sheet grading routines
 4818: 
 4819:   For this documentation:
 4820: 
 4821:    'scanline' refers to the full line of characters
 4822:    from the file that we are parsing that represents one entire sheet
 4823: 
 4824:    'bubble line' refers to the data
 4825:    representing the line of bubbles that are on the physical bubble sheet
 4826: 
 4827: 
 4828: The overall process is that a scanned in bubble sheet data is uploaded
 4829: into a course. When a user wants to grade, they select a
 4830: sequence/folder of resources, a file of bubble sheet info, and pick
 4831: one of the predefined configurations for what each scanline looks
 4832: like.
 4833: 
 4834: Next each scanline is checked for any errors of either 'missing
 4835: bubbles' (it's an error because it may have been mis-scanned
 4836: because too light bubbling), 'double bubble' (each bubble line should
 4837: have no more that one letter picked), invalid or duplicated CODE,
 4838: invalid student/employee ID
 4839: 
 4840: If the CODE option is used that determines the randomization of the
 4841: homework problems, either way the student/employee ID is looked up into a
 4842: username:domain.
 4843: 
 4844: During the validation phase the instructor can choose to skip scanlines. 
 4845: 
 4846: After the validation phase, there are now 3 bubble sheet files
 4847: 
 4848:   scantron_original_filename (unmodified original file)
 4849:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4850:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4851: 
 4852: Also there is a separate hash nohist_scantrondata that contains extra
 4853: correction information that isn't representable in the bubble sheet
 4854: file (see &scantron_getfile() for more information)
 4855: 
 4856: After all scanlines are either valid, marked as valid or skipped, then
 4857: foreach line foreach problem in the picked sequence, an ssi request is
 4858: made that simulates a user submitting their selected letter(s) against
 4859: the homework problem.
 4860: 
 4861: =over 4
 4862: 
 4863: 
 4864: 
 4865: =item defaultFormData
 4866: 
 4867:   Returns html hidden inputs used to hold context/default values.
 4868: 
 4869:  Arguments:
 4870:   $symb - $symb of the current resource 
 4871: 
 4872: =cut
 4873: 
 4874: sub defaultFormData {
 4875:     my ($symb)=@_;
 4876:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4877:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4878:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4879: }
 4880: 
 4881: 
 4882: =pod 
 4883: 
 4884: =item getSequenceDropDown
 4885: 
 4886:    Return html dropdown of possible sequences to grade
 4887:  
 4888:  Arguments:
 4889:    $symb - $symb of the current resource
 4890:    $map_error - ref to scalar which will container error if
 4891:                 $navmap object is unavailable in &getSymbMap().
 4892: 
 4893: =cut
 4894: 
 4895: sub getSequenceDropDown {
 4896:     my ($symb,$map_error)=@_;
 4897:     my $result='<select name="selectpage">'."\n";
 4898:     my ($titles,$symbx) = &getSymbMap($map_error);
 4899:     if (ref($map_error)) {
 4900:         return if ($$map_error);
 4901:     }
 4902:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4903:     my $ctr=0;
 4904:     foreach (@$titles) {
 4905: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4906: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4907: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4908: 	    '>'.$showtitle.'</option>'."\n";
 4909: 	$ctr++;
 4910:     }
 4911:     $result.= '</select>';
 4912:     return $result;
 4913: }
 4914: 
 4915: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4916:                                    # key is zero-based index - 0, 1, 2 ...
 4917: 
 4918: my %first_bubble_line;             # First bubble line no. for each bubble.
 4919: 
 4920: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4921:                                    # matchresponse or rankresponse, where 
 4922:                                    # an individual response can have multiple 
 4923:                                    # lines
 4924: 
 4925: my %responsetype_per_response;     # responsetype for each response
 4926: 
 4927: # Save and restore the bubble lines array to the form env.
 4928: 
 4929: 
 4930: sub save_bubble_lines {
 4931:     foreach my $line (keys(%bubble_lines_per_response)) {
 4932: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4933: 	$env{"form.scantron.first_bubble_line.$line"} =
 4934: 	    $first_bubble_line{$line};
 4935:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4936:             $subdivided_bubble_lines{$line};
 4937:         $env{"form.scantron.responsetype.$line"} =
 4938:             $responsetype_per_response{$line};
 4939:     }
 4940: }
 4941: 
 4942: 
 4943: sub restore_bubble_lines {
 4944:     my $line = 0;
 4945:     %bubble_lines_per_response = ();
 4946:     while ($env{"form.scantron.bubblelines.$line"}) {
 4947: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4948: 	$bubble_lines_per_response{$line} = $value;
 4949: 	$first_bubble_line{$line}  =
 4950: 	    $env{"form.scantron.first_bubble_line.$line"};
 4951:         $subdivided_bubble_lines{$line} =
 4952:             $env{"form.scantron.sub_bubblelines.$line"};
 4953:         $responsetype_per_response{$line} =
 4954:             $env{"form.scantron.responsetype.$line"};
 4955: 	$line++;
 4956:     }
 4957: }
 4958: 
 4959: #  Given the parsed scanline, get the response for 
 4960: #  'answer' number n:
 4961: 
 4962: sub get_response_bubbles {
 4963:     my ($parsed_line, $response)  = @_;
 4964: 
 4965:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4966:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4967:     
 4968:     my $selected = "";
 4969: 
 4970:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4971: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4972: 	$bubble_line++;
 4973:     }
 4974:     return $selected;
 4975: }
 4976: 
 4977: =pod 
 4978: 
 4979: =item scantron_filenames
 4980: 
 4981:    Returns a list of the scantron files in the current course 
 4982: 
 4983: =cut
 4984: 
 4985: sub scantron_filenames {
 4986:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4987:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4988:     my $getpropath = 1;
 4989:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4990:                                        $getpropath);
 4991:     my @possiblenames;
 4992:     foreach my $filename (sort(@files)) {
 4993: 	($filename)=split(/&/,$filename);
 4994: 	if ($filename!~/^scantron_orig_/) { next ; }
 4995: 	$filename=~s/^scantron_orig_//;
 4996: 	push(@possiblenames,$filename);
 4997:     }
 4998:     return @possiblenames;
 4999: }
 5000: 
 5001: =pod 
 5002: 
 5003: =item scantron_uploads
 5004: 
 5005:    Returns  html drop-down list of scantron files in current course.
 5006: 
 5007:  Arguments:
 5008:    $file2grade - filename to set as selected in the dropdown
 5009: 
 5010: =cut
 5011: 
 5012: sub scantron_uploads {
 5013:     my ($file2grade) = @_;
 5014:     my $result=	'<select name="scantron_selectfile">';
 5015:     $result.="<option></option>";
 5016:     foreach my $filename (sort(&scantron_filenames())) {
 5017: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5018:     }
 5019:     $result.="</select>";
 5020:     return $result;
 5021: }
 5022: 
 5023: =pod 
 5024: 
 5025: =item scantron_scantab
 5026: 
 5027:   Returns html drop down of the scantron formats in the scantronformat.tab
 5028:   file.
 5029: 
 5030: =cut
 5031: 
 5032: sub scantron_scantab {
 5033:     my $result='<select name="scantron_format">'."\n";
 5034:     $result.='<option></option>'."\n";
 5035:     my @lines = &get_scantronformat_file();
 5036:     if (@lines > 0) {
 5037:         foreach my $line (@lines) {
 5038:             next if (($line =~ /^\#/) || ($line eq ''));
 5039: 	    my ($name,$descrip)=split(/:/,$line);
 5040: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5041:         }
 5042:     }
 5043:     $result.='</select>'."\n";
 5044:     return $result;
 5045: }
 5046: 
 5047: =pod
 5048: 
 5049: =item get_scantronformat_file
 5050: 
 5051:   Returns an array containing lines from the scantron format file for
 5052:   the domain of the course.
 5053: 
 5054:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5055:   lines are from this file.
 5056: 
 5057:   Otherwise, if a default.tab has been published in RES space by the 
 5058:   domainconfig user, lines are from this file.
 5059: 
 5060:   Otherwise, fall back to getting lines from the legacy file on the
 5061:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5062: 
 5063: =cut
 5064: 
 5065: sub get_scantronformat_file {
 5066:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5067:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5068:     my $gottab = 0;
 5069:     my @lines;
 5070:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5071:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5072:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5073:             if ($formatfile ne '-1') {
 5074:                 @lines = split("\n",$formatfile,-1);
 5075:                 $gottab = 1;
 5076:             }
 5077:         }
 5078:     }
 5079:     if (!$gottab) {
 5080:         my $confname = $cdom.'-domainconfig';
 5081:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5082:         my $formatfile =  &Apache::lonnet::getfile($default);
 5083:         if ($formatfile ne '-1') {
 5084:             @lines = split("\n",$formatfile,-1);
 5085:             $gottab = 1;
 5086:         }
 5087:     }
 5088:     if (!$gottab) {
 5089:         my @domains = &Apache::lonnet::current_machine_domains();
 5090:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5091:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5092:             @lines = <$fh>;
 5093:             close($fh);
 5094:         } else {
 5095:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5096:             @lines = <$fh>;
 5097:             close($fh);
 5098:         }
 5099:     }
 5100:     return @lines;
 5101: }
 5102: 
 5103: =pod 
 5104: 
 5105: =item scantron_CODElist
 5106: 
 5107:   Returns html drop down of the saved CODE lists from current course,
 5108:   generated from earlier printings.
 5109: 
 5110: =cut
 5111: 
 5112: sub scantron_CODElist {
 5113:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5114:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5115:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5116:     my $namechoice='<option></option>';
 5117:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5118: 	if ($name =~ /^error: 2 /) { next; }
 5119: 	if ($name =~ /^type\0/) { next; }
 5120: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5121:     }
 5122:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5123:     return $namechoice;
 5124: }
 5125: 
 5126: =pod 
 5127: 
 5128: =item scantron_CODEunique
 5129: 
 5130:   Returns the html for "Each CODE to be used once" radio.
 5131: 
 5132: =cut
 5133: 
 5134: sub scantron_CODEunique {
 5135:     my $result='<span class="LC_nobreak">
 5136:                  <label><input type="radio" name="scantron_CODEunique"
 5137:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5138:                 </span>
 5139:                 <span class="LC_nobreak">
 5140:                  <label><input type="radio" name="scantron_CODEunique"
 5141:                         value="no" />'.&mt('No').' </label>
 5142:                 </span>';
 5143:     return $result;
 5144: }
 5145: 
 5146: =pod 
 5147: 
 5148: =item scantron_selectphase
 5149: 
 5150:   Generates the initial screen to start the bubble sheet process.
 5151:   Allows for - starting a grading run.
 5152:              - downloading existing scan data (original, corrected
 5153:                                                 or skipped info)
 5154: 
 5155:              - uploading new scan data
 5156: 
 5157:  Arguments:
 5158:   $r          - The Apache request object
 5159:   $file2grade - name of the file that contain the scanned data to score
 5160: 
 5161: =cut
 5162: 
 5163: sub scantron_selectphase {
 5164:     my ($r,$file2grade) = @_;
 5165:     my ($symb)=&get_symb($r);
 5166:     if (!$symb) {return '';}
 5167:     my $map_error;
 5168:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5169:     if ($map_error) {
 5170:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5171:         return;
 5172:     }
 5173:     my $default_form_data=&defaultFormData($symb);
 5174:     my $grading_menu_button=&show_grading_menu_form($symb);
 5175:     my $file_selector=&scantron_uploads($file2grade);
 5176:     my $format_selector=&scantron_scantab();
 5177:     my $CODE_selector=&scantron_CODElist();
 5178:     my $CODE_unique=&scantron_CODEunique();
 5179:     my $result;
 5180: 
 5181:     $ssi_error = 0;
 5182: 
 5183:     # Chunk of form to prompt for a file to grade and how:
 5184: 
 5185:     $result.= '
 5186:     <br />
 5187:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5188:     <input type="hidden" name="command" value="scantron_warning" />
 5189:     '.$default_form_data.'
 5190:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5191:        '.&Apache::loncommon::start_data_table_header_row().'
 5192:             <th colspan="2">
 5193:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5194:             </th>
 5195:        '.&Apache::loncommon::end_data_table_header_row().'
 5196:        '.&Apache::loncommon::start_data_table_row().'
 5197:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5198:        '.&Apache::loncommon::end_data_table_row().'
 5199:        '.&Apache::loncommon::start_data_table_row().'
 5200:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5201:        '.&Apache::loncommon::end_data_table_row().'
 5202:        '.&Apache::loncommon::start_data_table_row().'
 5203:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5204:        '.&Apache::loncommon::end_data_table_row().'
 5205:        '.&Apache::loncommon::start_data_table_row().'
 5206:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5207:        '.&Apache::loncommon::end_data_table_row().'
 5208:        '.&Apache::loncommon::start_data_table_row().'
 5209:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5210:        '.&Apache::loncommon::end_data_table_row().'
 5211:        '.&Apache::loncommon::start_data_table_row().'
 5212: 	    <td> '.&mt('Options:').' </td>
 5213:             <td>
 5214: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5215:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5216:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5217: 	    </td>
 5218:        '.&Apache::loncommon::end_data_table_row().'
 5219:        '.&Apache::loncommon::start_data_table_row().'
 5220:             <td colspan="2">
 5221:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5222:             </td>
 5223:        '.&Apache::loncommon::end_data_table_row().'
 5224:     '.&Apache::loncommon::end_data_table().'
 5225:     </form>
 5226: ';
 5227:    
 5228:     $r->print($result);
 5229: 
 5230:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5231:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5232: 
 5233: 	# Chunk of form to prompt for a scantron file upload.
 5234: 
 5235:         $r->print('
 5236:     <br />
 5237:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5238:        '.&Apache::loncommon::start_data_table_header_row().'
 5239:             <th>
 5240:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5241:             </th>
 5242:        '.&Apache::loncommon::end_data_table_header_row().'
 5243:        '.&Apache::loncommon::start_data_table_row().'
 5244:             <td>
 5245: ');
 5246:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5247:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5248:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5249:     $r->print('
 5250:               <script type="text/javascript" language="javascript">
 5251:     function checkUpload(formname) {
 5252: 	if (formname.upfile.value == "") {
 5253: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5254: 	    return false;
 5255: 	}
 5256: 	formname.submit();
 5257:     }
 5258:               </script>
 5259: 
 5260:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5261:                 '.$default_form_data.'
 5262:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5263:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5264:                 <input name="command" value="scantronupload_save" type="hidden" />
 5265:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5266:                 <br />
 5267:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5268:               </form>
 5269: ');
 5270: 
 5271:         $r->print('
 5272:             </td>
 5273:        '.&Apache::loncommon::end_data_table_row().'
 5274:        '.&Apache::loncommon::end_data_table().'
 5275: ');
 5276:     }
 5277: 
 5278:     # Chunk of the form that prompts to view a scoring office file,
 5279:     # corrected file, skipped records in a file.
 5280: 
 5281:     $r->print('
 5282:    <br />
 5283:    <form action="/adm/grades" name="scantron_download">
 5284:      '.$default_form_data.'
 5285:      <input type="hidden" name="command" value="scantron_download" />
 5286:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5287:        '.&Apache::loncommon::start_data_table_header_row().'
 5288:               <th>
 5289:                 &nbsp;'.&mt('Download a scoring office file').'
 5290:               </th>
 5291:        '.&Apache::loncommon::end_data_table_header_row().'
 5292:        '.&Apache::loncommon::start_data_table_row().'
 5293:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5294:                 <br />
 5295:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5296:        '.&Apache::loncommon::end_data_table_row().'
 5297:      '.&Apache::loncommon::end_data_table().'
 5298:    </form>
 5299:    <br />
 5300: ');
 5301: 
 5302:     &Apache::lonpickcode::code_list($r,2);
 5303: 
 5304:     $r->print('<br /><form method="post" name="checkscantron">'.
 5305:              $default_form_data."\n".
 5306:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5307:              &Apache::loncommon::start_data_table_header_row()."\n".
 5308:              '<th colspan="2">
 5309:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5310:              '</th>'."\n".
 5311:               &Apache::loncommon::end_data_table_header_row()."\n".
 5312:               &Apache::loncommon::start_data_table_row()."\n".
 5313:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5314:               '<td> '.$sequence_selector.' </td>'.
 5315:               &Apache::loncommon::end_data_table_row()."\n".
 5316:               &Apache::loncommon::start_data_table_row()."\n".
 5317:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5318:               '<td> '.$file_selector.' </td>'."\n".
 5319:               &Apache::loncommon::end_data_table_row()."\n".
 5320:               &Apache::loncommon::start_data_table_row()."\n".
 5321:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5322:               '<td> '.$format_selector.' </td>'."\n".
 5323:               &Apache::loncommon::end_data_table_row()."\n".
 5324:               &Apache::loncommon::start_data_table_row()."\n".
 5325:               '<td> '.&mt('Options').' </td>'."\n".
 5326:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5327:               &Apache::loncommon::end_data_table_row()."\n".
 5328:               &Apache::loncommon::start_data_table_row()."\n".
 5329:               '<td colspan="2">'."\n".
 5330:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5331:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5332:               '</td>'."\n".
 5333:               &Apache::loncommon::end_data_table_row()."\n".
 5334:               &Apache::loncommon::end_data_table()."\n".
 5335:               '</form><br />');
 5336:     $r->print($grading_menu_button);
 5337:     return;
 5338: }
 5339: 
 5340: =pod
 5341: 
 5342: =item get_scantron_config
 5343: 
 5344:    Parse and return the scantron configuration line selected as a
 5345:    hash of configuration file fields.
 5346: 
 5347:  Arguments:
 5348:     which - the name of the configuration to parse from the file.
 5349: 
 5350: 
 5351:  Returns:
 5352:             If the named configuration is not in the file, an empty
 5353:             hash is returned.
 5354:     a hash with the fields
 5355:       name         - internal name for the this configuration setup
 5356:       description  - text to display to operator that describes this config
 5357:       CODElocation - if 0 or the string 'none'
 5358:                           - no CODE exists for this config
 5359:                      if -1 || the string 'letter'
 5360:                           - a CODE exists for this config and is
 5361:                             a string of letters
 5362:                      Unsupported value (but planned for future support)
 5363:                           if a positive integer
 5364:                                - The CODE exists as the first n items from
 5365:                                  the question section of the form
 5366:                           if the string 'number'
 5367:                                - The CODE exists for this config and is
 5368:                                  a string of numbers
 5369:       CODEstart   - (only matter if a CODE exists) column in the line where
 5370:                      the CODE starts
 5371:       CODElength  - length of the CODE
 5372:       IDstart     - column where the student/employee ID starts
 5373:       IDlength    - length of the student/employee ID info
 5374:       Qstart      - column where the information from the bubbled
 5375:                     'questions' start
 5376:       Qlength     - number of columns comprising a single bubble line from
 5377:                     the sheet. (usually either 1 or 10)
 5378:       Qon         - either a single character representing the character used
 5379:                     to signal a bubble was chosen in the positional setup, or
 5380:                     the string 'letter' if the letter of the chosen bubble is
 5381:                     in the final, or 'number' if a number representing the
 5382:                     chosen bubble is in the file (1->A 0->J)
 5383:       Qoff        - the character used to represent that a bubble was
 5384:                     left blank
 5385:       PaperID     - if the scanning process generates a unique number for each
 5386:                     sheet scanned the column that this ID number starts in
 5387:       PaperIDlength - number of columns that comprise the unique ID number
 5388:                       for the sheet of paper
 5389:       FirstName   - column that the first name starts in
 5390:       FirstNameLength - number of columns that the first name spans
 5391:  
 5392:       LastName    - column that the last name starts in
 5393:       LastNameLength - number of columns that the last name spans
 5394: 
 5395: =cut
 5396: 
 5397: sub get_scantron_config {
 5398:     my ($which) = @_;
 5399:     my @lines = &get_scantronformat_file();
 5400:     my %config;
 5401:     #FIXME probably should move to XML it has already gotten a bit much now
 5402:     foreach my $line (@lines) {
 5403: 	my ($name,$descrip)=split(/:/,$line);
 5404: 	if ($name ne $which ) { next; }
 5405: 	chomp($line);
 5406: 	my @config=split(/:/,$line);
 5407: 	$config{'name'}=$config[0];
 5408: 	$config{'description'}=$config[1];
 5409: 	$config{'CODElocation'}=$config[2];
 5410: 	$config{'CODEstart'}=$config[3];
 5411: 	$config{'CODElength'}=$config[4];
 5412: 	$config{'IDstart'}=$config[5];
 5413: 	$config{'IDlength'}=$config[6];
 5414: 	$config{'Qstart'}=$config[7];
 5415:  	$config{'Qlength'}=$config[8];
 5416: 	$config{'Qoff'}=$config[9];
 5417: 	$config{'Qon'}=$config[10];
 5418: 	$config{'PaperID'}=$config[11];
 5419: 	$config{'PaperIDlength'}=$config[12];
 5420: 	$config{'FirstName'}=$config[13];
 5421: 	$config{'FirstNamelength'}=$config[14];
 5422: 	$config{'LastName'}=$config[15];
 5423: 	$config{'LastNamelength'}=$config[16];
 5424: 	last;
 5425:     }
 5426:     return %config;
 5427: }
 5428: 
 5429: =pod 
 5430: 
 5431: =item username_to_idmap
 5432: 
 5433:     creates a hash keyed by student/employee ID with values of the corresponding
 5434:     student username:domain.
 5435: 
 5436:   Arguments:
 5437: 
 5438:     $classlist - reference to the class list hash. This is a hash
 5439:                  keyed by student name:domain  whose elements are references
 5440:                  to arrays containing various chunks of information
 5441:                  about the student. (See loncoursedata for more info).
 5442: 
 5443:   Returns
 5444:     %idmap - the constructed hash
 5445: 
 5446: =cut
 5447: 
 5448: sub username_to_idmap {
 5449:     my ($classlist)= @_;
 5450:     my %idmap;
 5451:     foreach my $student (keys(%$classlist)) {
 5452: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5453: 	    $student;
 5454:     }
 5455:     return %idmap;
 5456: }
 5457: 
 5458: =pod
 5459: 
 5460: =item scantron_fixup_scanline
 5461: 
 5462:    Process a requested correction to a scanline.
 5463: 
 5464:   Arguments:
 5465:     $scantron_config   - hash from &get_scantron_config()
 5466:     $scan_data         - hash of correction information 
 5467:                           (see &scantron_getfile())
 5468:     $line              - existing scanline
 5469:     $whichline         - line number of the passed in scanline
 5470:     $field             - type of change to process 
 5471:                          (either 
 5472:                           'ID'     -> correct the student/employee ID
 5473:                           'CODE'   -> correct the CODE
 5474:                           'answer' -> fixup the submitted answers)
 5475:     
 5476:    $args               - hash of additional info,
 5477:                           - 'ID' 
 5478:                                'newid' -> studentID to use in replacement
 5479:                                           of existing one
 5480:                           - 'CODE' 
 5481:                                'CODE_ignore_dup' - set to true if duplicates
 5482:                                                    should be ignored.
 5483: 	                       'CODE' - is new code or 'use_unfound'
 5484:                                         if the existing unfound code should
 5485:                                         be used as is
 5486:                           - 'answer'
 5487:                                'response' - new answer or 'none' if blank
 5488:                                'question' - the bubble line to change
 5489:                                'questionnum' - the question identifier,
 5490:                                                may include subquestion. 
 5491: 
 5492:   Returns:
 5493:     $line - the modified scanline
 5494: 
 5495:   Side effects: 
 5496:     $scan_data - may be updated
 5497: 
 5498: =cut
 5499: 
 5500: 
 5501: sub scantron_fixup_scanline {
 5502:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5503:     if ($field eq 'ID') {
 5504: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5505: 	    return ($line,1,'New value too large');
 5506: 	}
 5507: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5508: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5509: 				     $args->{'newid'});
 5510: 	}
 5511: 	substr($line,$$scantron_config{'IDstart'}-1,
 5512: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5513: 	if ($args->{'newid'}=~/^\s*$/) {
 5514: 	    &scan_data($scan_data,"$whichline.user",
 5515: 		       $args->{'username'}.':'.$args->{'domain'});
 5516: 	}
 5517:     } elsif ($field eq 'CODE') {
 5518: 	if ($args->{'CODE_ignore_dup'}) {
 5519: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5520: 	}
 5521: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5522: 	if ($args->{'CODE'} ne 'use_unfound') {
 5523: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5524: 		return ($line,1,'New CODE value too large');
 5525: 	    }
 5526: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5527: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5528: 	    }
 5529: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5530: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5531: 	}
 5532:     } elsif ($field eq 'answer') {
 5533: 	my $length=$scantron_config->{'Qlength'};
 5534: 	my $off=$scantron_config->{'Qoff'};
 5535: 	my $on=$scantron_config->{'Qon'};
 5536: 	my $answer=${off}x$length;
 5537: 	if ($args->{'response'} eq 'none') {
 5538: 	    &scan_data($scan_data,
 5539: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5540: 	} else {
 5541: 	    if ($on eq 'letter') {
 5542: 		my @alphabet=('A'..'Z');
 5543: 		$answer=$alphabet[$args->{'response'}];
 5544: 	    } elsif ($on eq 'number') {
 5545: 		$answer=$args->{'response'}+1;
 5546: 		if ($answer == 10) { $answer = '0'; }
 5547: 	    } else {
 5548: 		substr($answer,$args->{'response'},1)=$on;
 5549: 	    }
 5550: 	    &scan_data($scan_data,
 5551: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5552: 	}
 5553: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5554: 	substr($line,$where-1,$length)=$answer;
 5555:     }
 5556:     return $line;
 5557: }
 5558: 
 5559: =pod
 5560: 
 5561: =item scan_data
 5562: 
 5563:     Edit or look up  an item in the scan_data hash.
 5564: 
 5565:   Arguments:
 5566:     $scan_data  - The hash (see scantron_getfile)
 5567:     $key        - shorthand of the key to edit (actual key is
 5568:                   scantronfilename_key).
 5569:     $data        - New value of the hash entry.
 5570:     $delete      - If true, the entry is removed from the hash.
 5571: 
 5572:   Returns:
 5573:     The new value of the hash table field (undefined if deleted).
 5574: 
 5575: =cut
 5576: 
 5577: 
 5578: sub scan_data {
 5579:     my ($scan_data,$key,$value,$delete)=@_;
 5580:     my $filename=$env{'form.scantron_selectfile'};
 5581:     if (defined($value)) {
 5582: 	$scan_data->{$filename.'_'.$key} = $value;
 5583:     }
 5584:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5585:     return $scan_data->{$filename.'_'.$key};
 5586: }
 5587: 
 5588: # ----- These first few routines are general use routines.----
 5589: 
 5590: # Return the number of occurences of a pattern in a string.
 5591: 
 5592: sub occurence_count {
 5593:     my ($string, $pattern) = @_;
 5594: 
 5595:     my @matches = ($string =~ /$pattern/g);
 5596: 
 5597:     return scalar(@matches);
 5598: }
 5599: 
 5600: 
 5601: # Take a string known to have digits and convert all the
 5602: # digits into letters in the range J,A..I.
 5603: 
 5604: sub digits_to_letters {
 5605:     my ($input) = @_;
 5606: 
 5607:     my @alphabet = ('J', 'A'..'I');
 5608: 
 5609:     my @input    = split(//, $input);
 5610:     my $output ='';
 5611:     for (my $i = 0; $i < scalar(@input); $i++) {
 5612: 	if ($input[$i] =~ /\d/) {
 5613: 	    $output .= $alphabet[$input[$i]];
 5614: 	} else {
 5615: 	    $output .= $input[$i];
 5616: 	}
 5617:     }
 5618:     return $output;
 5619: }
 5620: 
 5621: =pod 
 5622: 
 5623: =item scantron_parse_scanline
 5624: 
 5625:   Decodes a scanline from the selected scantron file
 5626: 
 5627:  Arguments:
 5628:     line             - The text of the scantron file line to process
 5629:     whichline        - Line number
 5630:     scantron_config  - Hash describing the format of the scantron lines.
 5631:     scan_data        - Hash of extra information about the scanline
 5632:                        (see scantron_getfile for more information)
 5633:     just_header      - True if should not process question answers but only
 5634:                        the stuff to the left of the answers.
 5635:  Returns:
 5636:    Hash containing the result of parsing the scanline
 5637: 
 5638:    Keys are all proceeded by the string 'scantron.'
 5639: 
 5640:        CODE    - the CODE in use for this scanline
 5641:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5642:                  by the operator
 5643:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5644:                             CODEs were selected, but the usage has been
 5645:                             forced by the operator
 5646:        ID  - student/employee ID
 5647:        PaperID - if used, the ID number printed on the sheet when the 
 5648:                  paper was scanned
 5649:        FirstName - first name from the sheet
 5650:        LastName  - last name from the sheet
 5651: 
 5652:      if just_header was not true these key may also exist
 5653: 
 5654:        missingerror - a list of bubble ranges that are considered to be answers
 5655:                       to a single question that don't have any bubbles filled in.
 5656:                       Of the form questionnumber:firstbubblenumber:count.
 5657:        doubleerror  - a list of bubble ranges that are considered to be answers
 5658:                       to a single question that have more than one bubble filled in.
 5659:                       Of the form questionnumber::firstbubblenumber:count
 5660:    
 5661:                 In the above, count is the number of bubble responses in the
 5662:                 input line needed to represent the possible answers to the question.
 5663:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5664:                 per line would have count = 2.
 5665: 
 5666:        maxquest     - the number of the last bubble line that was parsed
 5667: 
 5668:        (<number> starts at 1)
 5669:        <number>.answer - zero or more letters representing the selected
 5670:                          letters from the scanline for the bubble line 
 5671:                          <number>.
 5672:                          if blank there was either no bubble or there where
 5673:                          multiple bubbles, (consult the keys missingerror and
 5674:                          doubleerror if this is an error condition)
 5675: 
 5676: =cut
 5677: 
 5678: sub scantron_parse_scanline {
 5679:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5680: 
 5681:     my %record;
 5682:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5683:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5684:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5685:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5686: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5687: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5688: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5689: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5690: 	    $record{'scantron.CODE'}=substr($data,
 5691: 					    $$scantron_config{'CODEstart'}-1,
 5692: 					    $$scantron_config{'CODElength'});
 5693: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5694: 		$record{'scantron.useCODE'}=1;
 5695: 	    }
 5696: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5697: 		$record{'scantron.CODE_ignore_dup'}=1;
 5698: 	    }
 5699: 	} else {
 5700: 	    #FIXME interpret first N questions
 5701: 	}
 5702:     }
 5703:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5704: 				  $$scantron_config{'IDlength'});
 5705:     $record{'scantron.PaperID'}=
 5706: 	substr($data,$$scantron_config{'PaperID'}-1,
 5707: 	       $$scantron_config{'PaperIDlength'});
 5708:     $record{'scantron.FirstName'}=
 5709: 	substr($data,$$scantron_config{'FirstName'}-1,
 5710: 	       $$scantron_config{'FirstNamelength'});
 5711:     $record{'scantron.LastName'}=
 5712: 	substr($data,$$scantron_config{'LastName'}-1,
 5713: 	       $$scantron_config{'LastNamelength'});
 5714:     if ($just_header) { return \%record; }
 5715: 
 5716:     my @alphabet=('A'..'Z');
 5717:     my $questnum=0;
 5718:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5719: 
 5720:     chomp($questions);		# Get rid of any trailing \n.
 5721:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5722:     while (length($questions)) {
 5723: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5724:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5725:                              || 1;
 5726:         $questnum++;
 5727:         my $quest_id = $questnum;
 5728:         my $currentquest = substr($questions,0,$answer_length);
 5729:         $questions       = substr($questions,$answer_length);
 5730:         if (length($currentquest) < $answer_length) { next; }
 5731: 
 5732:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5733:             my $subquestnum = 1;
 5734:             my $subquestions = $currentquest;
 5735:             my @subanswers_needed = 
 5736:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5737:             foreach my $subans (@subanswers_needed) {
 5738:                 my $subans_length =
 5739:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5740:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5741:                 $subquestions   = substr($subquestions,$subans_length);
 5742:                 $quest_id = "$questnum.$subquestnum";
 5743:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5744:                     ($$scantron_config{'Qon'} eq 'number')) {
 5745:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5746:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5747:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5748:                 } else {
 5749:                     $ansnum = &scantron_validator_positional($ansnum,
 5750:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5751:                 }
 5752:                 $subquestnum ++;
 5753:             }
 5754:         } else {
 5755:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5756:                 ($$scantron_config{'Qon'} eq 'number')) {
 5757:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5758:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5759:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5760:             } else {
 5761:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5762:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5763:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5764:             }
 5765:         }
 5766:     }
 5767:     $record{'scantron.maxquest'}=$questnum;
 5768:     return \%record;
 5769: }
 5770: 
 5771: sub scantron_validator_lettnum {
 5772:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5773:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5774: 
 5775:     # Qon 'letter' implies for each slot in currquest we have:
 5776:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5777:     #    about anything else (esp. a value of Qoff) for missing
 5778:     #    bubbles.
 5779:     #
 5780:     # Qon 'number' implies each slot gives a digit that indexes the
 5781:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5782:     #    and * or ? for double bubbles on a single line.
 5783:     #
 5784: 
 5785:     my $matchon;
 5786:     if ($$scantron_config{'Qon'} eq 'letter') {
 5787:         $matchon = '[A-Z]';
 5788:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5789:         $matchon = '\d';
 5790:     }
 5791:     my $occurrences = 0;
 5792:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5793:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5794:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5795:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5796:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5797:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5798:         my @singlelines = split('',$currquest);
 5799:         foreach my $entry (@singlelines) {
 5800:             $occurrences = &occurence_count($entry,$matchon);
 5801:             if ($occurrences > 1) {
 5802:                 last;
 5803:             }
 5804:         } 
 5805:     } else {
 5806:         $occurrences = &occurence_count($currquest,$matchon); 
 5807:     }
 5808:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5809:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5810:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5811:             my $bubble = substr($currquest,$ans,1);
 5812:             if ($bubble =~ /$matchon/ ) {
 5813:                 if ($$scantron_config{'Qon'} eq 'number') {
 5814:                     if ($bubble == 0) {
 5815:                         $bubble = 10; 
 5816:                     }
 5817:                     $record->{"scantron.$ansnum.answer"} = 
 5818:                         $alphabet->[$bubble-1];
 5819:                 } else {
 5820:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5821:                 }
 5822:             } else {
 5823:                 $record->{"scantron.$ansnum.answer"}='';
 5824:             }
 5825:             $ansnum++;
 5826:         }
 5827:     } elsif (!defined($currquest)
 5828:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5829:             || (&occurence_count($currquest,$matchon) == 0)) {
 5830:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5831:             $record->{"scantron.$ansnum.answer"}='';
 5832:             $ansnum++;
 5833:         }
 5834:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5835:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5836:         }
 5837:     } else {
 5838:         if ($$scantron_config{'Qon'} eq 'number') {
 5839:             $currquest = &digits_to_letters($currquest);            
 5840:         }
 5841:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5842:             my $bubble = substr($currquest,$ans,1);
 5843:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5844:             $ansnum++;
 5845:         }
 5846:     }
 5847:     return $ansnum;
 5848: }
 5849: 
 5850: sub scantron_validator_positional {
 5851:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5852:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5853: 
 5854:     # Otherwise there's a positional notation;
 5855:     # each bubble line requires Qlength items, and there are filled in
 5856:     # bubbles for each case where there 'Qon' characters.
 5857:     #
 5858: 
 5859:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5860: 
 5861:     # If the split only gives us one element.. the full length of the
 5862:     # answer string, no bubbles are filled in:
 5863: 
 5864:     if ($answers_needed eq '') {
 5865:         return;
 5866:     }
 5867: 
 5868:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5869:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5870:             $record->{"scantron.$ansnum.answer"}='';
 5871:             $ansnum++;
 5872:         }
 5873:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5874:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5875:         }
 5876:     } elsif (scalar(@array) == 2) {
 5877:         my $location = length($array[0]);
 5878:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5879:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5880:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5881:             if ($ans eq $line_num) {
 5882:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5883:             } else {
 5884:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5885:             }
 5886:             $ansnum++;
 5887:          }
 5888:     } else {
 5889:         #  If there's more than one instance of a bubble character
 5890:         #  That's a double bubble; with positional notation we can
 5891:         #  record all the bubbles filled in as well as the
 5892:         #  fact this response consists of multiple bubbles.
 5893:         #
 5894:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5895:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5896:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5897:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5898:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5899:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5900:             my $doubleerror = 0;
 5901:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5902:                    (!$doubleerror)) {
 5903:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5904:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5905:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5906:                if (length(@currarray) > 2) {
 5907:                    $doubleerror = 1;
 5908:                } 
 5909:             }
 5910:             if ($doubleerror) {
 5911:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5912:             }
 5913:         } else {
 5914:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5915:         }
 5916:         my $item = $ansnum;
 5917:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5918:             $record->{"scantron.$item.answer"} = '';
 5919:             $item ++;
 5920:         }
 5921: 
 5922:         my @ans=@array;
 5923:         my $i=0;
 5924:         my $increment = 0;
 5925:         while ($#ans) {
 5926:             $i+=length($ans[0]) + $increment;
 5927:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5928:             my $bubble = $i%$$scantron_config{'Qlength'};
 5929:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5930:             shift(@ans);
 5931:             $increment = 1;
 5932:         }
 5933:         $ansnum += $answers_needed;
 5934:     }
 5935:     return $ansnum;
 5936: }
 5937: 
 5938: =pod
 5939: 
 5940: =item scantron_add_delay
 5941: 
 5942:    Adds an error message that occurred during the grading phase to a
 5943:    queue of messages to be shown after grading pass is complete
 5944: 
 5945:  Arguments:
 5946:    $delayqueue  - arrary ref of hash ref of error messages
 5947:    $scanline    - the scanline that caused the error
 5948:    $errormesage - the error message
 5949:    $errorcode   - a numeric code for the error
 5950: 
 5951:  Side Effects:
 5952:    updates the $delayqueue to have a new hash ref of the error
 5953: 
 5954: =cut
 5955: 
 5956: sub scantron_add_delay {
 5957:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5958:     push(@$delayqueue,
 5959: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5960: 	  'ecode' => $errorcode }
 5961: 	 );
 5962: }
 5963: 
 5964: =pod
 5965: 
 5966: =item scantron_find_student
 5967: 
 5968:    Finds the username for the current scanline
 5969: 
 5970:   Arguments:
 5971:    $scantron_record - hash result from scantron_parse_scanline
 5972:    $scan_data       - hash of correction information 
 5973:                       (see &scantron_getfile() form more information)
 5974:    $idmap           - hash from &username_to_idmap()
 5975:    $line            - number of current scanline
 5976:  
 5977:   Returns:
 5978:    Either 'username:domain' or undef if unknown
 5979: 
 5980: =cut
 5981: 
 5982: sub scantron_find_student {
 5983:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5984:     my $scanID=$$scantron_record{'scantron.ID'};
 5985:     if ($scanID =~ /^\s*$/) {
 5986:  	return &scan_data($scan_data,"$line.user");
 5987:     }
 5988:     foreach my $id (keys(%$idmap)) {
 5989:  	if (lc($id) eq lc($scanID)) {
 5990:  	    return $$idmap{$id};
 5991:  	}
 5992:     }
 5993:     return undef;
 5994: }
 5995: 
 5996: =pod
 5997: 
 5998: =item scantron_filter
 5999: 
 6000:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6001:    hidden resources was selected
 6002: 
 6003: =cut
 6004: 
 6005: sub scantron_filter {
 6006:     my ($curres)=@_;
 6007: 
 6008:     if (ref($curres) && $curres->is_problem()) {
 6009: 	# if the user has asked to not have either hidden
 6010: 	# or 'randomout' controlled resources to be graded
 6011: 	# don't include them
 6012: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6013: 	    && $curres->randomout) {
 6014: 	    return 0;
 6015: 	}
 6016: 	return 1;
 6017:     }
 6018:     return 0;
 6019: }
 6020: 
 6021: =pod
 6022: 
 6023: =item scantron_process_corrections
 6024: 
 6025:    Gets correction information out of submitted form data and corrects
 6026:    the scanline
 6027: 
 6028: =cut
 6029: 
 6030: sub scantron_process_corrections {
 6031:     my ($r) = @_;
 6032:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6033:     my ($scanlines,$scan_data)=&scantron_getfile();
 6034:     my $classlist=&Apache::loncoursedata::get_classlist();
 6035:     my $which=$env{'form.scantron_line'};
 6036:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6037:     my ($skip,$err,$errmsg);
 6038:     if ($env{'form.scantron_skip_record'}) {
 6039: 	$skip=1;
 6040:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6041: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6042: 	    $env{'form.scantron_domain'};
 6043: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6044: 	($line,$err,$errmsg)=
 6045: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6046: 				     'ID',{'newid'=>$newid,
 6047: 				    'username'=>$env{'form.scantron_username'},
 6048: 				    'domain'=>$env{'form.scantron_domain'}});
 6049:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6050: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6051: 	my $newCODE;
 6052: 	my %args;
 6053: 	if      ($resolution eq 'use_unfound') {
 6054: 	    $newCODE='use_unfound';
 6055: 	} elsif ($resolution eq 'use_found') {
 6056: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6057: 	} elsif ($resolution eq 'use_typed') {
 6058: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6059: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6060: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6061: 	}
 6062: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6063: 	    $args{'CODE_ignore_dup'}=1;
 6064: 	}
 6065: 	$args{'CODE'}=$newCODE;
 6066: 	($line,$err,$errmsg)=
 6067: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6068: 				     'CODE',\%args);
 6069:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6070: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6071: 	    ($line,$err,$errmsg)=
 6072: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6073: 					 $which,'answer',
 6074: 					 { 'question'=>$question,
 6075: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6076:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6077: 	    if ($err) { last; }
 6078: 	}
 6079:     }
 6080:     if ($err) {
 6081: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6082:     } else {
 6083: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6084: 	&scantron_putfile($scanlines,$scan_data);
 6085:     }
 6086: }
 6087: 
 6088: =pod
 6089: 
 6090: =item reset_skipping_status
 6091: 
 6092:    Forgets the current set of remember skipped scanlines (and thus
 6093:    reverts back to considering all lines in the
 6094:    scantron_skipped_<filename> file)
 6095: 
 6096: =cut
 6097: 
 6098: sub reset_skipping_status {
 6099:     my ($scanlines,$scan_data)=&scantron_getfile();
 6100:     &scan_data($scan_data,'remember_skipping',undef,1);
 6101:     &scantron_putfile(undef,$scan_data);
 6102: }
 6103: 
 6104: =pod
 6105: 
 6106: =item start_skipping
 6107: 
 6108:    Marks a scanline to be skipped. 
 6109: 
 6110: =cut
 6111: 
 6112: sub start_skipping {
 6113:     my ($scan_data,$i)=@_;
 6114:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6115:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6116: 	$remembered{$i}=2;
 6117:     } else {
 6118: 	$remembered{$i}=1;
 6119:     }
 6120:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6121: }
 6122: 
 6123: =pod
 6124: 
 6125: =item should_be_skipped
 6126: 
 6127:    Checks whether a scanline should be skipped.
 6128: 
 6129: =cut
 6130: 
 6131: sub should_be_skipped {
 6132:     my ($scanlines,$scan_data,$i)=@_;
 6133:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6134: 	# not redoing old skips
 6135: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6136: 	return 0;
 6137:     }
 6138:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6139: 
 6140:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6141: 	return 0;
 6142:     }
 6143:     return 1;
 6144: }
 6145: 
 6146: =pod
 6147: 
 6148: =item remember_current_skipped
 6149: 
 6150:    Discovers what scanlines are in the scantron_skipped_<filename>
 6151:    file and remembers them into scan_data for later use.
 6152: 
 6153: =cut
 6154: 
 6155: sub remember_current_skipped {
 6156:     my ($scanlines,$scan_data)=&scantron_getfile();
 6157:     my %to_remember;
 6158:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6159: 	if ($scanlines->{'skipped'}[$i]) {
 6160: 	    $to_remember{$i}=1;
 6161: 	}
 6162:     }
 6163: 
 6164:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6165:     &scantron_putfile(undef,$scan_data);
 6166: }
 6167: 
 6168: =pod
 6169: 
 6170: =item check_for_error
 6171: 
 6172:     Checks if there was an error when attempting to remove a specific
 6173:     scantron_.. bubble sheet data file. Prints out an error if
 6174:     something went wrong.
 6175: 
 6176: =cut
 6177: 
 6178: sub check_for_error {
 6179:     my ($r,$result)=@_;
 6180:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6181: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6182:     }
 6183: }
 6184: 
 6185: =pod
 6186: 
 6187: =item scantron_warning_screen
 6188: 
 6189:    Interstitial screen to make sure the operator has selected the
 6190:    correct options before we start the validation phase.
 6191: 
 6192: =cut
 6193: 
 6194: sub scantron_warning_screen {
 6195:     my ($button_text)=@_;
 6196:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6197:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6198:     my $CODElist;
 6199:     if ($scantron_config{'CODElocation'} &&
 6200: 	$scantron_config{'CODEstart'} &&
 6201: 	$scantron_config{'CODElength'}) {
 6202: 	$CODElist=$env{'form.scantron_CODElist'};
 6203: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6204: 	$CODElist=
 6205: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6206: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6207:     }
 6208:     return ('
 6209: <p>
 6210: <span class="LC_warning">
 6211: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6212: </p>
 6213: <table>
 6214: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6215: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6216: '.$CODElist.'
 6217: </table>
 6218: <br />
 6219: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6220: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6221: 
 6222: <br />
 6223: ');
 6224: }
 6225: 
 6226: =pod
 6227: 
 6228: =item scantron_do_warning
 6229: 
 6230:    Check if the operator has picked something for all required
 6231:    fields. Error out if something is missing.
 6232: 
 6233: =cut
 6234: 
 6235: sub scantron_do_warning {
 6236:     my ($r)=@_;
 6237:     my ($symb)=&get_symb($r);
 6238:     if (!$symb) {return '';}
 6239:     my $default_form_data=&defaultFormData($symb);
 6240:     $r->print(&scantron_form_start().$default_form_data);
 6241:     if ( $env{'form.selectpage'} eq '' ||
 6242: 	 $env{'form.scantron_selectfile'} eq '' ||
 6243: 	 $env{'form.scantron_format'} eq '' ) {
 6244: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6245: 	if ( $env{'form.selectpage'} eq '') {
 6246: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6247: 	} 
 6248: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6249: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6250: 	} 
 6251: 	if ( $env{'form.scantron_format'} eq '') {
 6252: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6253: 	} 
 6254:     } else {
 6255: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6256: 	$r->print('
 6257: '.$warning.'
 6258: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6259: <input type="hidden" name="command" value="scantron_validate" />
 6260: ');
 6261:     }
 6262:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6263:     return '';
 6264: }
 6265: 
 6266: =pod
 6267: 
 6268: =item scantron_form_start
 6269: 
 6270:     html hidden input for remembering all selected grading options
 6271: 
 6272: =cut
 6273: 
 6274: sub scantron_form_start {
 6275:     my ($max_bubble)=@_;
 6276:     my $result= <<SCANTRONFORM;
 6277: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6278:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6279:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6280:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6281:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6282:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6283:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6284:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6285:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6286:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6287: SCANTRONFORM
 6288: 
 6289:   my $line = 0;
 6290:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6291:        my $chunk =
 6292: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6293:        $chunk .=
 6294: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6295:        $chunk .= 
 6296:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6297:        $chunk .=
 6298:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6299:        $result .= $chunk;
 6300:        $line++;
 6301:    }
 6302:     return $result;
 6303: }
 6304: 
 6305: =pod
 6306: 
 6307: =item scantron_validate_file
 6308: 
 6309:     Dispatch routine for doing validation of a bubble sheet data file.
 6310: 
 6311:     Also processes any necessary information resets that need to
 6312:     occur before validation begins (ignore previous corrections,
 6313:     restarting the skipped records processing)
 6314: 
 6315: =cut
 6316: 
 6317: sub scantron_validate_file {
 6318:     my ($r) = @_;
 6319:     my ($symb)=&get_symb($r);
 6320:     if (!$symb) {return '';}
 6321:     my $default_form_data=&defaultFormData($symb);
 6322:     
 6323:     # do the detection of only doing skipped records first befroe we delete
 6324:     # them when doing the corrections reset
 6325:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6326: 	&reset_skipping_status();
 6327:     }
 6328:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6329: 	&remember_current_skipped();
 6330: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6331:     }
 6332: 
 6333:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6334: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6335: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6336: 	&check_for_error($r,&scantron_remove_scan_data());
 6337: 	$env{'form.scantron_options_ignore'}='done';
 6338:     }
 6339: 
 6340:     if ($env{'form.scantron_corrections'}) {
 6341: 	&scantron_process_corrections($r);
 6342:     }
 6343:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6344:     #get the student pick code ready
 6345:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6346:     my $nav_error;
 6347:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6348:     if ($nav_error) {
 6349:         $r->print(&navmap_errormsg());
 6350:         return '';
 6351:     }
 6352:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6353:     $r->print($result);
 6354:     
 6355:     my @validate_phases=( 'sequence',
 6356: 			  'ID',
 6357: 			  'CODE',
 6358: 			  'doublebubble',
 6359: 			  'missingbubbles');
 6360:     if (!$env{'form.validatepass'}) {
 6361: 	$env{'form.validatepass'} = 0;
 6362:     }
 6363:     my $currentphase=$env{'form.validatepass'};
 6364: 
 6365: 
 6366:     my $stop=0;
 6367:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6368: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6369: 	$r->rflush();
 6370: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6371: 	{
 6372: 	    no strict 'refs';
 6373: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6374: 	}
 6375:     }
 6376:     if (!$stop) {
 6377: 	my $warning=&scantron_warning_screen('Start Grading');
 6378: 	$r->print(&mt('Validation process complete.').'<br />'.
 6379:                   $warning.
 6380:                   &mt('Perform verification for each student after storage of submissions?').
 6381:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6382:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6383:                   ('&nbsp;'x3).'<label>'.
 6384:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6385:                   '</label></span><br />'.
 6386:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6387:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6388:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6389:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6390:     } else {
 6391: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6392: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6393:     }
 6394:     if ($stop) {
 6395: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6396: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6397: 	    $r->print(' '.&mt('this error').' <br />');
 6398: 
 6399: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6400: 	} else {
 6401:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6402: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6403:             } else {
 6404:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6405:             }
 6406: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6407: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6408: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6409: 	}
 6410:     }
 6411:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6412:     return '';
 6413: }
 6414: 
 6415: 
 6416: =pod
 6417: 
 6418: =item scantron_remove_file
 6419: 
 6420:    Removes the requested bubble sheet data file, makes sure that
 6421:    scantron_original_<filename> is never removed
 6422: 
 6423: 
 6424: =cut
 6425: 
 6426: sub scantron_remove_file {
 6427:     my ($which)=@_;
 6428:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6429:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6430:     my $file='scantron_';
 6431:     if ($which eq 'corrected' || $which eq 'skipped') {
 6432: 	$file.=$which.'_';
 6433:     } else {
 6434: 	return 'refused';
 6435:     }
 6436:     $file.=$env{'form.scantron_selectfile'};
 6437:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6438: }
 6439: 
 6440: 
 6441: =pod
 6442: 
 6443: =item scantron_remove_scan_data
 6444: 
 6445:    Removes all scan_data correction for the requested bubble sheet
 6446:    data file.  (In the case that both the are doing skipped records we need
 6447:    to remember the old skipped lines for the time being so that element
 6448:    persists for a while.)
 6449: 
 6450: =cut
 6451: 
 6452: sub scantron_remove_scan_data {
 6453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6455:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6456:     my @todelete;
 6457:     my $filename=$env{'form.scantron_selectfile'};
 6458:     foreach my $key (@keys) {
 6459: 	if ($key=~/^\Q$filename\E_/) {
 6460: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6461: 		$key=~/remember_skipping/) {
 6462: 		next;
 6463: 	    }
 6464: 	    push(@todelete,$key);
 6465: 	}
 6466:     }
 6467:     my $result;
 6468:     if (@todelete) {
 6469: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6470: 				       \@todelete,$cdom,$cname);
 6471:     } else {
 6472: 	$result = 'ok';
 6473:     }
 6474:     return $result;
 6475: }
 6476: 
 6477: 
 6478: =pod
 6479: 
 6480: =item scantron_getfile
 6481: 
 6482:     Fetches the requested bubble sheet data file (all 3 versions), and
 6483:     the scan_data hash
 6484:   
 6485:   Arguments:
 6486:     None
 6487: 
 6488:   Returns:
 6489:     2 hash references
 6490: 
 6491:      - first one has 
 6492:          orig      -
 6493:          corrected -
 6494:          skipped   -  each of which points to an array ref of the specified
 6495:                       file broken up into individual lines
 6496:          count     - number of scanlines
 6497:  
 6498:      - second is the scan_data hash possible keys are
 6499:        ($number refers to scanline numbered $number and thus the key affects
 6500:         only that scanline
 6501:         $bubline refers to the specific bubble line element and the aspects
 6502:         refers to that specific bubble line element)
 6503: 
 6504:        $number.user - username:domain to use
 6505:        $number.CODE_ignore_dup 
 6506:                     - ignore the duplicate CODE error 
 6507:        $number.useCODE
 6508:                     - use the CODE in the scanline as is
 6509:        $number.no_bubble.$bubline
 6510:                     - it is valid that there is no bubbled in bubble
 6511:                       at $number $bubline
 6512:        remember_skipping
 6513:                     - a frozen hash containing keys of $number and values
 6514:                       of either 
 6515:                         1 - we are on a 'do skipped records pass' and plan
 6516:                             on processing this line
 6517:                         2 - we are on a 'do skipped records pass' and this
 6518:                             scanline has been marked to skip yet again
 6519: 
 6520: =cut
 6521: 
 6522: sub scantron_getfile {
 6523:     #FIXME really would prefer a scantron directory
 6524:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6525:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6526:     my $lines;
 6527:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6528: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6529:     my %scanlines;
 6530:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6531:     my $temp=$scanlines{'orig'};
 6532:     $scanlines{'count'}=$#$temp;
 6533: 
 6534:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6535: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6536:     if ($lines eq '-1') {
 6537: 	$scanlines{'corrected'}=[];
 6538:     } else {
 6539: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6540:     }
 6541:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6542: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6543:     if ($lines eq '-1') {
 6544: 	$scanlines{'skipped'}=[];
 6545:     } else {
 6546: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6547:     }
 6548:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6549:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6550:     my %scan_data = @tmp;
 6551:     return (\%scanlines,\%scan_data);
 6552: }
 6553: 
 6554: =pod
 6555: 
 6556: =item lonnet_putfile
 6557: 
 6558:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6559: 
 6560:  Arguments:
 6561:    $contents - data to store
 6562:    $filename - filename to store $contents into
 6563: 
 6564:  Returns:
 6565:    result value from &Apache::lonnet::finishuserfileupload
 6566: 
 6567: =cut
 6568: 
 6569: sub lonnet_putfile {
 6570:     my ($contents,$filename)=@_;
 6571:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6572:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6573:     $env{'form.sillywaytopassafilearound'}=$contents;
 6574:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6575: 
 6576: }
 6577: 
 6578: =pod
 6579: 
 6580: =item scantron_putfile
 6581: 
 6582:     Stores the current version of the bubble sheet data files, and the
 6583:     scan_data hash. (Does not modify the original version only the
 6584:     corrected and skipped versions.
 6585: 
 6586:  Arguments:
 6587:     $scanlines - hash ref that looks like the first return value from
 6588:                  &scantron_getfile()
 6589:     $scan_data - hash ref that looks like the second return value from
 6590:                  &scantron_getfile()
 6591: 
 6592: =cut
 6593: 
 6594: sub scantron_putfile {
 6595:     my ($scanlines,$scan_data) = @_;
 6596:     #FIXME really would prefer a scantron directory
 6597:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6598:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6599:     if ($scanlines) {
 6600: 	my $prefix='scantron_';
 6601: # no need to update orig, shouldn't change
 6602: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6603: #		    $env{'form.scantron_selectfile'});
 6604: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6605: 			$prefix.'corrected_'.
 6606: 			$env{'form.scantron_selectfile'});
 6607: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6608: 			$prefix.'skipped_'.
 6609: 			$env{'form.scantron_selectfile'});
 6610:     }
 6611:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6612: }
 6613: 
 6614: =pod
 6615: 
 6616: =item scantron_get_line
 6617: 
 6618:    Returns the correct version of the scanline
 6619: 
 6620:  Arguments:
 6621:     $scanlines - hash ref that looks like the first return value from
 6622:                  &scantron_getfile()
 6623:     $scan_data - hash ref that looks like the second return value from
 6624:                  &scantron_getfile()
 6625:     $i         - number of the requested line (starts at 0)
 6626: 
 6627:  Returns:
 6628:    A scanline, (either the original or the corrected one if it
 6629:    exists), or undef if the requested scanline should be
 6630:    skipped. (Either because it's an skipped scanline, or it's an
 6631:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6632:    pass.
 6633: 
 6634: =cut
 6635: 
 6636: sub scantron_get_line {
 6637:     my ($scanlines,$scan_data,$i)=@_;
 6638:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6639:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6640:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6641:     return $scanlines->{'orig'}[$i]; 
 6642: }
 6643: 
 6644: =pod
 6645: 
 6646: =item scantron_todo_count
 6647: 
 6648:     Counts the number of scanlines that need processing.
 6649: 
 6650:  Arguments:
 6651:     $scanlines - hash ref that looks like the first return value from
 6652:                  &scantron_getfile()
 6653:     $scan_data - hash ref that looks like the second return value from
 6654:                  &scantron_getfile()
 6655: 
 6656:  Returns:
 6657:     $count - number of scanlines to process
 6658: 
 6659: =cut
 6660: 
 6661: sub get_todo_count {
 6662:     my ($scanlines,$scan_data)=@_;
 6663:     my $count=0;
 6664:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6665: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6666: 	if ($line=~/^[\s\cz]*$/) { next; }
 6667: 	$count++;
 6668:     }
 6669:     return $count;
 6670: }
 6671: 
 6672: =pod
 6673: 
 6674: =item scantron_put_line
 6675: 
 6676:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6677:     data file.
 6678: 
 6679:  Arguments:
 6680:     $scanlines - hash ref that looks like the first return value from
 6681:                  &scantron_getfile()
 6682:     $scan_data - hash ref that looks like the second return value from
 6683:                  &scantron_getfile()
 6684:     $i         - line number to update
 6685:     $newline   - contents of the updated scanline
 6686:     $skip      - if true make the line for skipping and update the
 6687:                  'skipped' file
 6688: 
 6689: =cut
 6690: 
 6691: sub scantron_put_line {
 6692:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6693:     if ($skip) {
 6694: 	$scanlines->{'skipped'}[$i]=$newline;
 6695: 	&start_skipping($scan_data,$i);
 6696: 	return;
 6697:     }
 6698:     $scanlines->{'corrected'}[$i]=$newline;
 6699: }
 6700: 
 6701: =pod
 6702: 
 6703: =item scantron_clear_skip
 6704: 
 6705:    Remove a line from the 'skipped' file
 6706: 
 6707:  Arguments:
 6708:     $scanlines - hash ref that looks like the first return value from
 6709:                  &scantron_getfile()
 6710:     $scan_data - hash ref that looks like the second return value from
 6711:                  &scantron_getfile()
 6712:     $i         - line number to update
 6713: 
 6714: =cut
 6715: 
 6716: sub scantron_clear_skip {
 6717:     my ($scanlines,$scan_data,$i)=@_;
 6718:     if (exists($scanlines->{'skipped'}[$i])) {
 6719: 	undef($scanlines->{'skipped'}[$i]);
 6720: 	return 1;
 6721:     }
 6722:     return 0;
 6723: }
 6724: 
 6725: =pod
 6726: 
 6727: =item scantron_filter_not_exam
 6728: 
 6729:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6730:    filter out resources that are not marked as 'exam' mode
 6731: 
 6732: =cut
 6733: 
 6734: sub scantron_filter_not_exam {
 6735:     my ($curres)=@_;
 6736:     
 6737:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6738: 	# if the user has asked to not have either hidden
 6739: 	# or 'randomout' controlled resources to be graded
 6740: 	# don't include them
 6741: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6742: 	    && $curres->randomout) {
 6743: 	    return 0;
 6744: 	}
 6745: 	return 1;
 6746:     }
 6747:     return 0;
 6748: }
 6749: 
 6750: =pod
 6751: 
 6752: =item scantron_validate_sequence
 6753: 
 6754:     Validates the selected sequence, checking for resource that are
 6755:     not set to exam mode.
 6756: 
 6757: =cut
 6758: 
 6759: sub scantron_validate_sequence {
 6760:     my ($r,$currentphase) = @_;
 6761: 
 6762:     my $navmap=Apache::lonnavmaps::navmap->new();
 6763:     unless (ref($navmap)) {
 6764:         $r->print(&navmap_errormsg());
 6765:         return (1,$currentphase);
 6766:     }
 6767:     my (undef,undef,$sequence)=
 6768: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6769: 
 6770:     my $map=$navmap->getResourceByUrl($sequence);
 6771: 
 6772:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6773:                                     value="ignore" />');
 6774:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6775: 	my @resources=
 6776: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6777: 	if (@resources) {
 6778: 	    $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>");
 6779: 	    return (1,$currentphase);
 6780: 	}
 6781:     }
 6782: 
 6783:     return (0,$currentphase+1);
 6784: }
 6785: 
 6786: 
 6787: 
 6788: sub scantron_validate_ID {
 6789:     my ($r,$currentphase) = @_;
 6790:     
 6791:     #get student info
 6792:     my $classlist=&Apache::loncoursedata::get_classlist();
 6793:     my %idmap=&username_to_idmap($classlist);
 6794: 
 6795:     #get scantron line setup
 6796:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6797:     my ($scanlines,$scan_data)=&scantron_getfile();
 6798: 
 6799:     my $nav_error;
 6800:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6801:     if ($nav_error) {
 6802:         $r->print(&navmap_errormsg());
 6803:         return(1,$currentphase);
 6804:     }
 6805: 
 6806:     my %found=('ids'=>{},'usernames'=>{});
 6807:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6808: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6809: 	if ($line=~/^[\s\cz]*$/) { next; }
 6810: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6811: 						 $scan_data);
 6812: 	my $id=$$scan_record{'scantron.ID'};
 6813: 	my $found;
 6814: 	foreach my $checkid (keys(%idmap)) {
 6815: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6816: 	}
 6817: 	if ($found) {
 6818: 	    my $username=$idmap{$found};
 6819: 	    if ($found{'ids'}{$found}) {
 6820: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6821: 					 $line,'duplicateID',$found);
 6822: 		return(1,$currentphase);
 6823: 	    } elsif ($found{'usernames'}{$username}) {
 6824: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6825: 					 $line,'duplicateID',$username);
 6826: 		return(1,$currentphase);
 6827: 	    }
 6828: 	    #FIXME store away line we previously saw the ID on to use above
 6829: 	    $found{'ids'}{$found}++;
 6830: 	    $found{'usernames'}{$username}++;
 6831: 	} else {
 6832: 	    if ($id =~ /^\s*$/) {
 6833: 		my $username=&scan_data($scan_data,"$i.user");
 6834: 		if (defined($username) && $found{'usernames'}{$username}) {
 6835: 		    &scantron_get_correction($r,$i,$scan_record,
 6836: 					     \%scantron_config,
 6837: 					     $line,'duplicateID',$username);
 6838: 		    return(1,$currentphase);
 6839: 		} elsif (!defined($username)) {
 6840: 		    &scantron_get_correction($r,$i,$scan_record,
 6841: 					     \%scantron_config,
 6842: 					     $line,'incorrectID');
 6843: 		    return(1,$currentphase);
 6844: 		}
 6845: 		$found{'usernames'}{$username}++;
 6846: 	    } else {
 6847: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6848: 					 $line,'incorrectID');
 6849: 		return(1,$currentphase);
 6850: 	    }
 6851: 	}
 6852:     }
 6853: 
 6854:     return (0,$currentphase+1);
 6855: }
 6856: 
 6857: 
 6858: sub scantron_get_correction {
 6859:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6860: #FIXME in the case of a duplicated ID the previous line, probably need
 6861: #to show both the current line and the previous one and allow skipping
 6862: #the previous one or the current one
 6863: 
 6864:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6865: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6866: 			    " for PaperID <tt>[_1]</tt>",
 6867: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6868:     } else {
 6869: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6870: 			    " in scanline [_1] <pre>[_2]</pre>",
 6871: 			    $i,$line)."</p> \n");
 6872:     }
 6873:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6874: 			  "The name on the paper is [_2],[_3]",
 6875: 			  $$scan_record{'scantron.ID'},
 6876: 			  $$scan_record{'scantron.LastName'},
 6877: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6878: 
 6879:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6880:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6881:                            # Array populated for doublebubble or
 6882:     my @lines_to_correct;  # missingbubble errors to build javascript
 6883:                            # to validate radio button checking   
 6884: 
 6885:     if ($error =~ /ID$/) {
 6886: 	if ($error eq 'incorrectID') {
 6887: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6888: 		      "</p>\n");
 6889: 	} elsif ($error eq 'duplicateID') {
 6890: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6891: 	}
 6892: 	$r->print($message);
 6893: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6894: 	$r->print("\n<ul><li> ");
 6895: 	#FIXME it would be nice if this sent back the user ID and
 6896: 	#could do partial userID matches
 6897: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6898: 				       'scantron_username','scantron_domain'));
 6899: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6900: 	$r->print("\n@".
 6901: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6902: 
 6903: 	$r->print('</li>');
 6904:     } elsif ($error =~ /CODE$/) {
 6905: 	if ($error eq 'incorrectCODE') {
 6906: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6907: 	} elsif ($error eq 'duplicateCODE') {
 6908: 	    $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");
 6909: 	}
 6910: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6911: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6912: 	$r->print($message);
 6913: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6914: 	$r->print("\n<br /> ");
 6915: 	my $i=0;
 6916: 	if ($error eq 'incorrectCODE' 
 6917: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6918: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6919: 	    if ($closest > 0) {
 6920: 		foreach my $testcode (@{$closest}) {
 6921: 		    my $checked='';
 6922: 		    if (!$i) { $checked=' checked="checked"'; }
 6923: 		    $r->print("
 6924:    <label>
 6925:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6926:        ".&mt("Use the similar CODE [_1] instead.",
 6927: 	    "<b><tt>".$testcode."</tt></b>")."
 6928:     </label>
 6929:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6930: 		    $r->print("\n<br />");
 6931: 		    $i++;
 6932: 		}
 6933: 	    }
 6934: 	}
 6935: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6936: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6937: 	    $r->print("
 6938:     <label>
 6939:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6940:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6941: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6942:     </label>");
 6943: 	    $r->print("\n<br />");
 6944: 	}
 6945: 
 6946: 	$r->print(<<ENDSCRIPT);
 6947: <script type="text/javascript">
 6948: function change_radio(field) {
 6949:     var slct=document.scantronupload.scantron_CODE_resolution;
 6950:     var i;
 6951:     for (i=0;i<slct.length;i++) {
 6952:         if (slct[i].value==field) { slct[i].checked=true; }
 6953:     }
 6954: }
 6955: </script>
 6956: ENDSCRIPT
 6957: 	my $href="/adm/pickcode?".
 6958: 	   "form=".&escape("scantronupload").
 6959: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6960: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6961: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6962: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6963: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6964: 	    $r->print("
 6965:     <label>
 6966:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6967:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6968: 	     "<a target='_blank' href='$href'>","</a>")."
 6969:     </label> 
 6970:     ".&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\')" />'));
 6971: 	    $r->print("\n<br />");
 6972: 	}
 6973: 	$r->print("
 6974:     <label>
 6975:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6976:        ".&mt("Use [_1] as the CODE.",
 6977: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6978: 	$r->print("\n<br /><br />");
 6979:     } elsif ($error eq 'doublebubble') {
 6980: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6981: 
 6982: 	# The form field scantron_questions is acutally a list of line numbers.
 6983: 	# represented by this form so:
 6984: 
 6985: 	my $line_list = &questions_to_line_list($arg);
 6986: 
 6987: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6988: 		  $line_list.'" />');
 6989: 	$r->print($message);
 6990: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6991: 	foreach my $question (@{$arg}) {
 6992: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6993:                                                    $scan_record, $error);
 6994:             push(@lines_to_correct,@linenums);
 6995: 	}
 6996:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6997:     } elsif ($error eq 'missingbubble') {
 6998: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6999: 	$r->print($message);
 7000: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7001: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7002: 
 7003: 	# The form field scantron_questions is actually a list of line numbers not
 7004: 	# a list of question numbers. Therefore:
 7005: 	#
 7006: 	
 7007: 	my $line_list = &questions_to_line_list($arg);
 7008: 
 7009: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7010: 		  $line_list.'" />');
 7011: 	foreach my $question (@{$arg}) {
 7012: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7013:                                                    $scan_record, $error);
 7014:             push(@lines_to_correct,@linenums);
 7015: 	}
 7016:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7017:     } else {
 7018: 	$r->print("\n<ul>");
 7019:     }
 7020:     $r->print("\n</li></ul>");
 7021: }
 7022: 
 7023: sub verify_bubbles_checked {
 7024:     my (@ansnums) = @_;
 7025:     my $ansnumstr = join('","',@ansnums);
 7026:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7027:     my $output = (<<ENDSCRIPT);
 7028: <script type="text/javascript">
 7029: function verify_bubble_radio(form) {
 7030:     var ansnumArray = new Array ("$ansnumstr");
 7031:     var need_bubble_count = 0;
 7032:     for (var i=0; i<ansnumArray.length; i++) {
 7033:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7034:             var bubble_picked = 0; 
 7035:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7036:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7037:                     bubble_picked = 1;
 7038:                 }
 7039:             }
 7040:             if (bubble_picked == 0) {
 7041:                 need_bubble_count ++;
 7042:             }
 7043:         }
 7044:     }
 7045:     if (need_bubble_count) {
 7046:         alert("$warning");
 7047:         return;
 7048:     }
 7049:     form.submit(); 
 7050: }
 7051: </script>
 7052: ENDSCRIPT
 7053:     return $output;
 7054: }
 7055: 
 7056: =pod
 7057: 
 7058: =item  questions_to_line_list
 7059: 
 7060: Converts a list of questions into a string of comma separated
 7061: line numbers in the answer sheet used by the questions.  This is
 7062: used to fill in the scantron_questions form field.
 7063: 
 7064:   Arguments:
 7065:      questions    - Reference to an array of questions.
 7066: 
 7067: =cut
 7068: 
 7069: 
 7070: sub questions_to_line_list {
 7071:     my ($questions) = @_;
 7072:     my @lines;
 7073: 
 7074:     foreach my $item (@{$questions}) {
 7075:         my $question = $item;
 7076:         my ($first,$count,$last);
 7077:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7078:             $question = $1;
 7079:             my $subquestion = $2;
 7080:             $first = $first_bubble_line{$question-1} + 1;
 7081:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7082:             my $subcount = 1;
 7083:             while ($subcount<$subquestion) {
 7084:                 $first += $subans[$subcount-1];
 7085:                 $subcount ++;
 7086:             }
 7087:             $count = $subans[$subquestion-1];
 7088:         } else {
 7089: 	    $first   = $first_bubble_line{$question-1} + 1;
 7090: 	    $count   = $bubble_lines_per_response{$question-1};
 7091:         }
 7092:         $last = $first+$count-1;
 7093:         push(@lines, ($first..$last));
 7094:     }
 7095:     return join(',', @lines);
 7096: }
 7097: 
 7098: =pod 
 7099: 
 7100: =item prompt_for_corrections
 7101: 
 7102: Prompts for a potentially multiline correction to the
 7103: user's bubbling (factors out common code from scantron_get_correction
 7104: for multi and missing bubble cases).
 7105: 
 7106:  Arguments:
 7107:    $r           - Apache request object.
 7108:    $question    - The question number to prompt for.
 7109:    $scan_config - The scantron file configuration hash.
 7110:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7111:    $error       - Type of error
 7112: 
 7113:  Implicit inputs:
 7114:    %bubble_lines_per_response   - Starting line numbers for each question.
 7115:                                   Numbered from 0 (but question numbers are from
 7116:                                   1.
 7117:    %first_bubble_line           - Starting bubble line for each question.
 7118:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7119:                                   type problems render as separate sub-questions, 
 7120:                                   in exam mode. This hash contains a 
 7121:                                   comma-separated list of the lines per 
 7122:                                   sub-question.
 7123:    %responsetype_per_response   - essayresponse, formularesponse,
 7124:                                   stringresponse, imageresponse, reactionresponse,
 7125:                                   and organicresponse type problem parts can have
 7126:                                   multiple lines per response if the weight
 7127:                                   assigned exceeds 10.  In this case, only
 7128:                                   one bubble per line is permitted, but more 
 7129:                                   than one line might contain bubbles, e.g.
 7130:                                   bubbling of: line 1 - J, line 2 - J, 
 7131:                                   line 3 - B would assign 22 points.  
 7132: 
 7133: =cut
 7134: 
 7135: sub prompt_for_corrections {
 7136:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7137:     my ($current_line,$lines);
 7138:     my @linenums;
 7139:     my $questionnum = $question;
 7140:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7141:         $question = $1;
 7142:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7143:         my $subquestion = $2;
 7144:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7145:         my $subcount = 1;
 7146:         while ($subcount<$subquestion) {
 7147:             $current_line += $subans[$subcount-1];
 7148:             $subcount ++;
 7149:         }
 7150:         $lines = $subans[$subquestion-1];
 7151:     } else {
 7152:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7153:         $lines        = $bubble_lines_per_response{$question-1};
 7154:     }
 7155:     if ($lines > 1) {
 7156:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7157:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7158:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7159:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7160:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7161:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7162:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7163:             $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 />');
 7164:         } else {
 7165:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7166:         }
 7167:     }
 7168:     for (my $i =0; $i < $lines; $i++) {
 7169:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7170: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7171: 	        		  $questionnum,$error,split('', $selected));
 7172:         push(@linenums,$current_line);
 7173: 	$current_line++;
 7174:     }
 7175:     if ($lines > 1) {
 7176: 	$r->print("<hr /><br />");
 7177:     }
 7178:     return @linenums;
 7179: }
 7180: 
 7181: =pod
 7182: 
 7183: =item scantron_bubble_selector
 7184:   
 7185:    Generates the html radiobuttons to correct a single bubble line
 7186:    possibly showing the existing the selected bubbles if known
 7187: 
 7188:  Arguments:
 7189:     $r           - Apache request object
 7190:     $scan_config - hash from &get_scantron_config()
 7191:     $line        - Number of the line being displayed.
 7192:     $questionnum - Question number (may include subquestion)
 7193:     $error       - Type of error.
 7194:     @selected    - Array of bubbles picked on this line.
 7195: 
 7196: =cut
 7197: 
 7198: sub scantron_bubble_selector {
 7199:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7200:     my $max=$$scan_config{'Qlength'};
 7201: 
 7202:     my $scmode=$$scan_config{'Qon'};
 7203:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7204: 
 7205:     my @alphabet=('A'..'Z');
 7206:     $r->print(&Apache::loncommon::start_data_table().
 7207:               &Apache::loncommon::start_data_table_row());
 7208:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7209:     for (my $i=0;$i<$max+1;$i++) {
 7210: 	$r->print("\n".'<td align="center">');
 7211: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7212: 	else { $r->print('&nbsp;'); }
 7213: 	$r->print('</td>');
 7214:     }
 7215:     $r->print(&Apache::loncommon::end_data_table_row().
 7216:               &Apache::loncommon::start_data_table_row());
 7217:     for (my $i=0;$i<$max;$i++) {
 7218: 	$r->print("\n".
 7219: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7220: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7221:     }
 7222:     my $nobub_checked = ' ';
 7223:     if ($error eq 'missingbubble') {
 7224:         $nobub_checked = ' checked = "checked" ';
 7225:     }
 7226:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7227: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7228:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7229:               $line.'" value="'.$questionnum.'" /></td>');
 7230:     $r->print(&Apache::loncommon::end_data_table_row().
 7231:               &Apache::loncommon::end_data_table());
 7232: }
 7233: 
 7234: =pod
 7235: 
 7236: =item num_matches
 7237: 
 7238:    Counts the number of characters that are the same between the two arguments.
 7239: 
 7240:  Arguments:
 7241:    $orig - CODE from the scanline
 7242:    $code - CODE to match against
 7243: 
 7244:  Returns:
 7245:    $count - integer count of the number of same characters between the
 7246:             two arguments
 7247: 
 7248: =cut
 7249: 
 7250: sub num_matches {
 7251:     my ($orig,$code) = @_;
 7252:     my @code=split(//,$code);
 7253:     my @orig=split(//,$orig);
 7254:     my $same=0;
 7255:     for (my $i=0;$i<scalar(@code);$i++) {
 7256: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7257:     }
 7258:     return $same;
 7259: }
 7260: 
 7261: =pod
 7262: 
 7263: =item scantron_get_closely_matching_CODEs
 7264: 
 7265:    Cycles through all CODEs and finds the set that has the greatest
 7266:    number of same characters as the provided CODE
 7267: 
 7268:  Arguments:
 7269:    $allcodes - hash ref returned by &get_codes()
 7270:    $CODE     - CODE from the current scanline
 7271: 
 7272:  Returns:
 7273:    2 element list
 7274:     - first elements is number of how closely matching the best fit is 
 7275:       (5 means best set has 5 matching characters)
 7276:     - second element is an arrary ref containing the set of valid CODEs
 7277:       that best fit the passed in CODE
 7278: 
 7279: =cut
 7280: 
 7281: sub scantron_get_closely_matching_CODEs {
 7282:     my ($allcodes,$CODE)=@_;
 7283:     my @CODEs;
 7284:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7285: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7286:     }
 7287: 
 7288:     return ($#CODEs,$CODEs[-1]);
 7289: }
 7290: 
 7291: =pod
 7292: 
 7293: =item get_codes
 7294: 
 7295:    Builds a hash which has keys of all of the valid CODEs from the selected
 7296:    set of remembered CODEs.
 7297: 
 7298:  Arguments:
 7299:   $old_name - name of the set of remembered CODEs
 7300:   $cdom     - domain of the course
 7301:   $cnum     - internal course name
 7302: 
 7303:  Returns:
 7304:   %allcodes - keys are the valid CODEs, values are all 1
 7305: 
 7306: =cut
 7307: 
 7308: sub get_codes {
 7309:     my ($old_name, $cdom, $cnum) = @_;
 7310:     if (!$old_name) {
 7311: 	$old_name=$env{'form.scantron_CODElist'};
 7312:     }
 7313:     if (!$cdom) {
 7314: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7315:     }
 7316:     if (!$cnum) {
 7317: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7318:     }
 7319:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7320: 				    $cdom,$cnum);
 7321:     my %allcodes;
 7322:     if ($result{"type\0$old_name"} eq 'number') {
 7323: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7324:     } else {
 7325: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7326:     }
 7327:     return %allcodes;
 7328: }
 7329: 
 7330: =pod
 7331: 
 7332: =item scantron_validate_CODE
 7333: 
 7334:    Validates all scanlines in the selected file to not have any
 7335:    invalid or underspecified CODEs and that none of the codes are
 7336:    duplicated if this was requested.
 7337: 
 7338: =cut
 7339: 
 7340: sub scantron_validate_CODE {
 7341:     my ($r,$currentphase) = @_;
 7342:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7343:     if ($scantron_config{'CODElocation'} &&
 7344: 	$scantron_config{'CODEstart'} &&
 7345: 	$scantron_config{'CODElength'}) {
 7346: 	if (!defined($env{'form.scantron_CODElist'})) {
 7347: 	    &FIXME_blow_up()
 7348: 	}
 7349:     } else {
 7350: 	return (0,$currentphase+1);
 7351:     }
 7352:     
 7353:     my %usedCODEs;
 7354: 
 7355:     my %allcodes=&get_codes();
 7356: 
 7357:     my $nav_error;
 7358:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7359:     if ($nav_error) {
 7360:         $r->print(&navmap_errormsg());
 7361:         return(1,$currentphase);
 7362:     }
 7363: 
 7364:     my ($scanlines,$scan_data)=&scantron_getfile();
 7365:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7366: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7367: 	if ($line=~/^[\s\cz]*$/) { next; }
 7368: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7369: 						 $scan_data);
 7370: 	my $CODE=$$scan_record{'scantron.CODE'};
 7371: 	my $error=0;
 7372: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7373: 	    &scantron_get_correction($r,$i,$scan_record,
 7374: 				     \%scantron_config,
 7375: 				     $line,'incorrectCODE',\%allcodes);
 7376: 	    return(1,$currentphase);
 7377: 	}
 7378: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7379: 	    && !$$scan_record{'scantron.useCODE'}) {
 7380: 	    &scantron_get_correction($r,$i,$scan_record,
 7381: 				     \%scantron_config,
 7382: 				     $line,'incorrectCODE',\%allcodes);
 7383: 	    return(1,$currentphase);
 7384: 	}
 7385: 	if (exists($usedCODEs{$CODE}) 
 7386: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7387: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7388: 	    &scantron_get_correction($r,$i,$scan_record,
 7389: 				     \%scantron_config,
 7390: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7391: 	    return(1,$currentphase);
 7392: 	}
 7393: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7394:     }
 7395:     return (0,$currentphase+1);
 7396: }
 7397: 
 7398: =pod
 7399: 
 7400: =item scantron_validate_doublebubble
 7401: 
 7402:    Validates all scanlines in the selected file to not have any
 7403:    bubble lines with multiple bubbles marked.
 7404: 
 7405: =cut
 7406: 
 7407: sub scantron_validate_doublebubble {
 7408:     my ($r,$currentphase) = @_;
 7409:     #get student info
 7410:     my $classlist=&Apache::loncoursedata::get_classlist();
 7411:     my %idmap=&username_to_idmap($classlist);
 7412: 
 7413:     #get scantron line setup
 7414:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7415:     my ($scanlines,$scan_data)=&scantron_getfile();
 7416:     my $nav_error;
 7417:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7418:     if ($nav_error) {
 7419:         $r->print(&navmap_errormsg());
 7420:         return(1,$currentphase);
 7421:     }
 7422: 
 7423:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7424: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7425: 	if ($line=~/^[\s\cz]*$/) { next; }
 7426: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7427: 						 $scan_data);
 7428: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7429: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7430: 				 'doublebubble',
 7431: 				 $$scan_record{'scantron.doubleerror'});
 7432:     	return (1,$currentphase);
 7433:     }
 7434:     return (0,$currentphase+1);
 7435: }
 7436: 
 7437: 
 7438: sub scantron_get_maxbubble {
 7439:     my ($nav_error) = @_;
 7440:     if (defined($env{'form.scantron_maxbubble'}) &&
 7441: 	$env{'form.scantron_maxbubble'}) {
 7442: 	&restore_bubble_lines();
 7443: 	return $env{'form.scantron_maxbubble'};
 7444:     }
 7445: 
 7446:     my (undef, undef, $sequence) =
 7447: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7448: 
 7449:     my $navmap=Apache::lonnavmaps::navmap->new();
 7450:     unless (ref($navmap)) {
 7451:         if (ref($nav_error)) {
 7452:             $$nav_error = 1;
 7453:         }
 7454:     }
 7455:     my $map=$navmap->getResourceByUrl($sequence);
 7456:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7457: 
 7458:     &Apache::lonxml::clear_problem_counter();
 7459: 
 7460:     my $uname       = $env{'user.name'};
 7461:     my $udom        = $env{'user.domain'};
 7462:     my $cid         = $env{'request.course.id'};
 7463:     my $total_lines = 0;
 7464:     %bubble_lines_per_response = ();
 7465:     %first_bubble_line         = ();
 7466:     %subdivided_bubble_lines   = ();
 7467:     %responsetype_per_response = ();
 7468: 
 7469:     my $response_number = 0;
 7470:     my $bubble_line     = 0;
 7471:     foreach my $resource (@resources) {
 7472:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7473:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7474: 	    foreach my $part_id (@{$parts}) {
 7475:                 my $lines;
 7476: 
 7477: 	        # TODO - make this a persistent hash not an array.
 7478: 
 7479:                 # optionresponse, matchresponse and rankresponse type items 
 7480:                 # render as separate sub-questions in exam mode.
 7481:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7482:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7483:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7484:                     my ($numbub,$numshown);
 7485:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7486:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7487:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7488:                         }
 7489:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7490:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7491:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7492:                         }
 7493:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7494:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7495:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7496:                         }
 7497:                     }
 7498:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7499:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7500:                     }
 7501:                     my $bubbles_per_line = 10;
 7502:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7503:                     if (($numbub % $bubbles_per_line) != 0) {
 7504:                         $inner_bubble_lines++;
 7505:                     }
 7506:                     for (my $i=0; $i<$numshown; $i++) {
 7507:                         $subdivided_bubble_lines{$response_number} .= 
 7508:                             $inner_bubble_lines.',';
 7509:                     }
 7510:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7511:                     $lines = $numshown * $inner_bubble_lines;
 7512:                 } else {
 7513:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7514:                 } 
 7515: 
 7516:                 $first_bubble_line{$response_number} = $bubble_line;
 7517: 	        $bubble_lines_per_response{$response_number} = $lines;
 7518:                 $responsetype_per_response{$response_number} = 
 7519:                     $analysis->{$part_id.'.type'};
 7520: 	        $response_number++;
 7521: 
 7522: 	        $bubble_line +=  $lines;
 7523: 	        $total_lines +=  $lines;
 7524: 	    }
 7525:         }
 7526:     }
 7527:     &Apache::lonnet::delenv('scantron.');
 7528: 
 7529:     &save_bubble_lines();
 7530:     $env{'form.scantron_maxbubble'} =
 7531: 	$total_lines;
 7532:     return $env{'form.scantron_maxbubble'};
 7533: }
 7534: 
 7535: sub scantron_validate_missingbubbles {
 7536:     my ($r,$currentphase) = @_;
 7537:     #get student info
 7538:     my $classlist=&Apache::loncoursedata::get_classlist();
 7539:     my %idmap=&username_to_idmap($classlist);
 7540: 
 7541:     #get scantron line setup
 7542:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7543:     my ($scanlines,$scan_data)=&scantron_getfile();
 7544:     my $nav_error;
 7545:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7546:     if ($nav_error) {
 7547:         return(1,$currentphase);
 7548:     }
 7549:     if (!$max_bubble) { $max_bubble=2**31; }
 7550:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7551: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7552: 	if ($line=~/^[\s\cz]*$/) { next; }
 7553: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7554: 						 $scan_data);
 7555: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7556: 	my @to_correct;
 7557: 	
 7558: 	# Probably here's where the error is...
 7559: 
 7560: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7561:             my $lastbubble;
 7562:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7563:                my $question = $1;
 7564:                my $subquestion = $2;
 7565:                if (!defined($first_bubble_line{$question -1})) { next; }
 7566:                my $first = $first_bubble_line{$question-1};
 7567:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7568:                my $subcount = 1;
 7569:                while ($subcount<$subquestion) {
 7570:                    $first += $subans[$subcount-1];
 7571:                    $subcount ++;
 7572:                }
 7573:                my $count = $subans[$subquestion-1];
 7574:                $lastbubble = $first + $count;
 7575:             } else {
 7576:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7577:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7578:             }
 7579:             if ($lastbubble > $max_bubble) { next; }
 7580: 	    push(@to_correct,$missing);
 7581: 	}
 7582: 	if (@to_correct) {
 7583: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7584: 				     $line,'missingbubble',\@to_correct);
 7585: 	    return (1,$currentphase);
 7586: 	}
 7587: 
 7588:     }
 7589:     return (0,$currentphase+1);
 7590: }
 7591: 
 7592: 
 7593: sub scantron_process_students {
 7594:     my ($r) = @_;
 7595: 
 7596:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7597:     my ($symb)=&get_symb($r);
 7598:     if (!$symb) {
 7599: 	return '';
 7600:     }
 7601:     my $default_form_data=&defaultFormData($symb);
 7602: 
 7603:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7604:     my ($scanlines,$scan_data)=&scantron_getfile();
 7605:     my $classlist=&Apache::loncoursedata::get_classlist();
 7606:     my %idmap=&username_to_idmap($classlist);
 7607:     my $navmap=Apache::lonnavmaps::navmap->new();
 7608:     unless (ref($navmap)) {
 7609:         $r->print(&navmap_errormsg());
 7610:         return '';
 7611:     }  
 7612:     my $map=$navmap->getResourceByUrl($sequence);
 7613:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7614:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7615:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7616:                             \%grader_randomlists_by_symb);
 7617:     my $resource_error;
 7618:     foreach my $resource (@resources) {
 7619:         my $ressymb;
 7620:         if (ref($resource)) {
 7621:             $ressymb = $resource->symb();
 7622:         } else {
 7623:             $resource_error = 1;
 7624:             last;
 7625:         }
 7626:         my ($analysis,$parts) =
 7627:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7628:                                       $env{'user.name'},$env{'user.domain'},1);
 7629:         $grader_partids_by_symb{$ressymb} = $parts;
 7630:         if (ref($analysis) eq 'HASH') {
 7631:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7632:                 $grader_randomlists_by_symb{$ressymb} = 
 7633:                     $analysis->{'parts_withrandomlist'};
 7634:             }
 7635:         }
 7636:     }
 7637:     if ($resource_error) {
 7638:         $r->print(&navmap_errormsg());
 7639:         return '';
 7640:     }
 7641: 
 7642:     my ($uname,$udom);
 7643:     my $result= <<SCANTRONFORM;
 7644: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7645:   <input type="hidden" name="command" value="scantron_configphase" />
 7646:   $default_form_data
 7647: SCANTRONFORM
 7648:     $r->print($result);
 7649: 
 7650:     my @delayqueue;
 7651:     my (%completedstudents,%scandata);
 7652:     
 7653:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7654:     my $count=&get_todo_count($scanlines,$scan_data);
 7655:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7656:  				    'Bubblesheet Progress',$count,
 7657: 				    'inline',undef,'scantronupload');
 7658:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7659: 					  'Processing first student');
 7660:     $r->print('<br />');
 7661:     my $start=&Time::HiRes::time();
 7662:     my $i=-1;
 7663:     my $started;
 7664: 
 7665:     my $nav_error;
 7666:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7667:     if ($nav_error) {
 7668:         $r->print(&navmap_errormsg());
 7669:         return '';
 7670:     }
 7671: 
 7672:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7673:     # the user and return.
 7674: 
 7675:     if ($ssi_error) {
 7676: 	$r->print("</form>");
 7677: 	&ssi_print_error($r);
 7678: 	$r->print(&show_grading_menu_form($symb));
 7679:         &Apache::lonnet::remove_lock($lock);
 7680: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7681:     }
 7682: 
 7683:     my %lettdig = &letter_to_digits();
 7684:     my $numletts = scalar(keys(%lettdig));
 7685: 
 7686:     while ($i<$scanlines->{'count'}) {
 7687:  	($uname,$udom)=('','');
 7688:  	$i++;
 7689:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7690:  	if ($line=~/^[\s\cz]*$/) { next; }
 7691: 	if ($started) {
 7692: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7693: 						     'last student');
 7694: 	}
 7695: 	$started=1;
 7696:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7697:  						 $scan_data);
 7698:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7699:  					      \%idmap,$i)) {
 7700:   	    &scantron_add_delay(\@delayqueue,$line,
 7701:  				'Unable to find a student that matches',1);
 7702:  	    next;
 7703:   	}
 7704:  	if (exists $completedstudents{$uname}) {
 7705:  	    &scantron_add_delay(\@delayqueue,$line,
 7706:  				'Student '.$uname.' has multiple sheets',2);
 7707:  	    next;
 7708:  	}
 7709:   	($uname,$udom)=split(/:/,$uname);
 7710: 
 7711:         my (%partids_by_symb,$res_error);
 7712:         foreach my $resource (@resources) {
 7713:             my $ressymb;
 7714:             if (ref($resource)) {
 7715:                 $ressymb = $resource->symb();
 7716:             } else {
 7717:                 $res_error = 1;
 7718:                 last;
 7719:             }
 7720:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7721:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7722:                 my ($analysis,$parts) =
 7723:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7724:                 $partids_by_symb{$ressymb} = $parts;
 7725:             } else {
 7726:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7727:             }
 7728:         }
 7729: 
 7730:         if ($res_error) {
 7731:             &scantron_add_delay(\@delayqueue,$line,
 7732:                                 'An error occurred while grading student '.$uname,2);
 7733:             next;
 7734:         }
 7735: 
 7736: 	&Apache::lonxml::clear_problem_counter();
 7737:   	&Apache::lonnet::appenv($scan_record);
 7738: 
 7739: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7740: 	    &scantron_putfile($scanlines,$scan_data);
 7741: 	}
 7742: 	
 7743:         my $scancode;
 7744:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7745:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7746:             $scancode = $scan_record->{'scantron.CODE'};
 7747:         } else {
 7748:             $scancode = '';
 7749:         }
 7750: 
 7751:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7752:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7753:             $ssi_error = 0; # So end of handler error message does not trigger.
 7754:             $r->print("</form>");
 7755:             &ssi_print_error($r);
 7756:             $r->print(&show_grading_menu_form($symb));
 7757:             &Apache::lonnet::remove_lock($lock);
 7758:             return '';      # Why return ''?  Beats me.
 7759:         }
 7760: 
 7761: 	$completedstudents{$uname}={'line'=>$line};
 7762:         if ($env{'form.verifyrecord'}) {
 7763:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7764:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7765:             chomp($studentdata);
 7766:             $studentdata =~ s/\r$//;
 7767:             my $studentrecord = '';
 7768:             my $counter = -1;
 7769:             foreach my $resource (@resources) {
 7770:                 my $ressymb = $resource->symb();
 7771:                 ($counter,my $recording) =
 7772:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7773:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7774:                                              \%scantron_config,\%lettdig,$numletts);
 7775:                 $studentrecord .= $recording;
 7776:             }
 7777:             if ($studentrecord ne $studentdata) {
 7778:                 &Apache::lonxml::clear_problem_counter();
 7779:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7780:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7781:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7782:                     $r->print("</form>");
 7783:                     &ssi_print_error($r);
 7784:                     $r->print(&show_grading_menu_form($symb));
 7785:                     &Apache::lonnet::remove_lock($lock);
 7786:                     delete($completedstudents{$uname});
 7787:                     return '';
 7788:                 }
 7789:                 $counter = -1;
 7790:                 $studentrecord = '';
 7791:                 foreach my $resource (@resources) {
 7792:                     my $ressymb = $resource->symb();
 7793:                     ($counter,my $recording) =
 7794:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7795:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7796:                                                  \%scantron_config,\%lettdig,$numletts);
 7797:                     $studentrecord .= $recording;
 7798:                 }
 7799:                 if ($studentrecord ne $studentdata) {
 7800:                     $r->print('<p><span class="LC_error">');
 7801:                     if ($scancode eq '') {
 7802:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7803:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7804:                     } else {
 7805:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7806:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7807:                     }
 7808:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7809:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7810:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7811:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7812:                               &Apache::loncommon::start_data_table_row().
 7813:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7814:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7815:                               &Apache::loncommon::end_data_table_row().
 7816:                               &Apache::loncommon::start_data_table_row().
 7817:                               '<td>Stored submissions</td>'.
 7818:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7819:                               &Apache::loncommon::end_data_table_row().
 7820:                               &Apache::loncommon::end_data_table().'</p>');
 7821:                 } else {
 7822:                     $r->print('<br /><span class="LC_warning">'.
 7823:                              &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 />'.
 7824:                              &mt("As a consequence, this user's submission history records two tries.").
 7825:                                  '</span><br />');
 7826:                 }
 7827:             }
 7828:         }
 7829:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7830:     } continue {
 7831: 	&Apache::lonxml::clear_problem_counter();
 7832: 	&Apache::lonnet::delenv('scantron.');
 7833:     }
 7834:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7835:     &Apache::lonnet::remove_lock($lock);
 7836: #    my $lasttime = &Time::HiRes::time()-$start;
 7837: #    $r->print("<p>took $lasttime</p>");
 7838: 
 7839:     $r->print("</form>");
 7840:     $r->print(&show_grading_menu_form($symb));
 7841:     return '';
 7842: }
 7843: 
 7844: sub graders_resources_pass {
 7845:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7846:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7847:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7848:         foreach my $resource (@{$resources}) {
 7849:             my $ressymb = $resource->symb();
 7850:             my ($analysis,$parts) =
 7851:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7852:                                           $env{'user.name'},$env{'user.domain'},1);
 7853:             $grader_partids_by_symb->{$ressymb} = $parts;
 7854:             if (ref($analysis) eq 'HASH') {
 7855:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7856:                     $grader_randomlists_by_symb->{$ressymb} =
 7857:                         $analysis->{'parts_withrandomlist'};
 7858:                 }
 7859:             }
 7860:         }
 7861:     }
 7862:     return;
 7863: }
 7864: 
 7865: sub grade_student_bubbles {
 7866:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7867:     if (ref($resources) eq 'ARRAY') {
 7868:         my $count = 0;
 7869:         foreach my $resource (@{$resources}) {
 7870:             my $ressymb = $resource->symb();
 7871:             my %form = ('submitted'      => 'scantron',
 7872:                         'grade_target'   => 'grade',
 7873:                         'grade_username' => $uname,
 7874:                         'grade_domain'   => $udom,
 7875:                         'grade_courseid' => $env{'request.course.id'},
 7876:                         'grade_symb'     => $ressymb,
 7877:                         'CODE'           => $scancode
 7878:                        );
 7879:             if (ref($parts) eq 'HASH') {
 7880:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7881:                     foreach my $part (@{$parts->{$ressymb}}) {
 7882:                         $form{'scantron_questnum_start.'.$part} =
 7883:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7884:                         $count++;
 7885:                     }
 7886:                 }
 7887:             }
 7888:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7889:             return 'ssi_error' if ($ssi_error);
 7890:             last if (&Apache::loncommon::connection_aborted($r));
 7891:         }
 7892:     }
 7893:     return;
 7894: }
 7895: 
 7896: sub scantron_upload_scantron_data {
 7897:     my ($r)=@_;
 7898:     my $dom = $env{'request.role.domain'};
 7899:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7900:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7901:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7902: 							  'domainid',
 7903: 							  'coursename',$dom);
 7904:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7905:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7906:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7907:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7908:     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.");
 7909:     $r->print('
 7910: <script type="text/javascript" language="javascript">
 7911:     function checkUpload(formname) {
 7912: 	if (formname.upfile.value == "") {
 7913: 	    alert("'.$nofile_alert.'");
 7914: 	    return false;
 7915: 	}
 7916:         if (formname.courseid.value == "") {
 7917:             alert("'.$nocourseid_alert.'");
 7918:             return false;
 7919:         }
 7920: 	formname.submit();
 7921:     }
 7922: 
 7923:     function ToSyllabus() {
 7924:         var cdom = '."'$dom'".';
 7925:         var cnum = document.rules.courseid.value;
 7926:         if (cdom == "" || cdom == null) {
 7927:             return;
 7928:         }
 7929:         if (cnum == "" || cnum == null) {
 7930:            return;
 7931:         }
 7932:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7933:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7934:         return;
 7935:     }
 7936: 
 7937: </script>
 7938: 
 7939: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7940: 
 7941: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7942: '.$default_form_data.
 7943:   &Apache::lonhtmlcommon::start_pick_box().
 7944:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7945:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7946:   &Apache::lonhtmlcommon::row_closure().
 7947:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7948:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7949:   &Apache::lonhtmlcommon::row_closure().
 7950:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7951:   '<input name="domainid" type="hidden" />'.$domdesc.
 7952:   &Apache::lonhtmlcommon::row_closure().
 7953:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7954:   '<input type="file" name="upfile" size="50" />'.
 7955:   &Apache::lonhtmlcommon::row_closure(1).
 7956:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7957: 
 7958: <input name="command" value="scantronupload_save" type="hidden" />
 7959: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7960: </form>
 7961: ');
 7962:     return '';
 7963: }
 7964: 
 7965: 
 7966: sub scantron_upload_scantron_data_save {
 7967:     my($r)=@_;
 7968:     my ($symb)=&get_symb($r,1);
 7969:     my $doanotherupload=
 7970: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7971: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7972: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7973: 	'</form>'."\n";
 7974:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7975: 	!&Apache::lonnet::allowed('usc',
 7976: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7977: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7978: 	if ($symb) {
 7979: 	    $r->print(&show_grading_menu_form($symb));
 7980: 	} else {
 7981: 	    $r->print($doanotherupload);
 7982: 	}
 7983: 	return '';
 7984:     }
 7985:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7986:     my $uploadedfile;
 7987:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7988:     if (length($env{'form.upfile'}) < 2) {
 7989:         $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>'));
 7990:     } else {
 7991:         my $result = 
 7992:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7993:                                             $env{'form.courseid'},$env{'form.domainid'});
 7994: 	if ($result =~ m{^/uploaded/}) {
 7995: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7996:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7997: 			  '<span class="LC_filename">'.$result.'</span>'));
 7998:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7999:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 8000:                                                        $env{'form.courseid'},$uploadedfile));
 8001: 	} else {
 8002: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 8003:                           '<span class="LC_error">','</span>',$result,
 8004: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 8005: 	}
 8006:     }
 8007:     if ($symb) {
 8008: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 8009:     } else {
 8010: 	$r->print($doanotherupload);
 8011:     }
 8012:     return '';
 8013: }
 8014: 
 8015: sub validate_uploaded_scantron_file {
 8016:     my ($cdom,$cname,$fname) = @_;
 8017:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8018:     my @lines;
 8019:     if ($scanlines ne '-1') {
 8020:         @lines=split("\n",$scanlines,-1);
 8021:     }
 8022:     my $output;
 8023:     if (@lines) {
 8024:         my (%counts,$max_match_format);
 8025:         my ($max_match_count,$max_match_pct) = (0,0);
 8026:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8027:         my %idmap = &username_to_idmap($classlist);
 8028:         foreach my $key (keys(%idmap)) {
 8029:             my $lckey = lc($key);
 8030:             $idmap{$lckey} = $idmap{$key};
 8031:         }
 8032:         my %unique_formats;
 8033:         my @formatlines = &get_scantronformat_file();
 8034:         foreach my $line (@formatlines) {
 8035:             chomp($line);
 8036:             my @config = split(/:/,$line);
 8037:             my $idstart = $config[5];
 8038:             my $idlength = $config[6];
 8039:             if (($idstart ne '') && ($idlength > 0)) {
 8040:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8041:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8042:                 } else {
 8043:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8044:                 }
 8045:             }
 8046:         }
 8047:         foreach my $key (keys(%unique_formats)) {
 8048:             my ($idstart,$idlength) = split(':',$key);
 8049:             %{$counts{$key}} = (
 8050:                                'found'   => 0,
 8051:                                'total'   => 0,
 8052:                               );
 8053:             foreach my $line (@lines) {
 8054:                 next if ($line =~ /^#/);
 8055:                 next if ($line =~ /^[\s\cz]*$/);
 8056:                 my $id = substr($line,$idstart-1,$idlength);
 8057:                 $id = lc($id);
 8058:                 if (exists($idmap{$id})) {
 8059:                     $counts{$key}{'found'} ++;
 8060:                 }
 8061:                 $counts{$key}{'total'} ++;
 8062:             }
 8063:             if ($counts{$key}{'total'}) {
 8064:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8065:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8066:                     $max_match_pct = $percent_match;
 8067:                     $max_match_format = $key;
 8068:                     $max_match_count = $counts{$key}{'total'};
 8069:                 }
 8070:             }
 8071:         }
 8072:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8073:             my $format_descs;
 8074:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8075:             for (my $i=0; $i<$numwithformat; $i++) {
 8076:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8077:                 if ($i<$numwithformat-2) {
 8078:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8079:                 } elsif ($i==$numwithformat-2) {
 8080:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8081:                 } elsif ($i==$numwithformat-1) {
 8082:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8083:                 }
 8084:             }
 8085:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8086:             $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).
 8087:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8088:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8089:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8090:                                   '<i>'.$cdom.'</i>').'</li>'.
 8091:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8092:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8093:                        '</ul>';
 8094:         }
 8095:     } else {
 8096:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8097:     }
 8098:     return $output;
 8099: }
 8100: 
 8101: sub valid_file {
 8102:     my ($requested_file)=@_;
 8103:     foreach my $filename (sort(&scantron_filenames())) {
 8104: 	if ($requested_file eq $filename) { return 1; }
 8105:     }
 8106:     return 0;
 8107: }
 8108: 
 8109: sub scantron_download_scantron_data {
 8110:     my ($r)=@_;
 8111:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8112:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8113:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8114:     my $file=$env{'form.scantron_selectfile'};
 8115:     if (! &valid_file($file)) {
 8116: 	$r->print('
 8117: 	<p>
 8118: 	    '.&mt('The requested file name was invalid.').'
 8119:         </p>
 8120: ');
 8121: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8122: 	return;
 8123:     }
 8124:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8125:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8126:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8127:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8128:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8129:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8130:     $r->print('
 8131:     <p>
 8132: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8133: 	      '<a href="'.$orig.'">','</a>').'
 8134:     </p>
 8135:     <p>
 8136: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8137: 	      '<a href="'.$corrected.'">','</a>').'
 8138:     </p>
 8139:     <p>
 8140: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8141: 	      '<a href="'.$skipped.'">','</a>').'
 8142:     </p>
 8143: ');
 8144:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8145:     return '';
 8146: }
 8147: 
 8148: sub checkscantron_results {
 8149:     my ($r) = @_;
 8150:     my ($symb)=&get_symb($r);
 8151:     if (!$symb) {return '';}
 8152:     my $grading_menu_button=&show_grading_menu_form($symb);
 8153:     my $cid = $env{'request.course.id'};
 8154:     my %lettdig = &letter_to_digits();
 8155:     my $numletts = scalar(keys(%lettdig));
 8156:     my $cnum = $env{'course.'.$cid.'.num'};
 8157:     my $cdom = $env{'course.'.$cid.'.domain'};
 8158:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8159:     my %record;
 8160:     my %scantron_config =
 8161:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8162:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8163:     my $classlist=&Apache::loncoursedata::get_classlist();
 8164:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8165:     my $navmap=Apache::lonnavmaps::navmap->new();
 8166:     unless (ref($navmap)) {
 8167:         $r->print(&navmap_errormsg());
 8168:         return '';
 8169:     }
 8170:     my $map=$navmap->getResourceByUrl($sequence);
 8171:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8172:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8173:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8174: 
 8175:     my ($uname,$udom);
 8176:     my (%scandata,%lastname,%bylast);
 8177:     $r->print('
 8178: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8179: 
 8180:     my @delayqueue;
 8181:     my %completedstudents;
 8182: 
 8183:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8184:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8185:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8186:                                     'inline',undef,'checkscantron');
 8187:     my ($username,$domain,$started);
 8188:     my $nav_error;
 8189:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8190:     if ($nav_error) {
 8191:         $r->print(&navmap_errormsg());
 8192:         return '';
 8193:     }
 8194: 
 8195:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8196:                                           'Processing first student');
 8197:     my $start=&Time::HiRes::time();
 8198:     my $i=-1;
 8199: 
 8200:     while ($i<$scanlines->{'count'}) {
 8201:         ($username,$domain,$uname)=('','','');
 8202:         $i++;
 8203:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8204:         if ($line=~/^[\s\cz]*$/) { next; }
 8205:         if ($started) {
 8206:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8207:                                                      'last student');
 8208:         }
 8209:         $started=1;
 8210:         my $scan_record=
 8211:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8212:                                                      $scan_data);
 8213:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8214:                                                               \%idmap,$i)) {
 8215:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8216:                                 'Unable to find a student that matches',1);
 8217:             next;
 8218:         }
 8219:         if (exists $completedstudents{$uname}) {
 8220:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8221:                                 'Student '.$uname.' has multiple sheets',2);
 8222:             next;
 8223:         }
 8224:         my $pid = $scan_record->{'scantron.ID'};
 8225:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8226:         push(@{$bylast{$lastname{$pid}}},$pid);
 8227:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8228:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8229:         chomp($scandata{$pid});
 8230:         $scandata{$pid} =~ s/\r$//;
 8231:         ($username,$domain)=split(/:/,$uname);
 8232:         my $counter = -1;
 8233:         foreach my $resource (@resources) {
 8234:             my $parts;
 8235:             my $ressymb = $resource->symb();
 8236:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8237:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8238:                 (my $analysis,$parts) =
 8239:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8240:             } else {
 8241:                 $parts = $grader_partids_by_symb{$ressymb};
 8242:             }
 8243:             ($counter,my $recording) =
 8244:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8245:                                          $scandata{$pid},$parts,
 8246:                                          \%scantron_config,\%lettdig,$numletts);
 8247:             $record{$pid} .= $recording;
 8248:         }
 8249:     }
 8250:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8251:     $r->print('<br />');
 8252:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8253:     $passed = 0;
 8254:     $failed = 0;
 8255:     $numstudents = 0;
 8256:     foreach my $last (sort(keys(%bylast))) {
 8257:         if (ref($bylast{$last}) eq 'ARRAY') {
 8258:             foreach my $pid (sort(@{$bylast{$last}})) {
 8259:                 my $showscandata = $scandata{$pid};
 8260:                 my $showrecord = $record{$pid};
 8261:                 $showscandata =~ s/\s/&nbsp;/g;
 8262:                 $showrecord =~ s/\s/&nbsp;/g;
 8263:                 if ($scandata{$pid} eq $record{$pid}) {
 8264:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8265:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8266: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8267: '</tr>'."\n".
 8268: '<tr class="'.$css_class.'">'."\n".
 8269: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8270:                     $passed ++;
 8271:                 } else {
 8272:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8273:                     $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".
 8274: '</tr>'."\n".
 8275: '<tr class="'.$css_class.'">'."\n".
 8276: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8277: '</tr>'."\n";
 8278:                     $failed ++;
 8279:                 }
 8280:                 $numstudents ++;
 8281:             }
 8282:         }
 8283:     }
 8284:     $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>');
 8285:     $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>');
 8286:     if ($passed) {
 8287:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8288:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8289:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8290:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8291:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8292:                  $okstudents."\n".
 8293:                  &Apache::loncommon::end_data_table().'<br />');
 8294:     }
 8295:     if ($failed) {
 8296:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8297:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8298:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8299:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8300:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8301:                  $badstudents."\n".
 8302:                  &Apache::loncommon::end_data_table()).'<br />'.
 8303:                  &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.');  
 8304:     }
 8305:     $r->print('</form><br />'.$grading_menu_button);
 8306:     return;
 8307: }
 8308: 
 8309: sub verify_scantron_grading {
 8310:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8311:         $scantron_config,$lettdig,$numletts) = @_;
 8312:     my ($record,%expected,%startpos);
 8313:     return ($counter,$record) if (!ref($resource));
 8314:     return ($counter,$record) if (!$resource->is_problem());
 8315:     my $symb = $resource->symb();
 8316:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8317:     foreach my $part_id (@{$partids}) {
 8318:         $counter ++;
 8319:         $expected{$part_id} = 0;
 8320:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8321:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8322:             foreach my $item (@sub_lines) {
 8323:                 $expected{$part_id} += $item;
 8324:             }
 8325:         } else {
 8326:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8327:         }
 8328:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8329:     }
 8330:     if ($symb) {
 8331:         my %recorded;
 8332:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8333:         if ($returnhash{'version'}) {
 8334:             my %lasthash=();
 8335:             my $version;
 8336:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8337:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8338:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8339:                 }
 8340:             }
 8341:             foreach my $key (keys(%lasthash)) {
 8342:                 if ($key =~ /\.scantron$/) {
 8343:                     my $value = &unescape($lasthash{$key});
 8344:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8345:                     if ($value eq '') {
 8346:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8347:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8348:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8349:                             }
 8350:                         }
 8351:                     } else {
 8352:                         my @tocheck;
 8353:                         my @items = split(//,$value);
 8354:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8355:                             ($scantron_config->{'Qon'} eq 'number')) {
 8356:                             if (@items < $expected{$part_id}) {
 8357:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8358:                                 my @singles = split(//,$fragment);
 8359:                                 foreach my $pos (@singles) {
 8360:                                     if ($pos eq ' ') {
 8361:                                         push(@tocheck,$pos);
 8362:                                     } else {
 8363:                                         my $next = shift(@items);
 8364:                                         push(@tocheck,$next);
 8365:                                     }
 8366:                                 }
 8367:                             } else {
 8368:                                 @tocheck = @items;
 8369:                             }
 8370:                             foreach my $letter (@tocheck) {
 8371:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8372:                                     if ($letter !~ /^[A-J]$/) {
 8373:                                         $letter = $scantron_config->{'Qoff'};
 8374:                                     }
 8375:                                     $recorded{$part_id} .= $letter;
 8376:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8377:                                     my $digit;
 8378:                                     if ($letter !~ /^[A-J]$/) {
 8379:                                         $digit = $scantron_config->{'Qoff'};
 8380:                                     } else {
 8381:                                         $digit = $lettdig->{$letter};
 8382:                                     }
 8383:                                     $recorded{$part_id} .= $digit;
 8384:                                 }
 8385:                             }
 8386:                         } else {
 8387:                             @tocheck = @items;
 8388:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8389:                                 my $curr_sub = shift(@tocheck);
 8390:                                 my $digit;
 8391:                                 if ($curr_sub =~ /^[A-J]$/) {
 8392:                                     $digit = $lettdig->{$curr_sub}-1;
 8393:                                 }
 8394:                                 if ($curr_sub eq 'J') {
 8395:                                     $digit += scalar($numletts);
 8396:                                 }
 8397:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8398:                                     if ($j == $digit) {
 8399:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8400:                                     } else {
 8401:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8402:                                     }
 8403:                                 }
 8404:                             }
 8405:                         }
 8406:                     }
 8407:                 }
 8408:             }
 8409:         }
 8410:         foreach my $part_id (@{$partids}) {
 8411:             if ($recorded{$part_id} eq '') {
 8412:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8413:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8414:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8415:                     }
 8416:                 }
 8417:             }
 8418:             $record .= $recorded{$part_id};
 8419:         }
 8420:     }
 8421:     return ($counter,$record);
 8422: }
 8423: 
 8424: sub letter_to_digits { 
 8425:     my %lettdig = (
 8426:                     A => 1,
 8427:                     B => 2,
 8428:                     C => 3,
 8429:                     D => 4,
 8430:                     E => 5,
 8431:                     F => 6,
 8432:                     G => 7,
 8433:                     H => 8,
 8434:                     I => 9,
 8435:                     J => 0,
 8436:                   );
 8437:     return %lettdig;
 8438: }
 8439: 
 8440: 
 8441: #-------- end of section for handling grading scantron forms -------
 8442: #
 8443: #-------------------------------------------------------------------
 8444: 
 8445: #-------------------------- Menu interface -------------------------
 8446: #
 8447: #--- Show a Grading Menu button - Calls the next routine ---
 8448: sub show_grading_menu_form {
 8449:     my ($symb)=@_;
 8450:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8451: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8452: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8453: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8454: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8455: 	'</form>'."\n";
 8456:     return $result;
 8457: }
 8458: 
 8459: # -- Retrieve choices for grading form
 8460: sub savedState {
 8461:     my %savedState = ();
 8462:     if ($env{'form.saveState'}) {
 8463: 	foreach (split(/:/,$env{'form.saveState'})) {
 8464: 	    my ($key,$value) = split(/=/,$_,2);
 8465: 	    $savedState{$key} = $value;
 8466: 	}
 8467:     }
 8468:     return \%savedState;
 8469: }
 8470: 
 8471: sub grading_menu {
 8472:     my ($request) = @_;
 8473:     my ($symb)=&get_symb($request);
 8474:     if (!$symb) {return '';}
 8475:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8476:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8477: 
 8478:     $request->print($table);
 8479:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8480:                   'handgrade'=>$hdgrade,
 8481:                   'probTitle'=>$probTitle,
 8482:                   'command'=>'submit_options',
 8483:                   'saveState'=>"",
 8484:                   'gradingMenu'=>1,
 8485:                   'showgrading'=>"yes");
 8486:     
 8487:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8488:     
 8489:     $fields{'command'} = 'csvform';
 8490:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8491:     
 8492:     $fields{'command'} = 'processclicker';
 8493:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8494:     
 8495:     $fields{'command'} = 'scantron_selectphase';
 8496:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8497:     
 8498:     my @menu = ({	categorytitle=>'Course Grading',
 8499:             items =>[
 8500:                         {	linktext => 'Manual Grading/View Submissions',
 8501:                     		url => $url1,
 8502:                     		permission => 'F',
 8503:                     		icon => 'edit-find-replace.png',
 8504:                     		linktitle => 'Start the process of hand grading submissions.'
 8505:                         },
 8506:                 	    {	linktext => 'Upload Scores',
 8507:                     		url => $url2,
 8508:                     		permission => 'F',
 8509:                     		icon => 'uploadscores.png',
 8510:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8511:                 	    },
 8512:                 	    {	linktext => 'Process Clicker',
 8513:                     		url => $url3,
 8514:                     		permission => 'F',
 8515:                     		icon => 'addClickerInfoFile.png',
 8516:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8517:                 	    },
 8518:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
 8519:                     		url => $url4,
 8520:                     		permission => 'F',
 8521:                     		icon => 'stat.png',
 8522:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8523:                 	    }
 8524:                     ]
 8525:             });
 8526: 
 8527:     #$fields{'command'} = 'verify';
 8528:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8529:     #
 8530:     # Create the menu
 8531:     my $Str;
 8532:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8533:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8534:     $Str .= '<input type="hidden" name="command" value="" />'.
 8535:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8536: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8537: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8538: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8539: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8540: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8541: 
 8542:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8543:     #$menudata->{'jscript'}
 8544:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8545:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8546:         ' /> '.
 8547:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8548:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8549: 
 8550:     $Str .="</form>\n";
 8551:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8552:     $request->print(<<GRADINGMENUJS);
 8553: <script type="text/javascript" language="javascript">
 8554:     function checkChoice(formname,val,cmdx) {
 8555: 	if (val <= 2) {
 8556: 	    var cmd = radioSelection(formname.radioChoice);
 8557: 	    var cmdsave = cmd;
 8558: 	} else {
 8559: 	    cmd = cmdx;
 8560: 	    cmdsave = 'submission';
 8561: 	}
 8562: 	formname.command.value = cmd;
 8563: 	if (val < 5) formname.submit();
 8564: 	if (val == 5) {
 8565: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8566: 	        return false;
 8567: 	    } else {
 8568: 	        formname.submit();
 8569: 	    }
 8570: 	}
 8571:     }
 8572: 
 8573:     function checkReceiptNo(formname,nospace) {
 8574: 	var receiptNo = formname.receipt.value;
 8575: 	var checkOpt = false;
 8576: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8577: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8578: 	if (checkOpt) {
 8579: 	    alert("$receiptalert");
 8580: 	    formname.receipt.value = "";
 8581: 	    formname.receipt.focus();
 8582: 	    return false;
 8583: 	}
 8584: 	return true;
 8585:     }
 8586: </script>
 8587: GRADINGMENUJS
 8588:     &commonJSfunctions($request);
 8589:     return $Str;    
 8590: }
 8591: 
 8592: 
 8593: #--- Displays the submissions first page -------
 8594: sub submit_options {
 8595:     my ($request) = @_;
 8596:     my ($symb)=&get_symb($request);
 8597:     if (!$symb) {return '';}
 8598:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8599: 
 8600:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8601:     $request->print(<<GRADINGMENUJS);
 8602: <script type="text/javascript" language="javascript">
 8603:     function checkChoice(formname,val,cmdx) {
 8604: 	if (val <= 2) {
 8605: 	    var cmd = radioSelection(formname.radioChoice);
 8606: 	    var cmdsave = cmd;
 8607: 	} else {
 8608: 	    cmd = cmdx;
 8609: 	    cmdsave = 'submission';
 8610: 	}
 8611: 	formname.command.value = cmd;
 8612: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8613: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8614: 	if (val < 5) formname.submit();
 8615: 	if (val == 5) {
 8616: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8617: 	    formname.submit();
 8618: 	}
 8619: 	if (val < 7) formname.submit();
 8620:     }
 8621: 
 8622:     function checkReceiptNo(formname,nospace) {
 8623: 	var receiptNo = formname.receipt.value;
 8624: 	var checkOpt = false;
 8625: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8626: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8627: 	if (checkOpt) {
 8628: 	    alert("$receiptalert");
 8629: 	    formname.receipt.value = "";
 8630: 	    formname.receipt.focus();
 8631: 	    return false;
 8632: 	}
 8633: 	return true;
 8634:     }
 8635: </script>
 8636: GRADINGMENUJS
 8637:     &commonJSfunctions($request);
 8638:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8639:     my $result;
 8640:     my (undef,$sections) = &getclasslist('all','0');
 8641:     my $savedState = &savedState();
 8642:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8643:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8644:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8645:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8646: 
 8647:     # Preselect sections
 8648:     my $selsec="";
 8649:     if (ref($sections)) {
 8650:         foreach my $section (sort(@$sections)) {
 8651:             $selsec.='<option value="'.$section.'" '.
 8652:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8653:         }
 8654:     }
 8655: 
 8656:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8657: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8658: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8659: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8660: 	'<input type="hidden" name="command"     value="" />'."\n".
 8661: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8662: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8663: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8664: 
 8665:     $result.='
 8666: <h2>
 8667:   '.&mt('Grade Current Resource').'
 8668: </h2>
 8669: <div>
 8670:   '.$table.'
 8671: </div>
 8672: 
 8673: <div class="LC_columnSection">
 8674:   
 8675:     <fieldset>
 8676:       <legend>
 8677:        '.&mt('Sections').'
 8678:       </legend>
 8679:       <select name="section" multiple="multiple" size="5">'."\n";
 8680:     $result.= $selsec;
 8681:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8682:     $result.='
 8683:     </fieldset>
 8684:   
 8685:     <fieldset>
 8686:       <legend>
 8687:         '.&mt('Groups').'
 8688:       </legend>
 8689:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8690:     </fieldset>
 8691:   
 8692:     <fieldset>
 8693:       <legend>
 8694:         '.&mt('Access Status').'
 8695:       </legend>
 8696:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8697:     </fieldset>
 8698:   
 8699:     <fieldset>
 8700:       <legend>
 8701:         '.&mt('Submission Status').'
 8702:       </legend>
 8703:       <select name="submitonly" size="5">
 8704: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8705: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8706: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8707: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8708:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8709:       </select>
 8710:     </fieldset>
 8711:   
 8712: </div>
 8713: 
 8714: <br />
 8715:           <div>
 8716:             <div>
 8717:               <label>
 8718:                 <input type="radio" name="radioChoice" value="submission" '.
 8719:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8720:              &mt('Select individual students to grade and view submissions.').'
 8721: 	      </label> 
 8722:             </div>
 8723:             <div>
 8724: 	      <label>
 8725:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8726:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8727:                     &mt('Grade all selected students in a grading table.').'
 8728:               </label>
 8729:             </div>
 8730:             <div>
 8731: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8732:             </div>
 8733:           </div>
 8734: 
 8735: 
 8736:         <h2>
 8737:          '.&mt('Grade Complete Folder for One Student').'
 8738:         </h2>
 8739:         <div>
 8740:             <div>
 8741:               <label>
 8742:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8743: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8744:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8745:               </label>
 8746:             </div>
 8747:             <div>
 8748: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8749:             </div>
 8750:         </div>
 8751:   </form>';
 8752:     $result .= &show_grading_menu_form($symb);
 8753:     return $result;
 8754: }
 8755: 
 8756: sub reset_perm {
 8757:     undef(%perm);
 8758: }
 8759: 
 8760: sub init_perm {
 8761:     &reset_perm();
 8762:     foreach my $test_perm ('vgr','mgr','opa') {
 8763: 
 8764: 	my $scope = $env{'request.course.id'};
 8765: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8766: 
 8767: 	    $scope .= '/'.$env{'request.course.sec'};
 8768: 	    if ( $perm{$test_perm}=
 8769: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8770: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8771: 	    } else {
 8772: 		delete($perm{$test_perm});
 8773: 	    }
 8774: 	}
 8775:     }
 8776: }
 8777: 
 8778: sub gather_clicker_ids {
 8779:     my %clicker_ids;
 8780: 
 8781:     my $classlist = &Apache::loncoursedata::get_classlist();
 8782: 
 8783:     # Set up a couple variables.
 8784:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8785:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8786:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8787: 
 8788:     foreach my $student (keys(%$classlist)) {
 8789:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8790:         my $username = $classlist->{$student}->[$username_idx];
 8791:         my $domain   = $classlist->{$student}->[$domain_idx];
 8792:         my $clickers =
 8793: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8794:         foreach my $id (split(/\,/,$clickers)) {
 8795:             $id=~s/^[\#0]+//;
 8796:             $id=~s/[\-\:]//g;
 8797:             if (exists($clicker_ids{$id})) {
 8798: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8799:             } else {
 8800: 		$clicker_ids{$id}=$username.':'.$domain;
 8801:             }
 8802:         }
 8803:     }
 8804:     return %clicker_ids;
 8805: }
 8806: 
 8807: sub gather_adv_clicker_ids {
 8808:     my %clicker_ids;
 8809:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8810:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8811:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8812:     foreach my $element (sort(keys(%coursepersonnel))) {
 8813:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8814:             my ($puname,$pudom)=split(/\:/,$person);
 8815:             my $clickers =
 8816: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8817:             foreach my $id (split(/\,/,$clickers)) {
 8818: 		$id=~s/^[\#0]+//;
 8819:                 $id=~s/[\-\:]//g;
 8820: 		if (exists($clicker_ids{$id})) {
 8821: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8822: 		} else {
 8823: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8824: 		}
 8825:             }
 8826:         }
 8827:     }
 8828:     return %clicker_ids;
 8829: }
 8830: 
 8831: sub clicker_grading_parameters {
 8832:     return ('gradingmechanism' => 'scalar',
 8833:             'upfiletype' => 'scalar',
 8834:             'specificid' => 'scalar',
 8835:             'pcorrect' => 'scalar',
 8836:             'pincorrect' => 'scalar');
 8837: }
 8838: 
 8839: sub process_clicker {
 8840:     my ($r)=@_;
 8841:     my ($symb)=&get_symb($r);
 8842:     if (!$symb) {return '';}
 8843:     my $result=&checkforfile_js();
 8844:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8845:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8846:     $result.=$table;
 8847:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8848:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8849:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8850:         '</b></td></tr>'."\n";
 8851:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8852: # Attempt to restore parameters from last session, set defaults if not present
 8853:     my %Saveable_Parameters=&clicker_grading_parameters();
 8854:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8855:                                                  \%Saveable_Parameters);
 8856:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8857:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8858:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8859:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8860: 
 8861:     my %checked;
 8862:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8863:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8864:           $checked{$gradingmechanism}=' checked="checked"';
 8865:        }
 8866:     }
 8867: 
 8868:     my $upload=&mt("Upload File");
 8869:     my $type=&mt("Type");
 8870:     my $attendance=&mt("Award points just for participation");
 8871:     my $personnel=&mt("Correctness determined from response by course personnel");
 8872:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8873:     my $given=&mt("Correctness determined from given list of answers").' '.
 8874:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8875:     my $pcorrect=&mt("Percentage points for correct solution");
 8876:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8877:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8878: 						   ('iclicker' => 'i>clicker',
 8879:                                                     'interwrite' => 'interwrite PRS'));
 8880:     $symb = &Apache::lonenc::check_encrypt($symb);
 8881:     $result.=<<ENDUPFORM;
 8882: <script type="text/javascript">
 8883: function sanitycheck() {
 8884: // Accept only integer percentages
 8885:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8886:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8887: // Find out grading choice
 8888:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8889:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8890:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8891:       }
 8892:    }
 8893: // By default, new choice equals user selection
 8894:    newgradingchoice=gradingchoice;
 8895: // Not good to give more points for false answers than correct ones
 8896:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8897:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8898:    }
 8899: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8900:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8901:       document.forms.gradesupload.pcorrect.value=100;
 8902:       document.forms.gradesupload.pincorrect.value=100;
 8903:    }
 8904: // If the values are different, cannot be attendance only
 8905:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8906:        (gradingchoice=='attendance')) {
 8907:        newgradingchoice='personnel';
 8908:    }
 8909: // Change grading choice to new one
 8910:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8911:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8912:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8913:       } else {
 8914:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8915:       }
 8916:    }
 8917: // Remember the old state
 8918:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8919: }
 8920: </script>
 8921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8922: <input type="hidden" name="symb" value="$symb" />
 8923: <input type="hidden" name="command" value="processclickerfile" />
 8924: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8925: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8926: <input type="file" name="upfile" size="50" />
 8927: <br /><label>$type: $selectform</label>
 8928: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8929: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8930: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8931: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8932: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8933: <br />&nbsp;&nbsp;&nbsp;
 8934: <input type="text" name="givenanswer" size="50" />
 8935: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8936: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8937: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8938: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8939: </form>
 8940: ENDUPFORM
 8941:     $result.='</td></tr></table>'."\n".
 8942:              '</td></tr></table><br /><br />'."\n";
 8943:     $result.=&show_grading_menu_form($symb);
 8944:     return $result;
 8945: }
 8946: 
 8947: sub process_clicker_file {
 8948:     my ($r)=@_;
 8949:     my ($symb)=&get_symb($r);
 8950:     if (!$symb) {return '';}
 8951: 
 8952:     my %Saveable_Parameters=&clicker_grading_parameters();
 8953:     &Apache::loncommon::store_course_settings('grades_clicker',
 8954:                                               \%Saveable_Parameters);
 8955: 
 8956:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8957:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8958: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8959: 	return $result.&show_grading_menu_form($symb);
 8960:     }
 8961:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8962:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8963:         return $result.&show_grading_menu_form($symb);
 8964:     }
 8965:     my $foundgiven=0;
 8966:     if ($env{'form.gradingmechanism'} eq 'given') {
 8967:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8968:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8969:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8970:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8971:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8972:         $foundgiven=$#answers+1;
 8973:     }
 8974:     my %clicker_ids=&gather_clicker_ids();
 8975:     my %correct_ids;
 8976:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8977: 	%correct_ids=&gather_adv_clicker_ids();
 8978:     }
 8979:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8980: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8981: 	   $correct_id=~tr/a-z/A-Z/;
 8982: 	   $correct_id=~s/\s//gs;
 8983: 	   $correct_id=~s/^[\#0]+//;
 8984:            $correct_id=~s/[\-\:]//g;
 8985:            if ($correct_id) {
 8986: 	      $correct_ids{$correct_id}='specified';
 8987:            }
 8988:         }
 8989:     }
 8990:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8991: 	$result.=&mt('Score based on attendance only');
 8992:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8993:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8994:     } else {
 8995: 	my $number=0;
 8996: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8997: 	foreach my $id (sort(keys(%correct_ids))) {
 8998: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8999: 	    if ($correct_ids{$id} eq 'specified') {
 9000: 		$result.=&mt('specified');
 9001: 	    } else {
 9002: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 9003: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 9004: 	    }
 9005: 	    $number++;
 9006: 	}
 9007:         $result.="</p>\n";
 9008: 	if ($number==0) {
 9009: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 9010: 	    return $result.&show_grading_menu_form($symb);
 9011: 	}
 9012:     }
 9013:     if (length($env{'form.upfile'}) < 2) {
 9014:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 9015: 		     '<span class="LC_error">',
 9016: 		     '</span>',
 9017: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9018:         return $result.&show_grading_menu_form($symb);
 9019:     }
 9020: 
 9021: # Were able to get all the info needed, now analyze the file
 9022: 
 9023:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9024:     $symb = &Apache::lonenc::check_encrypt($symb);
 9025:     my $heading=&mt('Scanning clicker file');
 9026:     $result.=(<<ENDHEADER);
 9027: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9028: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9029: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9030: <form method="post" action="/adm/grades" name="clickeranalysis">
 9031: <input type="hidden" name="symb" value="$symb" />
 9032: <input type="hidden" name="command" value="assignclickergrades" />
 9033: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9034: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9035: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9036: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9037: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9038: ENDHEADER
 9039:     if ($env{'form.gradingmechanism'} eq 'given') {
 9040:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9041:     } 
 9042:     my %responses;
 9043:     my @questiontitles;
 9044:     my $errormsg='';
 9045:     my $number=0;
 9046:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9047: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9048:     }
 9049:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9050:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9051:     }
 9052:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9053:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9054:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9055:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9056:              '<br />';
 9057:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9058:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9059:        return $result.&show_grading_menu_form($symb);
 9060:     } 
 9061: # Remember Question Titles
 9062: # FIXME: Possibly need delimiter other than ":"
 9063:     for (my $i=0;$i<$number;$i++) {
 9064:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9065:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9066:     }
 9067:     my $correct_count=0;
 9068:     my $student_count=0;
 9069:     my $unknown_count=0;
 9070: # Match answers with usernames
 9071: # FIXME: Possibly need delimiter other than ":"
 9072:     foreach my $id (keys(%responses)) {
 9073:        if ($correct_ids{$id}) {
 9074:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9075:           $correct_count++;
 9076:        } elsif ($clicker_ids{$id}) {
 9077:           if ($clicker_ids{$id}=~/\,/) {
 9078: # More than one user with the same clicker!
 9079:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9080:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9081:                            "<select name='multi".$id."'>";
 9082:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9083:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9084:              }
 9085:              $result.='</select>';
 9086:              $unknown_count++;
 9087:           } else {
 9088: # Good: found one and only one user with the right clicker
 9089:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9090:              $student_count++;
 9091:           }
 9092:        } else {
 9093:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9094:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9095:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9096:                    "\n".&mt("Domain").": ".
 9097:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9098:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9099:           $unknown_count++;
 9100:        }
 9101:     }
 9102:     $result.='<hr />'.
 9103:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9104:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9105:        if ($correct_count==0) {
 9106:           $errormsg.="Found no correct answers answers for grading!";
 9107:        } elsif ($correct_count>1) {
 9108:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9109:        }
 9110:     }
 9111:     if ($number<1) {
 9112:        $errormsg.="Found no questions.";
 9113:     }
 9114:     if ($errormsg) {
 9115:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9116:     } else {
 9117:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9118:     }
 9119:     $result.='</form></td></tr></table>'."\n".
 9120:              '</td></tr></table><br /><br />'."\n";
 9121:     return $result.&show_grading_menu_form($symb);
 9122: }
 9123: 
 9124: sub iclicker_eval {
 9125:     my ($questiontitles,$responses)=@_;
 9126:     my $number=0;
 9127:     my $errormsg='';
 9128:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9129:         my %components=&Apache::loncommon::record_sep($line);
 9130:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9131: 	if ($entries[0] eq 'Question') {
 9132: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9133: 		$$questiontitles[$number]=$entries[$i];
 9134: 		$number++;
 9135: 	    }
 9136: 	}
 9137: 	if ($entries[0]=~/^\#/) {
 9138: 	    my $id=$entries[0];
 9139: 	    my @idresponses;
 9140: 	    $id=~s/^[\#0]+//;
 9141: 	    for (my $i=0;$i<$number;$i++) {
 9142: 		my $idx=3+$i*6;
 9143: 		push(@idresponses,$entries[$idx]);
 9144: 	    }
 9145: 	    $$responses{$id}=join(',',@idresponses);
 9146: 	}
 9147:     }
 9148:     return ($errormsg,$number);
 9149: }
 9150: 
 9151: sub interwrite_eval {
 9152:     my ($questiontitles,$responses)=@_;
 9153:     my $number=0;
 9154:     my $errormsg='';
 9155:     my $skipline=1;
 9156:     my $questionnumber=0;
 9157:     my %idresponses=();
 9158:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9159:         my %components=&Apache::loncommon::record_sep($line);
 9160:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9161:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9162:         if ($entries[1] eq 'Response') { $skipline=1; }
 9163:         next if $skipline;
 9164:         if ($entries[0]!=$questionnumber) {
 9165:            $questionnumber=$entries[0];
 9166:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9167:            $number++;
 9168:         }
 9169:         my $id=$entries[4];
 9170:         $id=~s/^[\#0]+//;
 9171:         $id=~s/^v\d*\://i;
 9172:         $id=~s/[\-\:]//g;
 9173:         $idresponses{$id}[$number]=$entries[6];
 9174:     }
 9175:     foreach my $id (keys(%idresponses)) {
 9176:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9177:        $$responses{$id}=~s/^\s*\,//;
 9178:     }
 9179:     return ($errormsg,$number);
 9180: }
 9181: 
 9182: sub assign_clicker_grades {
 9183:     my ($r)=@_;
 9184:     my ($symb)=&get_symb($r);
 9185:     if (!$symb) {return '';}
 9186: # See which part we are saving to
 9187:     my $res_error;
 9188:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9189:     if ($res_error) {
 9190:         return &navmap_errormsg();
 9191:     }
 9192: # FIXME: This should probably look for the first handgradeable part
 9193:     my $part=$$partlist[0];
 9194: # Start screen output
 9195:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9196: 
 9197:     my $heading=&mt('Assigning grades based on clicker file');
 9198:     $result.=(<<ENDHEADER);
 9199: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9200: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9201: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9202: ENDHEADER
 9203: # Get correct result
 9204: # FIXME: Possibly need delimiter other than ":"
 9205:     my @correct=();
 9206:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9207:     my $number=$env{'form.number'};
 9208:     if ($gradingmechanism ne 'attendance') {
 9209:        foreach my $key (keys(%env)) {
 9210:           if ($key=~/^form\.correct\:/) {
 9211:              my @input=split(/\,/,$env{$key});
 9212:              for (my $i=0;$i<=$#input;$i++) {
 9213:                  if (($correct[$i]) && ($input[$i]) &&
 9214:                      ($correct[$i] ne $input[$i])) {
 9215:                     $result.='<br /><span class="LC_warning">'.
 9216:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9217:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9218:                  } elsif ($input[$i]) {
 9219:                     $correct[$i]=$input[$i];
 9220:                  }
 9221:              }
 9222:           }
 9223:        }
 9224:        for (my $i=0;$i<$number;$i++) {
 9225:           if (!$correct[$i]) {
 9226:              $result.='<br /><span class="LC_error">'.
 9227:                       &mt('No correct result given for question "[_1]"!',
 9228:                           $env{'form.question:'.$i}).'</span>';
 9229:           }
 9230:        }
 9231:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9232:     }
 9233: # Start grading
 9234:     my $pcorrect=$env{'form.pcorrect'};
 9235:     my $pincorrect=$env{'form.pincorrect'};
 9236:     my $storecount=0;
 9237:     foreach my $key (keys(%env)) {
 9238:        my $user='';
 9239:        if ($key=~/^form\.student\:(.*)$/) {
 9240:           $user=$1;
 9241:        }
 9242:        if ($key=~/^form\.unknown\:(.*)$/) {
 9243:           my $id=$1;
 9244:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9245:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9246:           } elsif ($env{'form.multi'.$id}) {
 9247:              $user=$env{'form.multi'.$id};
 9248:           }
 9249:        }
 9250:        if ($user) { 
 9251:           my @answer=split(/\,/,$env{$key});
 9252:           my $sum=0;
 9253:           my $realnumber=$number;
 9254:           for (my $i=0;$i<$number;$i++) {
 9255:              if  ($correct[$i] eq '-') {
 9256:                 $realnumber--;
 9257:              } elsif ($answer[$i]) {
 9258:                 if ($gradingmechanism eq 'attendance') {
 9259:                    $sum+=$pcorrect;
 9260:                 } elsif ($correct[$i] eq '*') {
 9261:                    $sum+=$pcorrect;
 9262:                 } else {
 9263:                    if ($answer[$i] eq $correct[$i]) {
 9264:                       $sum+=$pcorrect;
 9265:                    } else {
 9266:                       $sum+=$pincorrect;
 9267:                    }
 9268:                 }
 9269:              }
 9270:           }
 9271:           my $ave=$sum/(100*$realnumber);
 9272: # Store
 9273:           my ($username,$domain)=split(/\:/,$user);
 9274:           my %grades=();
 9275:           $grades{"resource.$part.solved"}='correct_by_override';
 9276:           $grades{"resource.$part.awarded"}=$ave;
 9277:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9278:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9279:                                                  $env{'request.course.id'},
 9280:                                                  $domain,$username);
 9281:           if ($returncode ne 'ok') {
 9282:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9283:           } else {
 9284:              $storecount++;
 9285:           }
 9286:        }
 9287:     }
 9288: # We are done
 9289:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9290:              '</td></tr></table>'."\n".
 9291:              '</td></tr></table><br /><br />'."\n";
 9292:     return $result.&show_grading_menu_form($symb);
 9293: }
 9294: 
 9295: sub navmap_errormsg {
 9296:     return '<div class="LC_error">'.
 9297:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9298:            &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>').
 9299:            '</div>';
 9300: }
 9301: 
 9302: sub handler {
 9303:     my $request=$_[0];
 9304:     &reset_caches();
 9305:     if ($env{'browser.mathml'}) {
 9306: 	&Apache::loncommon::content_type($request,'text/xml');
 9307:     } else {
 9308: 	&Apache::loncommon::content_type($request,'text/html');
 9309:     }
 9310:     $request->send_http_header;
 9311:     return '' if $request->header_only;
 9312:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9313:     my $symb=&get_symb($request,1);
 9314:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9315:     my $command=$commands[0];
 9316: 
 9317:     if ($#commands > 0) {
 9318: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9319:     }
 9320: 
 9321:     $ssi_error = 0;
 9322:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9323:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9324:                                           {'bread_crumbs' => $brcrum}));
 9325:     if ($symb eq '' && $command eq '') {
 9326: 	if ($env{'user.adv'}) {
 9327: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9328: 		($env{'form.codethree'})) {
 9329: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9330: 		    $env{'form.codethree'};
 9331: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9332: 		    &Apache::lonnet::checkin($token);
 9333: 		if ($tsymb) {
 9334: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9335: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9336: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9337: 					  ('grade_username' => $tuname,
 9338: 					   'grade_domain' => $tudom,
 9339: 					   'grade_courseid' => $tcrsid,
 9340: 					   'grade_symb' => $tsymb)));
 9341: 		    } else {
 9342: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9343: 		    }
 9344: 		} else {
 9345: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9346: 		}
 9347: 	    } else {
 9348: 		$request->print(&Apache::lonxml::tokeninputfield());
 9349: 	    }
 9350: 	}
 9351:     } else {
 9352: 	&init_perm();
 9353: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9354: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9355: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9356: 	    &pickStudentPage($request);
 9357: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9358: 	    &displayPage($request);
 9359: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9360: 	    &updateGradeByPage($request);
 9361: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9362: 	    &processGroup($request);
 9363: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9364: 	    $request->print(&grading_menu($request));
 9365: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9366: 	    $request->print(&submit_options($request));
 9367: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9368: 	    $request->print(&viewgrades($request));
 9369: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9370: 	    $request->print(&processHandGrade($request));
 9371: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9372: 	    $request->print(&editgrades($request));
 9373: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9374: 	    $request->print(&verifyreceipt($request));
 9375:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9376:             $request->print(&process_clicker($request));
 9377:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9378:             $request->print(&process_clicker_file($request));
 9379:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9380:             $request->print(&assign_clicker_grades($request));
 9381: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9382: 	    $request->print(&upcsvScores_form($request));
 9383: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9384: 	    $request->print(&csvupload($request));
 9385: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9386: 	    $request->print(&csvuploadmap($request));
 9387: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9388: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9389: 		$request->print(&csvuploadoptions($request));
 9390: 	    } else {
 9391: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9392: 		    $env{'form.upfile_associate'} = 'reverse';
 9393: 		} else {
 9394: 		    $env{'form.upfile_associate'} = 'forward';
 9395: 		}
 9396: 		$request->print(&csvuploadmap($request));
 9397: 	    }
 9398: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9399: 	    $request->print(&csvuploadassign($request));
 9400: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9401: 	    $request->print(&scantron_selectphase($request));
 9402:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9403:  	    $request->print(&scantron_do_warning($request));
 9404: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9405: 	    $request->print(&scantron_validate_file($request));
 9406: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9407: 	    $request->print(&scantron_process_students($request));
 9408:  	} elsif ($command eq 'scantronupload' && 
 9409:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9410: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9411:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9412:  	} elsif ($command eq 'scantronupload_save' &&
 9413:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9414: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9415:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9416:  	} elsif ($command eq 'scantron_download' &&
 9417: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9418:  	    $request->print(&scantron_download_scantron_data($request));
 9419:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9420:             $request->print(&checkscantron_results($request));     
 9421: 	} elsif ($command) {
 9422: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9423: 	}
 9424:     }
 9425:     if ($ssi_error) {
 9426: 	&ssi_print_error($request);
 9427:     }
 9428:     $request->print(&Apache::loncommon::end_page());
 9429:     &reset_caches();
 9430:     return '';
 9431: }
 9432: 
 9433: 1;
 9434: 
 9435: __END__;
 9436: 
 9437: 
 9438: =head1 NAME
 9439: 
 9440: Apache::grades
 9441: 
 9442: =head1 SYNOPSIS
 9443: 
 9444: Handles the viewing of grades.
 9445: 
 9446: This is part of the LearningOnline Network with CAPA project
 9447: described at http://www.lon-capa.org.
 9448: 
 9449: =head1 OVERVIEW
 9450: 
 9451: Do an ssi with retries:
 9452: While I'd love to factor out this with the vesrion in lonprintout,
 9453: 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
 9454: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9455: 
 9456: At least the logic that drives this has been pulled out into loncommon.
 9457: 
 9458: 
 9459: 
 9460: ssi_with_retries - Does the server side include of a resource.
 9461:                      if the ssi call returns an error we'll retry it up to
 9462:                      the number of times requested by the caller.
 9463:                      If we still have a proble, no text is appended to the
 9464:                      output and we set some global variables.
 9465:                      to indicate to the caller an SSI error occurred.  
 9466:                      All of this is supposed to deal with the issues described
 9467:                      in LonCAPA BZ 5631 see:
 9468:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9469:                      by informing the user that this happened.
 9470: 
 9471: Parameters:
 9472:   resource   - The resource to include.  This is passed directly, without
 9473:                interpretation to lonnet::ssi.
 9474:   form       - The form hash parameters that guide the interpretation of the resource
 9475:                
 9476:   retries    - Number of retries allowed before giving up completely.
 9477: Returns:
 9478:   On success, returns the rendered resource identified by the resource parameter.
 9479: Side Effects:
 9480:   The following global variables can be set:
 9481:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9482:                               It is up to the caller to initialize this to false
 9483:                               if desired.
 9484:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9485:                               of the resource that could not be rendered by the ssi
 9486:                               call.
 9487:    ssi_error_message   - The error string fetched from the ssi response
 9488:                               in the event of an error.
 9489: 
 9490: 
 9491: =head1 HANDLER SUBROUTINE
 9492: 
 9493: ssi_with_retries()
 9494: 
 9495: =head1 SUBROUTINES
 9496: 
 9497: =over
 9498: 
 9499: =item scantron_get_correction() : 
 9500: 
 9501:    Builds the interface screen to interact with the operator to fix a
 9502:    specific error condition in a specific scanline
 9503: 
 9504:  Arguments:
 9505:     $r           - Apache request object
 9506:     $i           - number of the current scanline
 9507:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9508:     $scan_config - hash ref as returned from &get_scantron_config()
 9509:     $line        - full contents of the current scanline
 9510:     $error       - error condition, valid values are
 9511:                    'incorrectCODE', 'duplicateCODE',
 9512:                    'doublebubble', 'missingbubble',
 9513:                    'duplicateID', 'incorrectID'
 9514:     $arg         - extra information needed
 9515:        For errors:
 9516:          - duplicateID   - paper number that this studentID was seen before on
 9517:          - duplicateCODE - array ref of the paper numbers this CODE was
 9518:                            seen on before
 9519:          - incorrectCODE - current incorrect CODE 
 9520:          - doublebubble  - array ref of the bubble lines that have double
 9521:                            bubble errors
 9522:          - missingbubble - array ref of the bubble lines that have missing
 9523:                            bubble errors
 9524: 
 9525: =item  scantron_get_maxbubble() : 
 9526: 
 9527:    Arguments:
 9528:        $nav_error  - Reference to scalar which is a flag to indicate a
 9529:                       failure to retrieve a navmap object.
 9530:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9531:        calling routine should trap the error condition and display the warning
 9532:        found in &navmap_errormsg().
 9533: 
 9534:    Returns the maximum number of bubble lines that are expected to
 9535:    occur. Does this by walking the selected sequence rendering the
 9536:    resource and then checking &Apache::lonxml::get_problem_counter()
 9537:    for what the current value of the problem counter is.
 9538: 
 9539:    Caches the results to $env{'form.scantron_maxbubble'},
 9540:    $env{'form.scantron.bubble_lines.n'}, 
 9541:    $env{'form.scantron.first_bubble_line.n'} and
 9542:    $env{"form.scantron.sub_bubblelines.n"}
 9543:    which are the total number of bubble, lines, the number of bubble
 9544:    lines for response n and number of the first bubble line for response n,
 9545:    and a comma separated list of numbers of bubble lines for sub-questions
 9546:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9547: 
 9548: 
 9549: =item  scantron_validate_missingbubbles() : 
 9550: 
 9551:    Validates all scanlines in the selected file to not have any
 9552:     answers that don't have bubbles that have not been verified
 9553:     to be bubble free.
 9554: 
 9555: =item  scantron_process_students() : 
 9556: 
 9557:    Routine that does the actual grading of the bubble sheet information.
 9558: 
 9559:    The parsed scanline hash is added to %env 
 9560: 
 9561:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9562:    foreach resource , with the form data of
 9563: 
 9564: 	'submitted'     =>'scantron' 
 9565: 	'grade_target'  =>'grade',
 9566: 	'grade_username'=> username of student
 9567: 	'grade_domain'  => domain of student
 9568: 	'grade_courseid'=> of course
 9569: 	'grade_symb'    => symb of resource to grade
 9570: 
 9571:     This triggers a grading pass. The problem grading code takes care
 9572:     of converting the bubbled letter information (now in %env) into a
 9573:     valid submission.
 9574: 
 9575: =item  scantron_upload_scantron_data() :
 9576: 
 9577:     Creates the screen for adding a new bubble sheet data file to a course.
 9578: 
 9579: =item  scantron_upload_scantron_data_save() : 
 9580: 
 9581:    Adds a provided bubble information data file to the course if user
 9582:    has the correct privileges to do so. 
 9583: 
 9584: =item  valid_file() :
 9585: 
 9586:    Validates that the requested bubble data file exists in the course.
 9587: 
 9588: =item  scantron_download_scantron_data() : 
 9589: 
 9590:    Shows a list of the three internal files (original, corrected,
 9591:    skipped) for a specific bubble sheet data file that exists in the
 9592:    course.
 9593: 
 9594: =item  scantron_validate_ID() : 
 9595: 
 9596:    Validates all scanlines in the selected file to not have any
 9597:    invalid or underspecified student/employee IDs
 9598: 
 9599: =item navmap_errormsg() :
 9600: 
 9601:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9602:    Should be called whenever the request to instantiate a navmap object fails.  
 9603: 
 9604: =back
 9605: 
 9606: =cut

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