File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.585: download - view: text, annotated - select for diffs
Wed Dec 16 16:09:24 2009 UTC (14 years, 4 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Manual Grading:
Use standard data_table for grading table

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.585 2009/12/16 16:09:24 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_grade_show_problem_header">'.
 1873: 	&mt('View of the problem').
 1874: 	'</div><div class="LC_grade_show_problem_problem">'.
 1875: 	$rendered.
 1876: 	'</div>';
 1877:     $companswer=
 1878: 	'<div class="LC_grade_show_problem_header">'.
 1879: 	&mt('Correct answer').
 1880: 	'</div><div class="LC_grade_show_problem_problem">'.
 1881: 	$companswer.
 1882: 	'</div>';
 1883:     my $result;
 1884:     if ($mode eq 'both') {
 1885: 	$result=$rendered.$companswer;
 1886:     } elsif ($mode eq 'text') {
 1887: 	$result=$rendered;
 1888:     } elsif ($mode eq 'answer') {
 1889: 	$result=$companswer;
 1890:     }
 1891:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1892:     return $result;
 1893: }
 1894: 
 1895: sub files_exist {
 1896:     my ($r, $symb) = @_;
 1897:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1898: 
 1899:     foreach my $student (@students) {
 1900:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1901:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1902: 					      $udom,$uname);
 1903:         my ($string,$timestamp)= &get_last_submission(\%record);
 1904:         foreach my $submission (@$string) {
 1905:             my ($partid,$respid) =
 1906: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1907:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1908: 					   \%record);
 1909:             return 1 if (@$files);
 1910:         }
 1911:     }
 1912:     return 0;
 1913: }
 1914: 
 1915: sub download_all_link {
 1916:     my ($r,$symb) = @_;
 1917:     my $all_students = 
 1918: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1919: 
 1920:     my $parts =
 1921: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1922: 
 1923:     my $identifier = &Apache::loncommon::get_cgi_id();
 1924:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1925:                              'cgi.'.$identifier.'.symb' => $symb,
 1926:                              'cgi.'.$identifier.'.parts' => $parts,});
 1927:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1928: 	      &mt('Download All Submitted Documents').'</a>');
 1929:     return
 1930: }
 1931: 
 1932: sub build_section_inputs {
 1933:     my $section_inputs;
 1934:     if ($env{'form.section'} eq '') {
 1935:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1936:     } else {
 1937:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1938:         foreach my $section (@sections) {
 1939:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1940:         }
 1941:     }
 1942:     return $section_inputs;
 1943: }
 1944: 
 1945: # --------------------------- show submissions of a student, option to grade 
 1946: sub submission {
 1947:     my ($request,$counter,$total) = @_;
 1948:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1949:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1950:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1951:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1952:     my $symb = &get_symb($request); 
 1953:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1954: 
 1955:     if (!&canview($usec)) {
 1956: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1957: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1958: 			$env{'request.course.id'}.')</span>');
 1959: 	$request->print(&show_grading_menu_form($symb));
 1960: 	return;
 1961:     }
 1962: 
 1963:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1964:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1965:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1966:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1967:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1968: 	'" src="'.$request->dir_config('lonIconsURL').
 1969: 	'/check.gif" height="16" border="0" />';
 1970: 
 1971:     my %old_essays;
 1972:     # header info
 1973:     if ($counter == 0) {
 1974: 	&sub_page_js($request);
 1975: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1976: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1977: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1978: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1979: 	    &download_all_link($request, $symb);
 1980: 	}
 1981: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1982: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1983: 
 1984: 	# option to display problem, only once else it cause problems 
 1985:         # with the form later since the problem has a form.
 1986: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1987: 	    my $mode;
 1988: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1989: 		$mode='both';
 1990: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1991: 		$mode='text';
 1992: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1993: 		$mode='answer';
 1994: 	    }
 1995: 	    &Apache::lonxml::clear_problem_counter();
 1996: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1997: 	}
 1998: 
 1999: 	# kwclr is the only variable that is guaranteed to be non blank 
 2000:         # if this subroutine has been called once.
 2001: 	my %keyhash = ();
 2002: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2003: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2004: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2005: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2006: 
 2007: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2008: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2009: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2010: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2011: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2012: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2013: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2014: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2015: 	}
 2016: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2017: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2018: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2019: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2020: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2021: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2022: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2023: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2024: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2025: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2026: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2027: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2028: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2029: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2030: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2031: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2032: 			&build_section_inputs().
 2033: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2034: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2035: 			'<input type="hidden" name="NCT"'.
 2036: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2037: 	if ($env{'form.handgrade'} eq 'yes') {
 2038: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2039: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2040: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2041: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2042: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2043: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2044: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2045: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2046: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2047: 	    }
 2048: 	}
 2049: 	
 2050: 	my ($cts,$prnmsg) = (1,'');
 2051: 	while ($cts <= $env{'form.savemsgN'}) {
 2052: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2053: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2054: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2055: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2056: 		'" />'."\n".
 2057: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2058: 	    $cts++;
 2059: 	}
 2060: 	$request->print($prnmsg);
 2061: 
 2062: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2063: #
 2064: # Print out the keyword options line
 2065: #
 2066: 	    $request->print(<<KEYWORDS);
 2067: &nbsp;<b>Keyword Options:</b>&nbsp;
 2068: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2069: <a href="#" onMouseDown="javascript:getSel(); return false"
 2070:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2071: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2072: KEYWORDS
 2073: #
 2074: # Load the other essays for similarity check
 2075: #
 2076:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2077: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2078: 	    $apath=&escape($apath);
 2079: 	    $apath=~s/\W/\_/gs;
 2080: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2081:         }
 2082:     }
 2083: 
 2084: # This is where output for one specific student would start
 2085:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2086:     $request->print("\n\n".
 2087:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2088: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2089: 		    '<div class="LC_grade_show_user_body">'."\n");
 2090: 
 2091:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2092: 	my $mode;
 2093: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2094: 	    $mode='both';
 2095: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2096: 	    $mode='text';
 2097: 	} elsif ($env{'form.vAns'} eq 'all') {
 2098: 	    $mode='answer';
 2099: 	}
 2100: 	&Apache::lonxml::clear_problem_counter();
 2101: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2102:     }
 2103: 
 2104:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2105:     my $res_error;
 2106:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2107:     if ($res_error) {
 2108:         $request->print(&navmap_errormsg());
 2109:         return;
 2110:     }
 2111: 
 2112:     # Display student info
 2113:     $request->print(($counter == 0 ? '' : '<br />'));
 2114:     my $result='<div class="LC_grade_submissions">';
 2115:     
 2116:     $result.='<div class="LC_grade_submissions_header">';
 2117:     $result.= &mt('Submissions');
 2118:     $result.='<input type="hidden" name="name'.$counter.
 2119: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2120:     if ($env{'form.handgrade'} eq 'no') {
 2121: 	$result.='<span class="LC_grade_check_note">'.
 2122: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2123: 
 2124:     }
 2125: 
 2126: 
 2127: 
 2128:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2129:     my $fullname;
 2130:     my $col_fullnames = [];
 2131:     if ($env{'form.handgrade'} eq 'yes') {
 2132: 	(my $sub_result,$fullname,$col_fullnames)=
 2133: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2134: 				 $counter);
 2135: 	$result.=$sub_result;
 2136:     }
 2137:     $request->print($result."\n");
 2138:     $request->print('</div>'."\n");
 2139:     # print student answer/submission
 2140:     # Options are (1) Handgaded submission only
 2141:     #             (2) Last submission, includes submission that is not handgraded 
 2142:     #                  (for multi-response type part)
 2143:     #             (3) Last submission plus the parts info
 2144:     #             (4) The whole record for this student
 2145:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2146: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2147: 	
 2148: 	my $lastsubonly;
 2149: 
 2150: 	if ($$timestamp eq '') {
 2151: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2152: 	} else {
 2153: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2154: 
 2155: 	    my %seenparts;
 2156: 	    my @part_response_id = &flatten_responseType($responseType);
 2157: 	    foreach my $part (@part_response_id) {
 2158: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2159: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2160: 
 2161: 		my ($partid,$respid) = @{ $part };
 2162: 		my $display_part=&get_display_part($partid,$symb);
 2163: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2164: 		    if (exists($seenparts{$partid})) { next; }
 2165: 		    $seenparts{$partid}=1;
 2166: 		    my $submitby='<b>Part:</b> '.$display_part.
 2167: 			' <b>Collaborative submission by:</b> '.
 2168: 			'<a href="javascript:viewSubmitter(\''.
 2169: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2170: 			'\');" target="_self">'.
 2171: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2172: 		    $request->print($submitby);
 2173: 		    next;
 2174: 		}
 2175: 		my $responsetype = $responseType->{$partid}->{$respid};
 2176: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2177:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2178:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2179:                         ' <span class="LC_internal_info">'.
 2180:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2181:                         '</span>&nbsp; &nbsp;'.
 2182: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2183: 		    next;
 2184: 		}
 2185: 		foreach my $submission (@$string) {
 2186: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2187: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2188: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2189: 		    # Similarity check
 2190: 		    my $similar='';
 2191: 		    if($env{'form.checkPlag'}){
 2192: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2193: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2194: 			if ($osim) {
 2195: 			    $osim=int($osim*100.0);
 2196: 			    my %old_course_desc = 
 2197: 				&Apache::lonnet::coursedescription($ocrsid,
 2198: 								   {'one_time' => 1});
 2199: 
 2200: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2201: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2202: 				    $osim,
 2203: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2204: 				    $old_course_desc{'description'},
 2205: 				    $old_course_desc{'num'},
 2206: 				    $old_course_desc{'domain'}).
 2207: 				'</span></h3><blockquote><i>'.
 2208: 				&keywords_highlight($oessay).
 2209: 				'</i></blockquote><hr />';
 2210: 			}
 2211: 		    }
 2212: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2213: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2214: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2215: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2216: 			my $display_part=&get_display_part($partid,$symb);
 2217:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2218:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2219:                             ' <span class="LC_internal_info">'.
 2220:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2221:                             '</b></span>&nbsp; &nbsp;';
 2222: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2223: 			if (@$files) {
 2224: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2225: 			    my $file_counter = 0;
 2226: 			    foreach my $file (@$files) {
 2227: 			        $file_counter++;
 2228: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2229: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2230: 			    }
 2231: 			    $lastsubonly.='<br />';
 2232: 			}
 2233: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2234: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2235: 					 $respid,\%record,$order,undef,$uname,$udom);
 2236: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2237: 			$lastsubonly.='</div>';
 2238: 		    }
 2239: 		}
 2240: 	    }
 2241: 	    $lastsubonly.='</div>'."\n";
 2242: 	}
 2243: 	$request->print($lastsubonly);
 2244:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2245: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2246: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2247:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2248: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2249: 								 $env{'request.course.id'},
 2250: 								 $last,'.submission',
 2251: 								 'Apache::grades::keywords_highlight'));
 2252:     }
 2253: 
 2254:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2255: 	.$udom.'" />'."\n");
 2256:     # return if view submission with no grading option
 2257:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2258: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2259: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2260: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2261: 	$toGrade.='</div>'."\n";
 2262: 	if (($env{'form.command'} eq 'submission') || 
 2263: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2264: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2265: 	}
 2266: 	$request->print($toGrade);
 2267: 	return;
 2268:     } else {
 2269: 	$request->print('</div>'."\n");
 2270:     }
 2271: 
 2272:     # essay grading message center
 2273:     if ($env{'form.handgrade'} eq 'yes') {
 2274: 	my $result='<div class="LC_grade_message_center">';
 2275:     
 2276: 	$result.='<div class="LC_grade_message_center_header">'.
 2277: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2278: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2279: 	my $msgfor = $givenn.' '.$lastname;
 2280: 	if (scalar(@$col_fullnames) > 0) {
 2281: 	    my $lastone = pop(@$col_fullnames);
 2282: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2283: 	}
 2284: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2285: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2286: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2287: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2288: 	    ',\''.$msgfor.'\');" target="_self">'.
 2289: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2290: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2291: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2292: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2293: 	    '<br />&nbsp;('.
 2294: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2295: 	$result.='</div></div>';
 2296: 	$request->print($result);
 2297:     }
 2298: 
 2299:     my %seen = ();
 2300:     my @partlist;
 2301:     my @gradePartRespid;
 2302:     my @part_response_id = &flatten_responseType($responseType);
 2303:     $request->print(
 2304:         '<div class="LC_grade_assign">'
 2305:        .'<div class="LC_grade_assign_header">'
 2306:        .&mt('Assign Grades').'</div>'
 2307:     );
 2308:     $request->print(&gradeBox_start()); # <div class="LC_grade_assign_body">
 2309:     foreach my $part_response_id (@part_response_id) {
 2310:     	my ($partid,$respid) = @{ $part_response_id };
 2311: 	my $part_resp = join('_',@{ $part_response_id });
 2312: 	next if ($seen{$partid} > 0);
 2313: 	$seen{$partid}++;
 2314: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2315: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2316: 	push(@partlist,$partid);
 2317: 	push(@gradePartRespid,$partid.'.'.$respid);
 2318: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2319:     }
 2320:     $request->print(&gradeBox_end()); # </div>
 2321:     $request->print('</div>');
 2322: 
 2323:     $request->print('<div class="LC_grade_info_links">');
 2324:     if ($perm{'vgr'}) {
 2325: 	$request->print(
 2326: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2327: 						   $uname,$udom,'check'));
 2328:     }
 2329:     if ($perm{'opa'}) {
 2330: 	$request->print(
 2331: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2332: 					 $uname,$udom,$symb,'check'));
 2333:     }
 2334:     $request->print('</div>');
 2335: 
 2336:     $result='<input type="hidden" name="partlist'.$counter.
 2337: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2338:     $result.='<input type="hidden" name="gradePartRespid'.
 2339: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2340:     my $ctr = 0;
 2341:     while ($ctr < scalar(@partlist)) {
 2342: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2343: 	    $partlist[$ctr].'" />'."\n";
 2344: 	$ctr++;
 2345:     }
 2346:     $request->print($result.''."\n");
 2347: 
 2348: # Done with printing info for one student
 2349: 
 2350:     $request->print('</div>');#LC_grade_show_user_body
 2351:     $request->print('</div>');#LC_grade_show_user
 2352: 
 2353: 
 2354:     # print end of form
 2355:     if ($counter == $total) {
 2356: 	my $endform='<table border="0"><tr><td>'."\n";
 2357: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2358: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2359: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2360: 	my $ntstu ='<select name="NTSTU">'.
 2361: 	    '<option>1</option><option>2</option>'.
 2362: 	    '<option>3</option><option>5</option>'.
 2363: 	    '<option>7</option><option>10</option></select>'."\n";
 2364: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2365: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2366:         $endform.=&mt('[_1]student(s)',$ntstu);
 2367: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2368: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2369: 	    '<input type="button" value="'.&mt('Next').'" '.
 2370: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2371: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2372:         $endform.="<input type='hidden' value='".&get_increment().
 2373:             "' name='increment' />";
 2374: 	$endform.='</td></tr></table></form>';
 2375: 	$endform.=&show_grading_menu_form($symb);
 2376: 	$request->print($endform);
 2377:     }
 2378:     return '';
 2379: }
 2380: 
 2381: sub check_collaborators {
 2382:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2383:     my ($result,@col_fullnames);
 2384:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2385:     foreach my $part (keys(%$handgrade)) {
 2386: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2387: 					'.maxcollaborators',
 2388: 					$symb,$udom,$uname);
 2389: 	next if ($ncol <= 0);
 2390: 	$part =~ s/\_/\./g;
 2391: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2392: 	my (@good_collaborators, @bad_collaborators);
 2393: 	foreach my $possible_collaborator
 2394: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2395: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2396: 	    next if ($possible_collaborator eq '');
 2397: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2398: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2399: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2400: 	    # Doing this grep allows 'fuzzy' specification
 2401: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2402: 			       keys(%$classlist));
 2403: 	    if (! scalar(@matches)) {
 2404: 		push(@bad_collaborators, $possible_collaborator);
 2405: 	    } else {
 2406: 		push(@good_collaborators, @matches);
 2407: 	    }
 2408: 	}
 2409: 	if (scalar(@good_collaborators) != 0) {
 2410: 	    $result.='<br />'.&mt('Collaborators: ');
 2411: 	    foreach my $name (@good_collaborators) {
 2412: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2413: 		push(@col_fullnames, $givenn.' '.$lastname);
 2414: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2415: 	    }
 2416: 	    $result.='<br />'."\n";
 2417: 	    my ($part)=split(/\./,$part);
 2418: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2419: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2420: 		"\n";
 2421: 	}
 2422: 	if (scalar(@bad_collaborators) > 0) {
 2423: 	    $result.='<div class="LC_warning">';
 2424: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2425: 	    $result .= '</div>';
 2426: 	}         
 2427: 	if (scalar(@bad_collaborators > $ncol)) {
 2428: 	    $result .= '<div class="LC_warning">';
 2429: 	    $result .= &mt('This student has submitted too many '.
 2430: 		'collaborators.  Maximum is [_1].',$ncol);
 2431: 	    $result .= '</div>';
 2432: 	}
 2433:     }
 2434:     return ($result,$fullname,\@col_fullnames);
 2435: }
 2436: 
 2437: #--- Retrieve the last submission for all the parts
 2438: sub get_last_submission {
 2439:     my ($returnhash)=@_;
 2440:     my (@string,$timestamp);
 2441:     if ($$returnhash{'version'}) {
 2442: 	my %lasthash=();
 2443: 	my ($version);
 2444: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2445: 	    foreach my $key (sort(split(/\:/,
 2446: 					$$returnhash{$version.':keys'}))) {
 2447: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2448: 		$timestamp = 
 2449: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2450: 	    }
 2451: 	}
 2452: 	foreach my $key (keys(%lasthash)) {
 2453: 	    next if ($key !~ /\.submission$/);
 2454: 
 2455: 	    my ($partid,$foo) = split(/submission$/,$key);
 2456: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2457: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2458: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2459: 	}
 2460:     }
 2461:     if (!@string) {
 2462: 	$string[0] =
 2463: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2464:     }
 2465:     return (\@string,\$timestamp);
 2466: }
 2467: 
 2468: #--- High light keywords, with style choosen by user.
 2469: sub keywords_highlight {
 2470:     my $string    = shift;
 2471:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2472:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2473:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2474:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2475:     foreach my $keyword (@keylist) {
 2476: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2477:     }
 2478:     return $string;
 2479: }
 2480: 
 2481: #--- Called from submission routine
 2482: sub processHandGrade {
 2483:     my ($request) = shift;
 2484:     my $symb   = &get_symb($request);
 2485:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2486:     my $button = $env{'form.gradeOpt'};
 2487:     my $ngrade = $env{'form.NCT'};
 2488:     my $ntstu  = $env{'form.NTSTU'};
 2489:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2490:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2491: 
 2492:     if ($button eq 'Save & Next') {
 2493: 	my $ctr = 0;
 2494: 	while ($ctr < $ngrade) {
 2495: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2496: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2497: 	    if ($errorflag eq 'no_score') {
 2498: 		$ctr++;
 2499: 		next;
 2500: 	    }
 2501: 	    if ($errorflag eq 'not_allowed') {
 2502: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2503: 		$ctr++;
 2504: 		next;
 2505: 	    }
 2506: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2507: 	    my ($subject,$message,$msgstatus) = ('','','');
 2508: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2509:             my ($feedurl,$showsymb) =
 2510: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2511: 	    my $messagetail;
 2512: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2513: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2514: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2515: 		$subject.=' ['.$restitle.']';
 2516: 		my (@msgnum) = split(/,/,$includemsg);
 2517: 		foreach (@msgnum) {
 2518: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2519: 		}
 2520: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2521: 		if ($env{'form.withgrades'.$ctr}) {
 2522: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2523: 		    $messagetail = " for <a href=\"".
 2524: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2525: 		}
 2526: 		$msgstatus = 
 2527:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2528: 						     $message.$messagetail,
 2529:                                                      undef,$feedurl,undef,
 2530:                                                      undef,undef,$showsymb,
 2531:                                                      $restitle);
 2532: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2533: 				$msgstatus);
 2534: 	    }
 2535: 	    if ($env{'form.collaborator'.$ctr}) {
 2536: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2537: 		foreach my $collabstr (@collabstrs) {
 2538: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2539: 		    foreach my $collaborator (@collaborators) {
 2540: 			my ($errorflag,$pts,$wgt) = 
 2541: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2542: 					   $env{'form.unamedom'.$ctr},$part);
 2543: 			if ($errorflag eq 'not_allowed') {
 2544: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2545: 			    next;
 2546: 			} elsif ($message ne '') {
 2547: 			    my ($baseurl,$showsymb) = 
 2548: 				&get_feedurl_and_symb($symb,$collaborator,
 2549: 						      $udom);
 2550: 			    if ($env{'form.withgrades'.$ctr}) {
 2551: 				$messagetail = " for <a href=\"".
 2552:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2553: 			    }
 2554: 			    $msgstatus = 
 2555: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2556: 			}
 2557: 		    }
 2558: 		}
 2559: 	    }
 2560: 	    $ctr++;
 2561: 	}
 2562:     }
 2563: 
 2564:     if ($env{'form.handgrade'} eq 'yes') {
 2565: 	# Keywords sorted in alphabatical order
 2566: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2567: 	my %keyhash = ();
 2568: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2569: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2570: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2571: 	$env{'form.keywords'} = join(' ',@keywords);
 2572: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2573: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2574: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2575: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2576: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2577: 
 2578: 	# message center - Order of message gets changed. Blank line is eliminated.
 2579: 	# New messages are saved in env for the next student.
 2580: 	# All messages are saved in nohist_handgrade.db
 2581: 	my ($ctr,$idx) = (1,1);
 2582: 	while ($ctr <= $env{'form.savemsgN'}) {
 2583: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2584: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2585: 		$idx++;
 2586: 	    }
 2587: 	    $ctr++;
 2588: 	}
 2589: 	$ctr = 0;
 2590: 	while ($ctr < $ngrade) {
 2591: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2592: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2593: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2594: 		$idx++;
 2595: 	    }
 2596: 	    $ctr++;
 2597: 	}
 2598: 	$env{'form.savemsgN'} = --$idx;
 2599: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2600: 	my $putresult = &Apache::lonnet::put
 2601: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2602:     }
 2603:     # Called by Save & Refresh from Highlight Attribute Window
 2604:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2605:     if ($env{'form.refresh'} eq 'on') {
 2606: 	my ($ctr,$total) = (0,0);
 2607: 	while ($ctr < $ngrade) {
 2608: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2609: 	    $ctr++;
 2610: 	}
 2611: 	$env{'form.NTSTU'}=$ngrade;
 2612: 	$ctr = 0;
 2613: 	while ($ctr < $total) {
 2614: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2615: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2616: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2617: 	    &submission($request,$ctr,$total-1);
 2618: 	    $ctr++;
 2619: 	}
 2620: 	return '';
 2621:     }
 2622: 
 2623: # Go directly to grade student - from submission or link from chart page
 2624:     if ($button eq 'Grade Student') {
 2625: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2626: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2627: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2628: 	$env{'form.fullname'} = $$fullname{$processUser};
 2629: 	&submission($request,0,0);
 2630: 	return '';
 2631:     }
 2632: 
 2633:     # Get the next/previous one or group of students
 2634:     my $firststu = $env{'form.unamedom0'};
 2635:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2636:     my $ctr = 2;
 2637:     while ($laststu eq '') {
 2638: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2639: 	$ctr++;
 2640: 	$laststu = $firststu if ($ctr > $ngrade);
 2641:     }
 2642: 
 2643:     my (@parsedlist,@nextlist);
 2644:     my ($nextflg) = 0;
 2645:     foreach my $item (sort 
 2646: 	     {
 2647: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2648: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2649: 		 }
 2650: 		 return $a cmp $b;
 2651: 	     } (keys(%$fullname))) {
 2652: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2653: 	    push(@parsedlist,$item);
 2654: 	}
 2655: 	$nextflg = 1 if ($item eq $laststu);
 2656: 	if ($button eq 'Previous') {
 2657: 	    last if ($item eq $firststu);
 2658: 	    push(@parsedlist,$item);
 2659: 	}
 2660:     }
 2661:     $ctr = 0;
 2662:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2663:     my $res_error;
 2664:     my ($partlist) = &response_type($symb,\$res_error);
 2665:     if ($res_error) {
 2666:         $request->print(&navmap_errormsg());
 2667:         return;
 2668:     }
 2669:     foreach my $student (@parsedlist) {
 2670: 	my $submitonly=$env{'form.submitonly'};
 2671: 	my ($uname,$udom) = split(/:/,$student);
 2672: 	
 2673: 	if ($submitonly eq 'queued') {
 2674: 	    my %queue_status = 
 2675: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2676: 							$udom,$uname);
 2677: 	    next if (!defined($queue_status{'gradingqueue'}));
 2678: 	}
 2679: 
 2680: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2681: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2682: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2683: 	    my $submitted = 0;
 2684: 	    my $ungraded = 0;
 2685: 	    my $incorrect = 0;
 2686: 	    foreach my $item (keys(%status)) {
 2687: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2688: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2689: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2690: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2691: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2692: 		    $submitted = 0;
 2693: 		}
 2694: 	    }
 2695: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2696: 				     $submitonly eq 'incorrect' ||
 2697: 				     $submitonly eq 'graded'));
 2698: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2699: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2700: 	}
 2701: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2702: 	last if ($ctr == $ntstu);
 2703: 	$ctr++;
 2704:     }
 2705: 
 2706:     $ctr = 0;
 2707:     my $total = scalar(@nextlist)-1;
 2708: 
 2709:     foreach (sort(@nextlist)) {
 2710: 	my ($uname,$udom,$submitter) = split(/:/);
 2711: 	$env{'form.student'}  = $uname;
 2712: 	$env{'form.userdom'}  = $udom;
 2713: 	$env{'form.fullname'} = $$fullname{$_};
 2714: 	&submission($request,$ctr,$total);
 2715: 	$ctr++;
 2716:     }
 2717:     if ($total < 0) {
 2718: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2719: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2720: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2721: 	$the_end.=&show_grading_menu_form($symb);
 2722: 	$request->print($the_end);
 2723:     }
 2724:     return '';
 2725: }
 2726: 
 2727: #---- Save the score and award for each student, if changed
 2728: sub saveHandGrade {
 2729:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2730:     my @version_parts;
 2731:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2732: 					   $env{'request.course.id'});
 2733:     if (!&canmodify($usec)) { return('not_allowed'); }
 2734:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2735:     my @parts_graded;
 2736:     my %newrecord  = ();
 2737:     my ($pts,$wgt) = ('','');
 2738:     my %aggregate = ();
 2739:     my $aggregateflag = 0;
 2740:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2741:     foreach my $new_part (@parts) {
 2742: 	#collaborator ($submi may vary for different parts
 2743: 	if ($submitter && $new_part ne $part) { next; }
 2744: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2745: 	if ($dropMenu eq 'excused') {
 2746: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2747: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2748: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2749: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2750: 		}
 2751: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2752: 	    }
 2753: 	} elsif ($dropMenu eq 'reset status'
 2754: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2755: 	    foreach my $key (keys(%record)) {
 2756: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2757: 	    }
 2758: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2759: 		"$env{'user.name'}:$env{'user.domain'}";
 2760:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2761: 
 2762:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2763: 					       [$new_part]);
 2764:             my $aggtries =$totaltries;
 2765:             if ($last_resets{$new_part}) {
 2766:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2767: 					   $new_part);
 2768:             }
 2769: 
 2770:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2771:             if ($aggtries > 0) {
 2772:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2773:                 $aggregateflag = 1;
 2774:             }
 2775: 	} elsif ($dropMenu eq '') {
 2776: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2777: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2778: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2779: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2780: 		next;
 2781: 	    }
 2782: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2783: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2784: 	    my $partial= $pts/$wgt;
 2785: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2786: 		#do not update score for part if not changed.
 2787:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2788: 		next;
 2789: 	    } else {
 2790: 	        push(@parts_graded,$new_part);
 2791: 	    }
 2792: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2793: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2794: 	    }
 2795: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2796: 	    if ($partial == 0) {
 2797: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2798: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2799: 		}
 2800: 	    } else {
 2801: 		if ($record{$reckey} ne 'correct_by_override') {
 2802: 		    $newrecord{$reckey} = 'correct_by_override';
 2803: 		}
 2804: 	    }	    
 2805: 	    if ($submitter && 
 2806: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2807: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2808: 	    }
 2809: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2810: 		"$env{'user.name'}:$env{'user.domain'}";
 2811: 	}
 2812: 	# unless problem has been graded, set flag to version the submitted files
 2813: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2814: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2815: 	        $dropMenu eq 'reset status')
 2816: 	   {
 2817: 	    push(@version_parts,$new_part);
 2818: 	}
 2819:     }
 2820:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2821:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2822: 
 2823:     if (%newrecord) {
 2824:         if (@version_parts) {
 2825:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2826:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2827: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2828: 	    foreach my $new_part (@version_parts) {
 2829: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2830: 				$new_part,\%newrecord);
 2831: 	    }
 2832:         }
 2833: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2834: 				$env{'request.course.id'},$domain,$stuname);
 2835: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2836: 				     $cdom,$cnum,$domain,$stuname);
 2837:     }
 2838:     if ($aggregateflag) {
 2839:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2840: 			      $cdom,$cnum);
 2841:     }
 2842:     return ('',$pts,$wgt);
 2843: }
 2844: 
 2845: sub check_and_remove_from_queue {
 2846:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2847:     my @ungraded_parts;
 2848:     foreach my $part (@{$parts}) {
 2849: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2850: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2851: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2852: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2853: 		) {
 2854: 	    push(@ungraded_parts, $part);
 2855: 	}
 2856:     }
 2857:     if ( !@ungraded_parts ) {
 2858: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2859: 					       $cnum,$domain,$stuname);
 2860:     }
 2861: }
 2862: 
 2863: sub handback_files {
 2864:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2865:     my $portfolio_root = '/userfiles/portfolio';
 2866:     my $res_error;
 2867:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2868:     if ($res_error) {
 2869:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2870:         return;
 2871:     }
 2872:     my @part_response_id = &flatten_responseType($responseType);
 2873:     foreach my $part_response_id (@part_response_id) {
 2874:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2875: 	my $part_resp = join('_',@{ $part_response_id });
 2876:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2877:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2878:                 my $file_counter = 1;
 2879: 		my $file_msg;
 2880:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2881:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2882:                     my ($directory,$answer_file) = 
 2883:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2884:                     my ($answer_name,$answer_ver,$answer_ext) =
 2885: 		        &file_name_version_ext($answer_file);
 2886: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2887:                     my $getpropath = 1;
 2888: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2889: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2890:                     # fix file name
 2891:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2892:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2893:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2894:             	                                $save_file_name);
 2895:                     if ($result !~ m|^/uploaded/|) {
 2896:                         $request->print('<br /><span class="LC_error">'.
 2897:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2898:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2899:                                         '</span>');
 2900:                     } else {
 2901:                         # mark the file as read only
 2902:                         my @files = ($save_file_name);
 2903:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2904:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2905: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2906: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2907: 			}
 2908:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2909: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2910: 
 2911:                     }
 2912:                     $request->print("<br />".$fname." will be the uploaded file name");
 2913:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2914:                     $file_counter++;
 2915:                 }
 2916: 		my $subject = "File Handed Back by Instructor ";
 2917: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2918: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2919: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2920: 		$message .= " and can be found in your portfolio space.";
 2921: 		my ($feedurl,$showsymb) = 
 2922: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2923:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2924: 		my $msgstatus = 
 2925:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2926: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2927:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2928:             }
 2929:         }
 2930:     return;
 2931: }
 2932: 
 2933: sub get_feedurl_and_symb {
 2934:     my ($symb,$uname,$udom) = @_;
 2935:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2936:     $url = &Apache::lonnet::clutter($url);
 2937:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2938: 					$symb,$udom,$uname);
 2939:     if ($encrypturl =~ /^yes$/i) {
 2940: 	&Apache::lonenc::encrypted(\$url,1);
 2941: 	&Apache::lonenc::encrypted(\$symb,1);
 2942:     }
 2943:     return ($url,$symb);
 2944: }
 2945: 
 2946: sub get_submitted_files {
 2947:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2948:     my @files;
 2949:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2950:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2951:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2952:     	    push(@files,$file_url.$file);
 2953:         }
 2954:     }
 2955:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2956:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2957:     }
 2958:     return (\@files);
 2959: }
 2960: 
 2961: # ----------- Provides number of tries since last reset.
 2962: sub get_num_tries {
 2963:     my ($record,$last_reset,$part) = @_;
 2964:     my $timestamp = '';
 2965:     my $num_tries = 0;
 2966:     if ($$record{'version'}) {
 2967:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2968:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2969:                 $timestamp = $$record{$version.':timestamp'};
 2970:                 if ($timestamp > $last_reset) {
 2971:                     $num_tries ++;
 2972:                 } else {
 2973:                     last;
 2974:                 }
 2975:             }
 2976:         }
 2977:     }
 2978:     return $num_tries;
 2979: }
 2980: 
 2981: # ----------- Determine decrements required in aggregate totals 
 2982: sub decrement_aggs {
 2983:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2984:     my %decrement = (
 2985:                         attempts => 0,
 2986:                         users => 0,
 2987:                         correct => 0
 2988:                     );
 2989:     $decrement{'attempts'} = $aggtries;
 2990:     if ($solvedstatus =~ /^correct/) {
 2991:         $decrement{'correct'} = 1;
 2992:     }
 2993:     if ($aggtries == $totaltries) {
 2994:         $decrement{'users'} = 1;
 2995:     }
 2996:     foreach my $type (keys(%decrement)) {
 2997:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2998:     }
 2999:     return;
 3000: }
 3001: 
 3002: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3003: sub get_last_resets {
 3004:     my ($symb,$courseid,$partids) =@_;
 3005:     my %last_resets;
 3006:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3007:     my $cname = $env{'course.'.$courseid.'.num'};
 3008:     my @keys;
 3009:     foreach my $part (@{$partids}) {
 3010: 	push(@keys,"$symb\0$part\0resettime");
 3011:     }
 3012:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3013: 				     $cdom,$cname);
 3014:     foreach my $part (@{$partids}) {
 3015: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3016:     }
 3017:     return %last_resets;
 3018: }
 3019: 
 3020: # ----------- Handles creating versions for portfolio files as answers
 3021: sub version_portfiles {
 3022:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3023:     my $version_parts = join('|',@$v_flag);
 3024:     my @returned_keys;
 3025:     my $parts = join('|', @$parts_graded);
 3026:     my $portfolio_root = '/userfiles/portfolio';
 3027:     foreach my $key (keys(%$record)) {
 3028:         my $new_portfiles;
 3029:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3030:             my @versioned_portfiles;
 3031:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3032:             foreach my $file (@portfiles) {
 3033:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3034:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3035: 		my ($answer_name,$answer_ver,$answer_ext) =
 3036: 		    &file_name_version_ext($answer_file);
 3037:                 my $getpropath = 1;    
 3038:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3039:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3040:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3041:                 if ($new_answer ne 'problem getting file') {
 3042:                     push(@versioned_portfiles, $directory.$new_answer);
 3043:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3044:                         [$directory.$new_answer],
 3045:                         [$symb,$env{'request.course.id'},'graded']);
 3046:                 }
 3047:             }
 3048:             $$record{$key} = join(',',@versioned_portfiles);
 3049:             push(@returned_keys,$key);
 3050:         }
 3051:     } 
 3052:     return (@returned_keys);   
 3053: }
 3054: 
 3055: sub get_next_version {
 3056:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3057:     my $version;
 3058:     foreach my $row (@$dir_list) {
 3059:         my ($file) = split(/\&/,$row,2);
 3060:         my ($file_name,$file_version,$file_ext) =
 3061: 	    &file_name_version_ext($file);
 3062:         if (($file_name eq $answer_name) && 
 3063: 	    ($file_ext eq $answer_ext)) {
 3064:                 # gets here if filename and extension match, regardless of version
 3065:                 if ($file_version ne '') {
 3066:                 # a versioned file is found  so save it for later
 3067:                 if ($file_version > $version) {
 3068: 		    $version = $file_version;
 3069: 	        }
 3070:             }
 3071:         }
 3072:     } 
 3073:     $version ++;
 3074:     return($version);
 3075: }
 3076: 
 3077: sub version_selected_portfile {
 3078:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3079:     my ($answer_name,$answer_ver,$answer_ext) =
 3080:         &file_name_version_ext($file_name);
 3081:     my $new_answer;
 3082:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3083:     if($env{'form.copy'} eq '-1') {
 3084:         $new_answer = 'problem getting file';
 3085:     } else {
 3086:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3087:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3088:                             $stu_name,$domain,'copy',
 3089: 		        '/portfolio'.$directory.$new_answer);
 3090:     }    
 3091:     return ($new_answer);
 3092: }
 3093: 
 3094: sub file_name_version_ext {
 3095:     my ($file)=@_;
 3096:     my @file_parts = split(/\./, $file);
 3097:     my ($name,$version,$ext);
 3098:     if (@file_parts > 1) {
 3099: 	$ext=pop(@file_parts);
 3100: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3101: 	    $version=pop(@file_parts);
 3102: 	}
 3103: 	$name=join('.',@file_parts);
 3104:     } else {
 3105: 	$name=join('.',@file_parts);
 3106:     }
 3107:     return($name,$version,$ext);
 3108: }
 3109: 
 3110: #--------------------------------------------------------------------------------------
 3111: #
 3112: #-------------------------- Next few routines handles grading by section or whole class
 3113: #
 3114: #--- Javascript to handle grading by section or whole class
 3115: sub viewgrades_js {
 3116:     my ($request) = shift;
 3117: 
 3118:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3119:     $request->print(<<VIEWJAVASCRIPT);
 3120: <script type="text/javascript" language="javascript">
 3121:    function writePoint(partid,weight,point) {
 3122: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3123: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3124: 	if (point == "textval") {
 3125: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3126: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3127: 		alert("$alertmsg"+parseFloat(point));
 3128: 		var resetbox = false;
 3129: 		for (var i=0; i<radioButton.length; i++) {
 3130: 		    if (radioButton[i].checked) {
 3131: 			textbox.value = i;
 3132: 			resetbox = true;
 3133: 		    }
 3134: 		}
 3135: 		if (!resetbox) {
 3136: 		    textbox.value = "";
 3137: 		}
 3138: 		return;
 3139: 	    }
 3140: 	    if (parseFloat(point) > parseFloat(weight)) {
 3141: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3142: 				   ") greater than the weight for the part. Accept?");
 3143: 		if (resp == false) {
 3144: 		    textbox.value = "";
 3145: 		    return;
 3146: 		}
 3147: 	    }
 3148: 	    for (var i=0; i<radioButton.length; i++) {
 3149: 		radioButton[i].checked=false;
 3150: 		if (parseFloat(point) == i) {
 3151: 		    radioButton[i].checked=true;
 3152: 		}
 3153: 	    }
 3154: 
 3155: 	} else {
 3156: 	    textbox.value = parseFloat(point);
 3157: 	}
 3158: 	for (i=0;i<document.classgrade.total.value;i++) {
 3159: 	    var user = document.classgrade["ctr"+i].value;
 3160: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3161: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3162: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3163: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3164: 	    if (saveval != "correct") {
 3165: 		scorename.value = point;
 3166: 		if (selname[0].selected != true) {
 3167: 		    selname[0].selected = true;
 3168: 		}
 3169: 	    }
 3170: 	}
 3171: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3172:     }
 3173: 
 3174:     function writeRadText(partid,weight) {
 3175: 	var selval   = document.classgrade["SELVAL_"+partid];
 3176: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3177:         var override = document.classgrade["FORCE_"+partid].checked;
 3178: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3179: 	if (selval[1].selected || selval[2].selected) {
 3180: 	    for (var i=0; i<radioButton.length; i++) {
 3181: 		radioButton[i].checked=false;
 3182: 
 3183: 	    }
 3184: 	    textbox.value = "";
 3185: 
 3186: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3187: 		var user = document.classgrade["ctr"+i].value;
 3188: 		user = user.replace(new RegExp(':', 'g'),"_");
 3189: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3190: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3191: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3192: 		if ((saveval != "correct") || override) {
 3193: 		    scorename.value = "";
 3194: 		    if (selval[1].selected) {
 3195: 			selname[1].selected = true;
 3196: 		    } else {
 3197: 			selname[2].selected = true;
 3198: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3199: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3200: 		    }
 3201: 		}
 3202: 	    }
 3203: 	} else {
 3204: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3205: 		var user = document.classgrade["ctr"+i].value;
 3206: 		user = user.replace(new RegExp(':', 'g'),"_");
 3207: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3208: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3209: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3210: 		if ((saveval != "correct") || override) {
 3211: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3212: 		    selname[0].selected = true;
 3213: 		}
 3214: 	    }
 3215: 	}	    
 3216:     }
 3217: 
 3218:     function changeSelect(partid,user) {
 3219: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3220: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3221: 	var point  = textbox.value;
 3222: 	var weight = document.classgrade["weight_"+partid].value;
 3223: 
 3224: 	if (isNaN(point) || parseFloat(point) < 0) {
 3225: 	    alert("$alertmsg"+parseFloat(point));
 3226: 	    textbox.value = "";
 3227: 	    return;
 3228: 	}
 3229: 	if (parseFloat(point) > parseFloat(weight)) {
 3230: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3231: 			       ") greater than the weight of the part. Accept?");
 3232: 	    if (resp == false) {
 3233: 		textbox.value = "";
 3234: 		return;
 3235: 	    }
 3236: 	}
 3237: 	selval[0].selected = true;
 3238:     }
 3239: 
 3240:     function changeOneScore(partid,user) {
 3241: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3242: 	if (selval[1].selected || selval[2].selected) {
 3243: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3244: 	    if (selval[2].selected) {
 3245: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3246: 	    }
 3247:         }
 3248:     }
 3249: 
 3250:     function resetEntry(numpart) {
 3251: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3252: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3253: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3254: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3255: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3256: 	    for (var i=0; i<radioButton.length; i++) {
 3257: 		radioButton[i].checked=false;
 3258: 
 3259: 	    }
 3260: 	    textbox.value = "";
 3261: 	    selval[0].selected = true;
 3262: 
 3263: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3264: 		var user = document.classgrade["ctr"+i].value;
 3265: 		user = user.replace(new RegExp(':', 'g'),"_");
 3266: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3267: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3268: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3269: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3270: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3271: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3272: 		if (saveselval == "excused") {
 3273: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3274: 		} else {
 3275: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3276: 		}
 3277: 	    }
 3278: 	}
 3279:     }
 3280: 
 3281: </script>
 3282: VIEWJAVASCRIPT
 3283: }
 3284: 
 3285: #--- show scores for a section or whole class w/ option to change/update a score
 3286: sub viewgrades {
 3287:     my ($request) = shift;
 3288:     &viewgrades_js($request);
 3289: 
 3290:     my ($symb) = &get_symb($request);
 3291:     #need to make sure we have the correct data for later EXT calls, 
 3292:     #thus invalidate the cache
 3293:     &Apache::lonnet::devalidatecourseresdata(
 3294:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3295:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3296:     &Apache::lonnet::clear_EXT_cache_status();
 3297: 
 3298:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3299:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3300: 
 3301:     #view individual student submission form - called using Javascript viewOneStudent
 3302:     $result.=&jscriptNform($symb);
 3303: 
 3304:     #beginning of class grading form
 3305:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3306:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3307: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3308: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3309: 	&build_section_inputs().
 3310: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3311: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3312: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3313: 
 3314:     my ($common_header,$specific_header);
 3315:     if ($env{'form.section'} eq 'all') {
 3316: 	$common_header = &mt('Assign Common Grade to Class');
 3317:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3318:     } elsif ($env{'form.section'} eq 'none') {
 3319:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3320: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3321:     } else {
 3322:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3323:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3324: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3325:     }
 3326:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3327:     #radio buttons/text box for assigning points for a section or class.
 3328:     #handles different parts of a problem
 3329:     my $res_error;
 3330:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3331:     if ($res_error) {
 3332:         return &navmap_errormsg();
 3333:     }
 3334:     my %weight = ();
 3335:     my $ctsparts = 0;
 3336:     my %seen = ();
 3337:     my @part_response_id = &flatten_responseType($responseType);
 3338:     foreach my $part_response_id (@part_response_id) {
 3339:     	my ($partid,$respid) = @{ $part_response_id };
 3340: 	my $part_resp = join('_',@{ $part_response_id });
 3341: 	next if $seen{$partid};
 3342: 	$seen{$partid}++;
 3343: 	my $handgrade=$$handgrade{$part_resp};
 3344: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3345: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3346: 
 3347: 	my $display_part=&get_display_part($partid,$symb);
 3348: 	my $radio.='<table border="0"><tr>';  
 3349: 	my $ctr = 0;
 3350: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3351: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3352: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3353: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3354: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3355: 	    $ctr++;
 3356: 	}
 3357: 	$radio.='</tr></table>';
 3358: 	my $line = '<input type="text" name="TEXTVAL_'.
 3359: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3360: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3361: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3362: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3363: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3364: 		$weight{$partid}.')"> '.
 3365: 	    '<option selected="selected"> </option>'.
 3366: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3367: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3368: 	    '</select></td>'.
 3369:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3370: 	$line.='<input type="hidden" name="partid_'.
 3371: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3372: 	$line.='<input type="hidden" name="weight_'.
 3373: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3374: 
 3375: 	$result.=
 3376: 	    &Apache::loncommon::start_data_table_row()."\n".
 3377: 	    '<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>'.
 3378: 	    &Apache::loncommon::end_data_table_row()."\n";
 3379: 	$ctsparts++;
 3380:     }
 3381:     $result.=&Apache::loncommon::end_data_table()."\n".
 3382: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3383:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3384: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3385: 
 3386:     #table listing all the students in a section/class
 3387:     #header of table
 3388:     $result.= '<h3>'.$specific_header.'</h3>'.
 3389:               &Apache::loncommon::start_data_table().
 3390: 	      &Apache::loncommon::start_data_table_header_row().
 3391: 	      '<th>'.&mt('No.').'</th>'.
 3392: 	      '<th>'.&nameUserString('header')."</th>\n";
 3393:     my $partserror;
 3394:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3395:     if ($partserror) {
 3396:         return &navmap_errormsg();
 3397:     }
 3398:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3399:     my @partids = ();
 3400:     foreach my $part (@parts) {
 3401: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3402:         my $narrowtext = &mt('Tries');
 3403: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3404: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3405: 	my ($partid) = &split_part_type($part);
 3406:         push(@partids,$partid);
 3407: 	my $display_part=&get_display_part($partid,$symb);
 3408: 	if ($display =~ /^Partial Credit Factor/) {
 3409: 	    $result.='<th>'.
 3410: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3411: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3412: 	    next;
 3413: 	    
 3414: 	} else {
 3415: 	    if ($display =~ /Problem Status/) {
 3416: 		my $grade_status_mt = &mt('Grade Status');
 3417: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3418: 	    }
 3419: 	    my $part_mt = &mt('Part:');
 3420: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3421: 	}
 3422: 
 3423: 	$result.='<th>'.$display.'</th>'."\n";
 3424:     }
 3425:     $result.=&Apache::loncommon::end_data_table_header_row();
 3426: 
 3427:     my %last_resets = 
 3428: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3429: 
 3430:     #get info for each student
 3431:     #list all the students - with points and grade status
 3432:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3433:     my $ctr = 0;
 3434:     foreach (sort 
 3435: 	     {
 3436: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3437: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3438: 		 }
 3439: 		 return $a cmp $b;
 3440: 	     } (keys(%$fullname))) {
 3441: 	$ctr++;
 3442: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3443: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3444:     }
 3445:     $result.=&Apache::loncommon::end_data_table();
 3446:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3447:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3448: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3449:     if (scalar(%$fullname) eq 0) {
 3450: 	my $colspan=3+scalar(@parts);
 3451: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3452:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3453: 	$result='<span class="LC_warning">'.
 3454: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3455: 	        $section_display, $stu_status).
 3456: 	    '</span>';
 3457:     }
 3458:     $result.=&show_grading_menu_form($symb);
 3459:     return $result;
 3460: }
 3461: 
 3462: #--- call by previous routine to display each student
 3463: sub viewstudentgrade {
 3464:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3465:     my ($uname,$udom) = split(/:/,$student);
 3466:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3467:     my %aggregates = (); 
 3468:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3469: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3470: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3471: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3472: 	'\');" target="_self">'.$fullname.'</a> '.
 3473: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3474:     $student=~s/:/_/; # colon doen't work in javascript for names
 3475:     foreach my $apart (@$parts) {
 3476: 	my ($part,$type) = &split_part_type($apart);
 3477: 	my $score=$record{"resource.$part.$type"};
 3478:         $result.='<td align="center">';
 3479:         my ($aggtries,$totaltries);
 3480:         unless (exists($aggregates{$part})) {
 3481: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3482: 
 3483: 	    $aggtries = $totaltries;
 3484:             if ($$last_resets{$part}) {  
 3485:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3486: 					   $part);
 3487:             }
 3488:             $result.='<input type="hidden" name="'.
 3489:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3490:             $result.='<input type="hidden" name="'.
 3491:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3492:             $aggregates{$part} = 1;
 3493:         }
 3494: 	if ($type eq 'awarded') {
 3495: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3496: 	    $result.='<input type="hidden" name="'.
 3497: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3498: 	    $result.='<input type="text" name="'.
 3499: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3500: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3501: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3502: 	} elsif ($type eq 'solved') {
 3503: 	    my ($status,$foo)=split(/_/,$score,2);
 3504: 	    $status = 'nothing' if ($status eq '');
 3505: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3506: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3507: 	    $result.='&nbsp;<select name="'.
 3508: 		'GD_'.$student.'_'.$part.'_solved" '.
 3509: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3510: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3511: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3512: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3513: 	    $result.="</select>&nbsp;</td>\n";
 3514: 	} else {
 3515: 	    $result.='<input type="hidden" name="'.
 3516: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3517: 		    "\n";
 3518: 	    $result.='<input type="text" name="'.
 3519: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3520: 		'value="'.$score.'" size="4" /></td>'."\n";
 3521: 	}
 3522:     }
 3523:     $result.=&Apache::loncommon::end_data_table_row();
 3524:     return $result;
 3525: }
 3526: 
 3527: #--- change scores for all the students in a section/class
 3528: #    record does not get update if unchanged
 3529: sub editgrades {
 3530:     my ($request) = @_;
 3531: 
 3532:     my $symb=&get_symb($request);
 3533:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3534:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3535:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3536:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3537: 
 3538:     my $result= &Apache::loncommon::start_data_table().
 3539: 	&Apache::loncommon::start_data_table_header_row().
 3540: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3541: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3542:     my %scoreptr = (
 3543: 		    'correct'  =>'correct_by_override',
 3544: 		    'incorrect'=>'incorrect_by_override',
 3545: 		    'excused'  =>'excused',
 3546: 		    'ungraded' =>'ungraded_attempted',
 3547: 		    'nothing'  => '',
 3548: 		    );
 3549:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3550: 
 3551:     my (@partid);
 3552:     my %weight = ();
 3553:     my %columns = ();
 3554:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3555: 
 3556:     my $partserror;
 3557:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3558:     if ($partserror) {
 3559:         return &navmap_errormsg();
 3560:     }
 3561:     my $header;
 3562:     while ($ctr < $env{'form.totalparts'}) {
 3563: 	my $partid = $env{'form.partid_'.$ctr};
 3564: 	push(@partid,$partid);
 3565: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3566: 	$ctr++;
 3567:     }
 3568:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3569:     foreach my $partid (@partid) {
 3570: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3571: 	    '<th align="center">'.&mt('New Score').'</th>';
 3572: 	$columns{$partid}=2;
 3573: 	foreach my $stores (@parts) {
 3574: 	    my ($part,$type) = &split_part_type($stores);
 3575: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3576: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3577: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3578: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3579:             my $narrowtext = &mt('Tries');
 3580: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3581: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3582: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3583: 	    $columns{$partid}+=2;
 3584: 	}
 3585:     }
 3586:     foreach my $partid (@partid) {
 3587: 	my $display_part=&get_display_part($partid,$symb);
 3588: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3589: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3590: 	    '</th>';
 3591: 
 3592:     }
 3593:     $result .= &Apache::loncommon::end_data_table_header_row().
 3594: 	&Apache::loncommon::start_data_table_header_row().
 3595: 	$header.
 3596: 	&Apache::loncommon::end_data_table_header_row();
 3597:     my @noupdate;
 3598:     my ($updateCtr,$noupdateCtr) = (1,1);
 3599:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3600: 	my $line;
 3601: 	my $user = $env{'form.ctr'.$i};
 3602: 	my ($uname,$udom)=split(/:/,$user);
 3603: 	my %newrecord;
 3604: 	my $updateflag = 0;
 3605: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3606: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3607: 	if (!&canmodify($usec)) {
 3608: 	    my $numcols=scalar(@partid)*4+2;
 3609: 	    push(@noupdate,
 3610: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3611: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3612: 	    next;
 3613: 	}
 3614:         my %aggregate = ();
 3615:         my $aggregateflag = 0;
 3616: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3617: 	foreach (@partid) {
 3618: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3619: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3620: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3621: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3622: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3623: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3624: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3625: 	    my $score;
 3626: 	    if ($partial eq '') {
 3627: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3628: 	    } elsif ($partial > 0) {
 3629: 		$score = 'correct_by_override';
 3630: 	    } elsif ($partial == 0) {
 3631: 		$score = 'incorrect_by_override';
 3632: 	    }
 3633: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3634: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3635: 
 3636: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3637: 		"$env{'user.name'}:$env{'user.domain'}";
 3638: 	    if ($dropMenu eq 'reset status' &&
 3639: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3640: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3641: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3642: 		$newrecord{'resource.'.$_.'.award'} = '';
 3643: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3644: 		$updateflag = 1;
 3645:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3646:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3647:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3648:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3649:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3650:                     $aggregateflag = 1;
 3651:                 }
 3652: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3653: 		$updateflag = 1;
 3654: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3655: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3656: 		$rec_update++;
 3657: 	    }
 3658: 
 3659: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3660: 		'<td align="center">'.$awarded.
 3661: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3662: 
 3663: 
 3664: 	    my $partid=$_;
 3665: 	    foreach my $stores (@parts) {
 3666: 		my ($part,$type) = &split_part_type($stores);
 3667: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3668: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3669: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3670: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3671: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3672: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3673: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3674: 		    $updateflag=1;
 3675: 		}
 3676: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3677: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3678: 	    }
 3679: 	}
 3680: 	$line.="\n";
 3681: 
 3682: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3683: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3684: 
 3685: 	if ($updateflag) {
 3686: 	    $count++;
 3687: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3688: 				    $udom,$uname);
 3689: 
 3690: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3691: 					      $cnum,$udom,$uname)) {
 3692: 		# need to figure out if should be in queue.
 3693: 		my %record =  
 3694: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3695: 					     $udom,$uname);
 3696: 		my $all_graded = 1;
 3697: 		my $none_graded = 1;
 3698: 		foreach my $part (@parts) {
 3699: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3700: 			$all_graded = 0;
 3701: 		    } else {
 3702: 			$none_graded = 0;
 3703: 		    }
 3704: 		}
 3705: 
 3706: 		if ($all_graded || $none_graded) {
 3707: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3708: 							   $symb,$cdom,$cnum,
 3709: 							   $udom,$uname);
 3710: 		}
 3711: 	    }
 3712: 
 3713: 	    $result.=&Apache::loncommon::start_data_table_row().
 3714: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3715: 		&Apache::loncommon::end_data_table_row();
 3716: 	    $updateCtr++;
 3717: 	} else {
 3718: 	    push(@noupdate,
 3719: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3720: 	    $noupdateCtr++;
 3721: 	}
 3722:         if ($aggregateflag) {
 3723:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3724: 				  $cdom,$cnum);
 3725:         }
 3726:     }
 3727:     if (@noupdate) {
 3728: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3729: 	my $numcols=scalar(@partid)*4+2;
 3730: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3731: 	    '<td align="center" colspan="'.$numcols.'">'.
 3732: 	    &mt('No Changes Occurred For the Students Below').
 3733: 	    '</td>'.
 3734: 	    &Apache::loncommon::end_data_table_row();
 3735: 	foreach my $line (@noupdate) {
 3736: 	    $result.=
 3737: 		&Apache::loncommon::start_data_table_row().
 3738: 		$line.
 3739: 		&Apache::loncommon::end_data_table_row();
 3740: 	}
 3741:     }
 3742:     $result .= &Apache::loncommon::end_data_table().
 3743: 	&show_grading_menu_form($symb);
 3744:     my $msg = '<p><b>'.
 3745: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3746: 	    $rec_update,$count).'</b><br />'.
 3747: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3748: 	'</b></p>';
 3749:     return $title.$msg.$result;
 3750: }
 3751: 
 3752: sub split_part_type {
 3753:     my ($partstr) = @_;
 3754:     my ($temp,@allparts)=split(/_/,$partstr);
 3755:     my $type=pop(@allparts);
 3756:     my $part=join('_',@allparts);
 3757:     return ($part,$type);
 3758: }
 3759: 
 3760: #------------- end of section for handling grading by section/class ---------
 3761: #
 3762: #----------------------------------------------------------------------------
 3763: 
 3764: 
 3765: #----------------------------------------------------------------------------
 3766: #
 3767: #-------------------------- Next few routines handles grading by csv upload
 3768: #
 3769: #--- Javascript to handle csv upload
 3770: sub csvupload_javascript_reverse_associate {
 3771:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3772:     my $error2=&mt('You need to specify at least one grading field');
 3773:   return(<<ENDPICK);
 3774:   function verify(vf) {
 3775:     var foundsomething=0;
 3776:     var founduname=0;
 3777:     var foundID=0;
 3778:     for (i=0;i<=vf.nfields.value;i++) {
 3779:       tw=eval('vf.f'+i+'.selectedIndex');
 3780:       if (i==0 && tw!=0) { foundID=1; }
 3781:       if (i==1 && tw!=0) { founduname=1; }
 3782:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3783:     }
 3784:     if (founduname==0 && foundID==0) {
 3785: 	alert('$error1');
 3786: 	return;
 3787:     }
 3788:     if (foundsomething==0) {
 3789: 	alert('$error2');
 3790: 	return;
 3791:     }
 3792:     vf.submit();
 3793:   }
 3794:   function flip(vf,tf) {
 3795:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3796:     var i;
 3797:     for (i=0;i<=vf.nfields.value;i++) {
 3798:       //can not pick the same destination field for both name and domain
 3799:       if (((i ==0)||(i ==1)) && 
 3800:           ((tf==0)||(tf==1)) && 
 3801:           (i!=tf) &&
 3802:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3803:         eval('vf.f'+i+'.selectedIndex=0;')
 3804:       }
 3805:     }
 3806:   }
 3807: ENDPICK
 3808: }
 3809: 
 3810: sub csvupload_javascript_forward_associate {
 3811:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3812:     my $error2=&mt('You need to specify at least one grading field');
 3813:   return(<<ENDPICK);
 3814:   function verify(vf) {
 3815:     var foundsomething=0;
 3816:     var founduname=0;
 3817:     var foundID=0;
 3818:     for (i=0;i<=vf.nfields.value;i++) {
 3819:       tw=eval('vf.f'+i+'.selectedIndex');
 3820:       if (tw==1) { foundID=1; }
 3821:       if (tw==2) { founduname=1; }
 3822:       if (tw>3) { foundsomething=1; }
 3823:     }
 3824:     if (founduname==0 && foundID==0) {
 3825: 	alert('$error1');
 3826: 	return;
 3827:     }
 3828:     if (foundsomething==0) {
 3829: 	alert('$error2');
 3830: 	return;
 3831:     }
 3832:     vf.submit();
 3833:   }
 3834:   function flip(vf,tf) {
 3835:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3836:     var i;
 3837:     //can not pick the same destination field twice
 3838:     for (i=0;i<=vf.nfields.value;i++) {
 3839:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3840:         eval('vf.f'+i+'.selectedIndex=0;')
 3841:       }
 3842:     }
 3843:   }
 3844: ENDPICK
 3845: }
 3846: 
 3847: sub csvuploadmap_header {
 3848:     my ($request,$symb,$datatoken,$distotal)= @_;
 3849:     my $javascript;
 3850:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3851: 	$javascript=&csvupload_javascript_reverse_associate();
 3852:     } else {
 3853: 	$javascript=&csvupload_javascript_forward_associate();
 3854:     }
 3855: 
 3856:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3857:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3858:     my $ignore=&mt('Ignore First Line');
 3859:     $symb = &Apache::lonenc::check_encrypt($symb);
 3860:     $request->print(<<ENDPICK);
 3861: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3862: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3863: $result
 3864: <hr />
 3865: <h3>Identify fields</h3>
 3866: Total number of records found in file: $distotal <hr />
 3867: Enter as many fields as you can. The system will inform you and bring you back
 3868: to this page if the data selected is insufficient to run your class.<hr />
 3869: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3870: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3871: <input type="hidden" name="associate"  value="" />
 3872: <input type="hidden" name="phase"      value="three" />
 3873: <input type="hidden" name="datatoken"  value="$datatoken" />
 3874: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3875: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3876: <input type="hidden" name="upfile_associate" 
 3877:                                        value="$env{'form.upfile_associate'}" />
 3878: <input type="hidden" name="symb"       value="$symb" />
 3879: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3880: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3881: <input type="hidden" name="command"    value="csvuploadoptions" />
 3882: <hr />
 3883: <script type="text/javascript" language="Javascript">
 3884: $javascript
 3885: </script>
 3886: ENDPICK
 3887:     return '';
 3888: 
 3889: }
 3890: 
 3891: sub csvupload_fields {
 3892:     my ($symb,$errorref) = @_;
 3893:     my (@parts) = &getpartlist($symb,$errorref);
 3894:     if (ref($errorref)) {
 3895:         if ($$errorref) {
 3896:             return;
 3897:         }
 3898:     }
 3899: 
 3900:     my @fields=(['ID','Student/Employee ID'],
 3901: 		['username','Student Username'],
 3902: 		['domain','Student Domain']);
 3903:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3904:     foreach my $part (sort(@parts)) {
 3905: 	my @datum;
 3906: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3907: 	my $name=$part;
 3908: 	if  (!$display) { $display = $name; }
 3909: 	@datum=($name,$display);
 3910: 	if ($name=~/^stores_(.*)_awarded/) {
 3911: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3912: 	}
 3913: 	push(@fields,\@datum);
 3914:     }
 3915:     return (@fields);
 3916: }
 3917: 
 3918: sub csvuploadmap_footer {
 3919:     my ($request,$i,$keyfields) =@_;
 3920:     $request->print(<<ENDPICK);
 3921: </table>
 3922: <input type="hidden" name="nfields" value="$i" />
 3923: <input type="hidden" name="keyfields" value="$keyfields" />
 3924: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3925: </form>
 3926: ENDPICK
 3927: }
 3928: 
 3929: sub checkforfile_js {
 3930:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3931:     my $result =<<CSVFORMJS;
 3932: <script type="text/javascript" language="javascript">
 3933:     function checkUpload(formname) {
 3934: 	if (formname.upfile.value == "") {
 3935: 	    alert("$alertmsg");
 3936: 	    return false;
 3937: 	}
 3938: 	formname.submit();
 3939:     }
 3940:     </script>
 3941: CSVFORMJS
 3942:     return $result;
 3943: }
 3944: 
 3945: sub upcsvScores_form {
 3946:     my ($request) = shift;
 3947:     my ($symb)=&get_symb($request);
 3948:     if (!$symb) {return '';}
 3949:     my $result=&checkforfile_js();
 3950:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3951:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3952:     $result.=$table;
 3953:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3954:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3955:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3956: 	'</b></td></tr>'."\n";
 3957:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3958:     my $upload=&mt("Upload Scores");
 3959:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3960:     my $ignore=&mt('Ignore First Line');
 3961:     $symb = &Apache::lonenc::check_encrypt($symb);
 3962:     $result.=<<ENDUPFORM;
 3963: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3964: <input type="hidden" name="symb" value="$symb" />
 3965: <input type="hidden" name="command" value="csvuploadmap" />
 3966: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3967: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3968: $upfile_select
 3969: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3970: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3971: </form>
 3972: ENDUPFORM
 3973:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3974:                            &mt("How do I create a CSV file from a spreadsheet"))
 3975:     .'</td></tr></table>'."\n";
 3976:     $result.='</td></tr></table><br /><br />'."\n";
 3977:     $result.=&show_grading_menu_form($symb);
 3978:     return $result;
 3979: }
 3980: 
 3981: 
 3982: sub csvuploadmap {
 3983:     my ($request)= @_;
 3984:     my ($symb)=&get_symb($request);
 3985:     if (!$symb) {return '';}
 3986: 
 3987:     my $datatoken;
 3988:     if (!$env{'form.datatoken'}) {
 3989: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3990:     } else {
 3991: 	$datatoken=$env{'form.datatoken'};
 3992: 	&Apache::loncommon::load_tmp_file($request);
 3993:     }
 3994:     my @records=&Apache::loncommon::upfile_record_sep();
 3995:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3996:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3997:     my ($i,$keyfields);
 3998:     if (@records) {
 3999:         my $fieldserror;
 4000: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 4001:         if ($fieldserror) {
 4002:             $request->print(&navmap_errormsg());
 4003:             return;
 4004:         }
 4005: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4006: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4007: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4008: 							  \@fields);
 4009: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4010: 	    chop($keyfields);
 4011: 	} else {
 4012: 	    unshift(@fields,['none','']);
 4013: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4014: 							    \@fields);
 4015:             foreach my $rec (@records) {
 4016:                 my %temp = &Apache::loncommon::record_sep($rec);
 4017:                 if (%temp) {
 4018:                     $keyfields=join(',',sort(keys(%temp)));
 4019:                     last;
 4020:                 }
 4021:             }
 4022: 	}
 4023:     }
 4024:     &csvuploadmap_footer($request,$i,$keyfields);
 4025:     $request->print(&show_grading_menu_form($symb));
 4026: 
 4027:     return '';
 4028: }
 4029: 
 4030: sub csvuploadoptions {
 4031:     my ($request)= @_;
 4032:     my ($symb)=&get_symb($request);
 4033:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4034:     my $ignore=&mt('Ignore First Line');
 4035:     $request->print(<<ENDPICK);
 4036: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4037: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4038: <input type="hidden" name="command"    value="csvuploadassign" />
 4039: <!--
 4040: <p>
 4041: <label>
 4042:    <input type="checkbox" name="show_full_results" />
 4043:    Show a table of all changes
 4044: </label>
 4045: </p>
 4046: -->
 4047: <p>
 4048: <label>
 4049:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4050:    Overwrite any existing score
 4051: </label>
 4052: </p>
 4053: ENDPICK
 4054:     my %fields=&get_fields();
 4055:     if (!defined($fields{'domain'})) {
 4056: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4057: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4058:     }
 4059:     foreach my $key (sort(keys(%env))) {
 4060: 	if ($key !~ /^form\.(.*)$/) { next; }
 4061: 	my $cleankey=$1;
 4062: 	if ($cleankey eq 'command') { next; }
 4063: 	$request->print('<input type="hidden" name="'.$cleankey.
 4064: 			'"  value="'.$env{$key}.'" />'."\n");
 4065:     }
 4066:     # FIXME do a check for any duplicated user ids...
 4067:     # FIXME do a check for any invalid user ids?...
 4068:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4069: <hr /></form>'."\n");
 4070:     $request->print(&show_grading_menu_form($symb));
 4071:     return '';
 4072: }
 4073: 
 4074: sub get_fields {
 4075:     my %fields;
 4076:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4077:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4078: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4079: 	    if ($env{'form.f'.$i} ne 'none') {
 4080: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4081: 	    }
 4082: 	} else {
 4083: 	    if ($env{'form.f'.$i} ne 'none') {
 4084: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4085: 	    }
 4086: 	}
 4087:     }
 4088:     return %fields;
 4089: }
 4090: 
 4091: sub csvuploadassign {
 4092:     my ($request)= @_;
 4093:     my ($symb)=&get_symb($request);
 4094:     if (!$symb) {return '';}
 4095:     my $error_msg = '';
 4096:     &Apache::loncommon::load_tmp_file($request);
 4097:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4098:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4099:     my %fields=&get_fields();
 4100:     $request->print('<h3>Assigning Grades</h3>');
 4101:     my $courseid=$env{'request.course.id'};
 4102:     my ($classlist) = &getclasslist('all',0);
 4103:     my @notallowed;
 4104:     my @skipped;
 4105:     my $countdone=0;
 4106:     foreach my $grade (@gradedata) {
 4107: 	my %entries=&Apache::loncommon::record_sep($grade);
 4108: 	my $domain;
 4109: 	if ($entries{$fields{'domain'}}) {
 4110: 	    $domain=$entries{$fields{'domain'}};
 4111: 	} else {
 4112: 	    $domain=$env{'form.default_domain'};
 4113: 	}
 4114: 	$domain=~s/\s//g;
 4115: 	my $username=$entries{$fields{'username'}};
 4116: 	$username=~s/\s//g;
 4117: 	if (!$username) {
 4118: 	    my $id=$entries{$fields{'ID'}};
 4119: 	    $id=~s/\s//g;
 4120: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4121: 	    $username=$ids{$id};
 4122: 	}
 4123: 	if (!exists($$classlist{"$username:$domain"})) {
 4124: 	    my $id=$entries{$fields{'ID'}};
 4125: 	    $id=~s/\s//g;
 4126: 	    if ($id) {
 4127: 		push(@skipped,"$id:$domain");
 4128: 	    } else {
 4129: 		push(@skipped,"$username:$domain");
 4130: 	    }
 4131: 	    next;
 4132: 	}
 4133: 	my $usec=$classlist->{"$username:$domain"}[5];
 4134: 	if (!&canmodify($usec)) {
 4135: 	    push(@notallowed,"$username:$domain");
 4136: 	    next;
 4137: 	}
 4138: 	my %points;
 4139: 	my %grades;
 4140: 	foreach my $dest (keys(%fields)) {
 4141: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4142: 		$dest eq 'domain') { next; }
 4143: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4144: 	    if ($dest=~/stores_(.*)_points/) {
 4145: 		my $part=$1;
 4146: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4147: 					      $symb,$domain,$username);
 4148:                 if ($wgt) {
 4149:                     $entries{$fields{$dest}}=~s/\s//g;
 4150:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4151:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4152:                                           : 'correct_by_override';
 4153:                     $grades{"resource.$part.awarded"}=$pcr;
 4154:                     $grades{"resource.$part.solved"}=$award;
 4155:                     $points{$part}=1;
 4156:                 } else {
 4157:                     $error_msg = "<br />" .
 4158:                         &mt("Some point values were assigned"
 4159:                             ." for problems with a weight "
 4160:                             ."of zero. These values were "
 4161:                             ."ignored.");
 4162:                 }
 4163: 	    } else {
 4164: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4165: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4166: 		my $store_key=$dest;
 4167: 		$store_key=~s/^stores/resource/;
 4168: 		$store_key=~s/_/\./g;
 4169: 		$grades{$store_key}=$entries{$fields{$dest}};
 4170: 	    }
 4171: 	}
 4172: 	if (! %grades) { 
 4173:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4174:         } else {
 4175: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4176: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4177: 					   $env{'request.course.id'},
 4178: 					   $domain,$username);
 4179: 	   if ($result eq 'ok') {
 4180: 	      $request->print('.');
 4181: 	   } else {
 4182: 	      $request->print("<p><span class=\"LC_error\">".
 4183:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4184:                                   "$username:$domain",$result)."</span></p>");
 4185: 	   }
 4186: 	   $request->rflush();
 4187: 	   $countdone++;
 4188:         }
 4189:     }
 4190:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4191:     if (@skipped) {
 4192: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4193:         $request->print(join(', ',@skipped));
 4194:     }
 4195:     if (@notallowed) {
 4196: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4197: 	$request->print(join(', ',@notallowed));
 4198:     }
 4199:     $request->print("<br />\n");
 4200:     $request->print(&show_grading_menu_form($symb));
 4201:     return $error_msg;
 4202: }
 4203: #------------- end of section for handling csv file upload ---------
 4204: #
 4205: #-------------------------------------------------------------------
 4206: #
 4207: #-------------- Next few routines handle grading by page/sequence
 4208: #
 4209: #--- Select a page/sequence and a student to grade
 4210: sub pickStudentPage {
 4211:     my ($request) = shift;
 4212: 
 4213:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4214:     $request->print(<<LISTJAVASCRIPT);
 4215: <script type="text/javascript" language="javascript">
 4216: 
 4217: function checkPickOne(formname) {
 4218:     if (radioSelection(formname.student) == null) {
 4219: 	alert("$alertmsg");
 4220: 	return;
 4221:     }
 4222:     ptr = pullDownSelection(formname.selectpage);
 4223:     formname.page.value = formname["page"+ptr].value;
 4224:     formname.title.value = formname["title"+ptr].value;
 4225:     formname.submit();
 4226: }
 4227: 
 4228: </script>
 4229: LISTJAVASCRIPT
 4230:     &commonJSfunctions($request);
 4231:     my ($symb) = &get_symb($request);
 4232:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4233:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4234:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4235: 
 4236:     my $result='<h3><span class="LC_info">&nbsp;'.
 4237: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4238: 
 4239:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4240:     my $map_error;
 4241:     my ($titles,$symbx) = &getSymbMap($map_error);
 4242:     if ($map_error) {
 4243:         $request->print(&navmap_errormsg());
 4244:         return; 
 4245:     }
 4246:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4247: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4248: #    my $type=($curpage =~ /\.(page|sequence)/);
 4249:     my $select = '<select name="selectpage">'."\n";
 4250:     my $ctr=0;
 4251:     foreach (@$titles) {
 4252: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4253: 	$select.='<option value="'.$ctr.'" '.
 4254: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4255: 	    '>'.$showtitle.'</option>'."\n";
 4256: 	$ctr++;
 4257:     }
 4258:     $select.= '</select>';
 4259:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4260: 
 4261:     $ctr=0;
 4262:     foreach (@$titles) {
 4263: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4264: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4265: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4266: 	$ctr++;
 4267:     }
 4268:     $result.='<input type="hidden" name="page" />'."\n".
 4269: 	'<input type="hidden" name="title" />'."\n";
 4270: 
 4271:     my $options =
 4272: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4273: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4274:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4275: 
 4276:     $options =
 4277: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4278: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4279: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4280:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4281:     
 4282:     $result.=&build_section_inputs();
 4283:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4284:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4285: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4286: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4287: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4288: 
 4289:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4290: 
 4291:     $result.='&nbsp;<input type="button" '.
 4292: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4293: 
 4294:     $request->print($result);
 4295: 
 4296:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4297: 	&Apache::loncommon::start_data_table().
 4298: 	&Apache::loncommon::start_data_table_header_row().
 4299: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4300: 	'<th>'.&nameUserString('header').'</th>'.
 4301: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4302: 	'<th>'.&nameUserString('header').'</th>'.
 4303: 	&Apache::loncommon::end_data_table_header_row();
 4304:  
 4305:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4306:     my $ptr = 1;
 4307:     foreach my $student (sort 
 4308: 			 {
 4309: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4310: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4311: 			     }
 4312: 			     return $a cmp $b;
 4313: 			 } (keys(%$fullname))) {
 4314: 	my ($uname,$udom) = split(/:/,$student);
 4315: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4316:                                   : '</td>');
 4317: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4318: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4319: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4320: 	$studentTable.=
 4321: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4322:                          : '');
 4323: 	$ptr++;
 4324:     }
 4325:     if ($ptr%2 == 0) {
 4326: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4327: 	    &Apache::loncommon::end_data_table_row();
 4328:     }
 4329:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4330:     $studentTable.='<input type="button" '.
 4331: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4332: 
 4333:     $studentTable.=&show_grading_menu_form($symb);
 4334:     $request->print($studentTable);
 4335: 
 4336:     return '';
 4337: }
 4338: 
 4339: sub getSymbMap {
 4340:     my ($map_error) = @_;
 4341:     my $navmap = Apache::lonnavmaps::navmap->new();
 4342:     unless (ref($navmap)) {
 4343:         if (ref($map_error)) {
 4344:             $$map_error = 'navmap';
 4345:         }
 4346:         return;
 4347:     }
 4348:     my %symbx = ();
 4349:     my @titles = ();
 4350:     my $minder = 0;
 4351: 
 4352:     # Gather every sequence that has problems.
 4353:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4354: 					       1,0,1);
 4355:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4356: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4357: 	    my $title = $minder.'.'.
 4358: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4359: 	    push(@titles, $title); # minder in case two titles are identical
 4360: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4361: 	    $minder++;
 4362: 	}
 4363:     }
 4364:     return \@titles,\%symbx;
 4365: }
 4366: 
 4367: #
 4368: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4369: sub displayPage {
 4370:     my ($request) = shift;
 4371: 
 4372:     my ($symb) = &get_symb($request);
 4373:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4374:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4375:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4376:     my $pageTitle = $env{'form.page'};
 4377:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4378:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4379:     my $usec=$classlist->{$env{'form.student'}}[5];
 4380: 
 4381:     #need to make sure we have the correct data for later EXT calls, 
 4382:     #thus invalidate the cache
 4383:     &Apache::lonnet::devalidatecourseresdata(
 4384:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4385:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4386:     &Apache::lonnet::clear_EXT_cache_status();
 4387: 
 4388:     if (!&canview($usec)) {
 4389: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4390: 	$request->print(&show_grading_menu_form($symb));
 4391: 	return;
 4392:     }
 4393:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4394:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4395: 	'</h3>'."\n";
 4396:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4397:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4398: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4399:     } else {
 4400: 	delete($env{'form.CODE'});
 4401:     }
 4402:     &sub_page_js($request);
 4403:     $request->print($result);
 4404: 
 4405:     my $navmap = Apache::lonnavmaps::navmap->new();
 4406:     unless (ref($navmap)) {
 4407:         $request->print(&navmap_errormsg());
 4408:         $request->print(&show_grading_menu_form($symb));
 4409:         return;
 4410:     }
 4411:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4412:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4413:     if (!$map) {
 4414: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4415: 	$request->print(&show_grading_menu_form($symb));
 4416: 	return; 
 4417:     }
 4418:     my $iterator = $navmap->getIterator($map->map_start(),
 4419: 					$map->map_finish());
 4420: 
 4421:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4422: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4423: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4424: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4425: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4426: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4427: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4428: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4429: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4430: 
 4431:     if (defined($env{'form.CODE'})) {
 4432: 	$studentTable.=
 4433: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4434:     }
 4435:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4436: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4437: 
 4438:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4439: 	&Apache::loncommon::start_data_table().
 4440: 	&Apache::loncommon::start_data_table_header_row().
 4441: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4442: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4443: 	&Apache::loncommon::end_data_table_header_row();
 4444: 
 4445:     &Apache::lonxml::clear_problem_counter();
 4446:     my ($depth,$question,$prob) = (1,1,1);
 4447:     $iterator->next(); # skip the first BEGIN_MAP
 4448:     my $curRes = $iterator->next(); # for "current resource"
 4449:     while ($depth > 0) {
 4450:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4451:         if($curRes == $iterator->END_MAP) { $depth--; }
 4452: 
 4453:         if (ref($curRes) && $curRes->is_problem()) {
 4454: 	    my $parts = $curRes->parts();
 4455:             my $title = $curRes->compTitle();
 4456: 	    my $symbx = $curRes->symb();
 4457: 	    $studentTable.=
 4458: 		&Apache::loncommon::start_data_table_row().
 4459: 		'<td align="center" valign="top" >'.$prob.
 4460: 		(scalar(@{$parts}) == 1 ? '' 
 4461: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4462: 							scalar(@{$parts}))
 4463: 		 ).
 4464: 		 '</td>';
 4465: 	    $studentTable.='<td valign="top">';
 4466: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4467: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4468: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4469: 					     undef,'both',\%form);
 4470: 	    } else {
 4471: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4472: 		$companswer =~ s|<form(.*?)>||g;
 4473: 		$companswer =~ s|</form>||g;
 4474: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4475: #		    $companswer =~ s/$1/ /ms;
 4476: #		    $request->print('match='.$1."<br />\n");
 4477: #		}
 4478: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4479: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4480: 	    }
 4481: 
 4482: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4483: 
 4484: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4485: 		if ($record{'version'} eq '') {
 4486: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4487: 		} else {
 4488: 		    my %responseType = ();
 4489: 		    foreach my $partid (@{$parts}) {
 4490: 			my @responseIds =$curRes->responseIds($partid);
 4491: 			my @responseType =$curRes->responseType($partid);
 4492: 			my %responseIds;
 4493: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4494: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4495: 			}
 4496: 			$responseType{$partid} = \%responseIds;
 4497: 		    }
 4498: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4499: 
 4500: 		}
 4501: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4502: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4503: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4504: 									$env{'request.course.id'},
 4505: 									'','.submission');
 4506:  
 4507: 	    }
 4508: 	    if (&canmodify($usec)) {
 4509:             $studentTable.=&gradeBox_start();
 4510: 		foreach my $partid (@{$parts}) {
 4511: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4512: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4513: 		    $question++;
 4514: 		}
 4515:             $studentTable.=&gradeBox_end();
 4516: 		$prob++;
 4517: 	    }
 4518: 	    $studentTable.='</td></tr>';
 4519: 
 4520: 	}
 4521:         $curRes = $iterator->next();
 4522:     }
 4523: 
 4524:     $studentTable.='</table>'."\n".
 4525: 	'<input type="button" value="'.&mt('Save').'" '.
 4526: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4527: 	'</form>'."\n";
 4528:     $studentTable.=&show_grading_menu_form($symb);
 4529:     $request->print($studentTable);
 4530: 
 4531:     return '';
 4532: }
 4533: 
 4534: sub displaySubByDates {
 4535:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4536:     my $isCODE=0;
 4537:     my $isTask = ($symb =~/\.task$/);
 4538:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4539:     my $studentTable=&Apache::loncommon::start_data_table().
 4540: 	&Apache::loncommon::start_data_table_header_row().
 4541: 	'<th>'.&mt('Date/Time').'</th>'.
 4542: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4543: 	'<th>'.&mt('Submission').'</th>'.
 4544: 	'<th>'.&mt('Status').'</th>'.
 4545: 	&Apache::loncommon::end_data_table_header_row();
 4546:     my ($version);
 4547:     my %mark;
 4548:     my %orders;
 4549:     $mark{'correct_by_student'} = $checkIcon;
 4550:     if (!exists($$record{'1:timestamp'})) {
 4551: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4552:     }
 4553: 
 4554:     my $interaction;
 4555:     my $no_increment = 1;
 4556:     for ($version=1;$version<=$$record{'version'};$version++) {
 4557: 	my $timestamp = 
 4558: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4559: 	if (exists($$record{$version.':resource.0.version'})) {
 4560: 	    $interaction = $$record{$version.':resource.0.version'};
 4561: 	}
 4562: 
 4563: 	my $where = ($isTask ? "$version:resource.$interaction"
 4564: 		             : "$version:resource");
 4565: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4566: 	    '<td>'.$timestamp.'</td>';
 4567: 	if ($isCODE) {
 4568: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4569: 	}
 4570: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4571: 	my @displaySub = ();
 4572: 	foreach my $partid (@{$parts}) {
 4573: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4574: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4575: 	    
 4576: 
 4577: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4578: 	    my $display_part=&get_display_part($partid,$symb);
 4579: 	    foreach my $matchKey (@matchKey) {
 4580: 		if (exists($$record{$version.':'.$matchKey}) &&
 4581: 		    $$record{$version.':'.$matchKey} ne '') {
 4582: 
 4583: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4584: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4585:                     $displaySub[0].='<span class="LC_nobreak"';
 4586:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4587:                                    .' <span class="LC_internal_info">'
 4588:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4589:                                    .'</span>'
 4590:                                    .' <b>';
 4591: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4592: 			$displaySub[0].=&mt('Trial not counted');
 4593: 		    } else {
 4594: 			$displaySub[0].=&mt('Trial: [_1]',
 4595: 					    $$record{"$where.$partid.tries"});
 4596: 		    }
 4597: 		    my $responseType=($isTask ? 'Task'
 4598:                                               : $responseType->{$partid}->{$responseId});
 4599: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4600: 		    if (!exists($orders{$partid}->{$responseId})) {
 4601: 			$orders{$partid}->{$responseId}=
 4602: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4603:                                        $no_increment);
 4604: 		    }
 4605: 		    $displaySub[0].='</b></span>'; # /nobreak
 4606: 		    $displaySub[0].='&nbsp; '.
 4607: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4608: 		}
 4609: 	    }
 4610: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4611: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4612: 				    $$record{"$where.$partid.checkedin"},
 4613: 				    $$record{"$where.$partid.checkedin.slot"}).
 4614: 					'<br />';
 4615: 	    }
 4616: 	    if (exists $$record{"$where.$partid.award"}) {
 4617: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4618: 		    lc($$record{"$where.$partid.award"}).' '.
 4619: 		    $mark{$$record{"$where.$partid.solved"}}.
 4620: 		    '<br />';
 4621: 	    }
 4622: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4623: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4624: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4625: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4626: 		$displaySub[2].=
 4627: 		    $$record{"$version:resource.$partid.regrader"}.
 4628: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4629: 	    }
 4630: 	}
 4631: 	# needed because old essay regrader has not parts info
 4632: 	if (exists $$record{"$version:resource.regrader"}) {
 4633: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4634: 	}
 4635: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4636: 	if ($displaySub[2]) {
 4637: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4638: 	}
 4639: 	$studentTable.='&nbsp;</td>'.
 4640: 	    &Apache::loncommon::end_data_table_row();
 4641:     }
 4642:     $studentTable.=&Apache::loncommon::end_data_table();
 4643:     return $studentTable;
 4644: }
 4645: 
 4646: sub updateGradeByPage {
 4647:     my ($request) = shift;
 4648: 
 4649:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4650:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4651:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4652:     my $pageTitle = $env{'form.page'};
 4653:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4654:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4655:     my $usec=$classlist->{$env{'form.student'}}[5];
 4656:     if (!&canmodify($usec)) {
 4657: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4658: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4659: 	return;
 4660:     }
 4661:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4662:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4663: 	'</h3>'."\n";
 4664: 
 4665:     $request->print($result);
 4666: 
 4667: 
 4668:     my $navmap = Apache::lonnavmaps::navmap->new();
 4669:     unless (ref($navmap)) {
 4670:         $request->print(&navmap_errormsg());
 4671:         return;
 4672:     }
 4673:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4674:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4675:     if (!$map) {
 4676: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4677: 	my ($symb)=&get_symb($request);
 4678: 	$request->print(&show_grading_menu_form($symb));
 4679: 	return; 
 4680:     }
 4681:     my $iterator = $navmap->getIterator($map->map_start(),
 4682: 					$map->map_finish());
 4683: 
 4684:     my $studentTable=
 4685: 	&Apache::loncommon::start_data_table().
 4686: 	&Apache::loncommon::start_data_table_header_row().
 4687: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4688: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4689: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4690: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4691: 	&Apache::loncommon::end_data_table_header_row();
 4692: 
 4693:     $iterator->next(); # skip the first BEGIN_MAP
 4694:     my $curRes = $iterator->next(); # for "current resource"
 4695:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4696:     while ($depth > 0) {
 4697:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4698:         if($curRes == $iterator->END_MAP) { $depth--; }
 4699: 
 4700:         if (ref($curRes) && $curRes->is_problem()) {
 4701: 	    my $parts = $curRes->parts();
 4702:             my $title = $curRes->compTitle();
 4703: 	    my $symbx = $curRes->symb();
 4704: 	    $studentTable.=
 4705: 		&Apache::loncommon::start_data_table_row().
 4706: 		'<td align="center" valign="top" >'.$prob.
 4707: 		(scalar(@{$parts}) == 1 ? '' 
 4708:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4709: 		.')').'</td>';
 4710: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4711: 
 4712: 	    my %newrecord=();
 4713: 	    my @displayPts=();
 4714:             my %aggregate = ();
 4715:             my $aggregateflag = 0;
 4716: 	    foreach my $partid (@{$parts}) {
 4717: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4718: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4719: 
 4720: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4721: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4722: 		my $partial = $newpts/$wgt;
 4723: 		my $score;
 4724: 		if ($partial > 0) {
 4725: 		    $score = 'correct_by_override';
 4726: 		} elsif ($newpts ne '') { #empty is taken as 0
 4727: 		    $score = 'incorrect_by_override';
 4728: 		}
 4729: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4730: 		if ($dropMenu eq 'excused') {
 4731: 		    $partial = '';
 4732: 		    $score = 'excused';
 4733: 		} elsif ($dropMenu eq 'reset status'
 4734: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4735: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4736: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4737: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4738: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4739: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4740: 		    $changeflag++;
 4741: 		    $newpts = '';
 4742:                     
 4743:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4744:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4745:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4746:                     if ($aggtries > 0) {
 4747:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4748:                         $aggregateflag = 1;
 4749:                     }
 4750: 		}
 4751: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4752: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4753: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4754: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4755: 		    '&nbsp;<br />';
 4756: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4757: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4758: 		    '&nbsp;<br />';
 4759: 		$question++;
 4760: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4761: 
 4762: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4763: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4764: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4765: 		    if (scalar(keys(%newrecord)) > 0);
 4766: 
 4767: 		$changeflag++;
 4768: 	    }
 4769: 	    if (scalar(keys(%newrecord)) > 0) {
 4770: 		my %record = 
 4771: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4772: 					     $udom,$uname);
 4773: 
 4774: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4775: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4776: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4777: 		    $newrecord{'resource.CODE'} = '';
 4778: 		}
 4779: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4780: 					$udom,$uname);
 4781: 		%record = &Apache::lonnet::restore($symbx,
 4782: 						   $env{'request.course.id'},
 4783: 						   $udom,$uname);
 4784: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4785: 					     $cdom,$cnum,$udom,$uname);
 4786: 	    }
 4787: 	    
 4788:             if ($aggregateflag) {
 4789:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4790:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4791:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4792:             }
 4793: 
 4794: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4795: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4796: 		&Apache::loncommon::end_data_table_row();
 4797: 
 4798: 	    $prob++;
 4799: 	}
 4800:         $curRes = $iterator->next();
 4801:     }
 4802: 
 4803:     $studentTable.=&Apache::loncommon::end_data_table();
 4804:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4805:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4806: 		  &mt('The scores were changed for [quant,_1,problem].',
 4807: 		  $changeflag));
 4808:     $request->print($grademsg.$studentTable);
 4809: 
 4810:     return '';
 4811: }
 4812: 
 4813: #-------- end of section for handling grading by page/sequence ---------
 4814: #
 4815: #-------------------------------------------------------------------
 4816: 
 4817: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4818: #
 4819: #------ start of section for handling grading by page/sequence ---------
 4820: 
 4821: =pod
 4822: 
 4823: =head1 Bubble sheet grading routines
 4824: 
 4825:   For this documentation:
 4826: 
 4827:    'scanline' refers to the full line of characters
 4828:    from the file that we are parsing that represents one entire sheet
 4829: 
 4830:    'bubble line' refers to the data
 4831:    representing the line of bubbles that are on the physical bubble sheet
 4832: 
 4833: 
 4834: The overall process is that a scanned in bubble sheet data is uploaded
 4835: into a course. When a user wants to grade, they select a
 4836: sequence/folder of resources, a file of bubble sheet info, and pick
 4837: one of the predefined configurations for what each scanline looks
 4838: like.
 4839: 
 4840: Next each scanline is checked for any errors of either 'missing
 4841: bubbles' (it's an error because it may have been mis-scanned
 4842: because too light bubbling), 'double bubble' (each bubble line should
 4843: have no more that one letter picked), invalid or duplicated CODE,
 4844: invalid student/employee ID
 4845: 
 4846: If the CODE option is used that determines the randomization of the
 4847: homework problems, either way the student/employee ID is looked up into a
 4848: username:domain.
 4849: 
 4850: During the validation phase the instructor can choose to skip scanlines. 
 4851: 
 4852: After the validation phase, there are now 3 bubble sheet files
 4853: 
 4854:   scantron_original_filename (unmodified original file)
 4855:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4856:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4857: 
 4858: Also there is a separate hash nohist_scantrondata that contains extra
 4859: correction information that isn't representable in the bubble sheet
 4860: file (see &scantron_getfile() for more information)
 4861: 
 4862: After all scanlines are either valid, marked as valid or skipped, then
 4863: foreach line foreach problem in the picked sequence, an ssi request is
 4864: made that simulates a user submitting their selected letter(s) against
 4865: the homework problem.
 4866: 
 4867: =over 4
 4868: 
 4869: 
 4870: 
 4871: =item defaultFormData
 4872: 
 4873:   Returns html hidden inputs used to hold context/default values.
 4874: 
 4875:  Arguments:
 4876:   $symb - $symb of the current resource 
 4877: 
 4878: =cut
 4879: 
 4880: sub defaultFormData {
 4881:     my ($symb)=@_;
 4882:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4883:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4884:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4885: }
 4886: 
 4887: 
 4888: =pod 
 4889: 
 4890: =item getSequenceDropDown
 4891: 
 4892:    Return html dropdown of possible sequences to grade
 4893:  
 4894:  Arguments:
 4895:    $symb - $symb of the current resource
 4896:    $map_error - ref to scalar which will container error if
 4897:                 $navmap object is unavailable in &getSymbMap().
 4898: 
 4899: =cut
 4900: 
 4901: sub getSequenceDropDown {
 4902:     my ($symb,$map_error)=@_;
 4903:     my $result='<select name="selectpage">'."\n";
 4904:     my ($titles,$symbx) = &getSymbMap($map_error);
 4905:     if (ref($map_error)) {
 4906:         return if ($$map_error);
 4907:     }
 4908:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4909:     my $ctr=0;
 4910:     foreach (@$titles) {
 4911: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4912: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4913: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4914: 	    '>'.$showtitle.'</option>'."\n";
 4915: 	$ctr++;
 4916:     }
 4917:     $result.= '</select>';
 4918:     return $result;
 4919: }
 4920: 
 4921: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4922:                                    # key is zero-based index - 0, 1, 2 ...
 4923: 
 4924: my %first_bubble_line;             # First bubble line no. for each bubble.
 4925: 
 4926: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4927:                                    # matchresponse or rankresponse, where 
 4928:                                    # an individual response can have multiple 
 4929:                                    # lines
 4930: 
 4931: my %responsetype_per_response;     # responsetype for each response
 4932: 
 4933: # Save and restore the bubble lines array to the form env.
 4934: 
 4935: 
 4936: sub save_bubble_lines {
 4937:     foreach my $line (keys(%bubble_lines_per_response)) {
 4938: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4939: 	$env{"form.scantron.first_bubble_line.$line"} =
 4940: 	    $first_bubble_line{$line};
 4941:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4942:             $subdivided_bubble_lines{$line};
 4943:         $env{"form.scantron.responsetype.$line"} =
 4944:             $responsetype_per_response{$line};
 4945:     }
 4946: }
 4947: 
 4948: 
 4949: sub restore_bubble_lines {
 4950:     my $line = 0;
 4951:     %bubble_lines_per_response = ();
 4952:     while ($env{"form.scantron.bubblelines.$line"}) {
 4953: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4954: 	$bubble_lines_per_response{$line} = $value;
 4955: 	$first_bubble_line{$line}  =
 4956: 	    $env{"form.scantron.first_bubble_line.$line"};
 4957:         $subdivided_bubble_lines{$line} =
 4958:             $env{"form.scantron.sub_bubblelines.$line"};
 4959:         $responsetype_per_response{$line} =
 4960:             $env{"form.scantron.responsetype.$line"};
 4961: 	$line++;
 4962:     }
 4963: }
 4964: 
 4965: #  Given the parsed scanline, get the response for 
 4966: #  'answer' number n:
 4967: 
 4968: sub get_response_bubbles {
 4969:     my ($parsed_line, $response)  = @_;
 4970: 
 4971:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4972:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4973:     
 4974:     my $selected = "";
 4975: 
 4976:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4977: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4978: 	$bubble_line++;
 4979:     }
 4980:     return $selected;
 4981: }
 4982: 
 4983: =pod 
 4984: 
 4985: =item scantron_filenames
 4986: 
 4987:    Returns a list of the scantron files in the current course 
 4988: 
 4989: =cut
 4990: 
 4991: sub scantron_filenames {
 4992:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4993:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4994:     my $getpropath = 1;
 4995:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4996:                                        $getpropath);
 4997:     my @possiblenames;
 4998:     foreach my $filename (sort(@files)) {
 4999: 	($filename)=split(/&/,$filename);
 5000: 	if ($filename!~/^scantron_orig_/) { next ; }
 5001: 	$filename=~s/^scantron_orig_//;
 5002: 	push(@possiblenames,$filename);
 5003:     }
 5004:     return @possiblenames;
 5005: }
 5006: 
 5007: =pod 
 5008: 
 5009: =item scantron_uploads
 5010: 
 5011:    Returns  html drop-down list of scantron files in current course.
 5012: 
 5013:  Arguments:
 5014:    $file2grade - filename to set as selected in the dropdown
 5015: 
 5016: =cut
 5017: 
 5018: sub scantron_uploads {
 5019:     my ($file2grade) = @_;
 5020:     my $result=	'<select name="scantron_selectfile">';
 5021:     $result.="<option></option>";
 5022:     foreach my $filename (sort(&scantron_filenames())) {
 5023: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5024:     }
 5025:     $result.="</select>";
 5026:     return $result;
 5027: }
 5028: 
 5029: =pod 
 5030: 
 5031: =item scantron_scantab
 5032: 
 5033:   Returns html drop down of the scantron formats in the scantronformat.tab
 5034:   file.
 5035: 
 5036: =cut
 5037: 
 5038: sub scantron_scantab {
 5039:     my $result='<select name="scantron_format">'."\n";
 5040:     $result.='<option></option>'."\n";
 5041:     my @lines = &get_scantronformat_file();
 5042:     if (@lines > 0) {
 5043:         foreach my $line (@lines) {
 5044:             next if (($line =~ /^\#/) || ($line eq ''));
 5045: 	    my ($name,$descrip)=split(/:/,$line);
 5046: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5047:         }
 5048:     }
 5049:     $result.='</select>'."\n";
 5050:     return $result;
 5051: }
 5052: 
 5053: =pod
 5054: 
 5055: =item get_scantronformat_file
 5056: 
 5057:   Returns an array containing lines from the scantron format file for
 5058:   the domain of the course.
 5059: 
 5060:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5061:   lines are from this file.
 5062: 
 5063:   Otherwise, if a default.tab has been published in RES space by the 
 5064:   domainconfig user, lines are from this file.
 5065: 
 5066:   Otherwise, fall back to getting lines from the legacy file on the
 5067:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5068: 
 5069: =cut
 5070: 
 5071: sub get_scantronformat_file {
 5072:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5073:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5074:     my $gottab = 0;
 5075:     my @lines;
 5076:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5077:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5078:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5079:             if ($formatfile ne '-1') {
 5080:                 @lines = split("\n",$formatfile,-1);
 5081:                 $gottab = 1;
 5082:             }
 5083:         }
 5084:     }
 5085:     if (!$gottab) {
 5086:         my $confname = $cdom.'-domainconfig';
 5087:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5088:         my $formatfile =  &Apache::lonnet::getfile($default);
 5089:         if ($formatfile ne '-1') {
 5090:             @lines = split("\n",$formatfile,-1);
 5091:             $gottab = 1;
 5092:         }
 5093:     }
 5094:     if (!$gottab) {
 5095:         my @domains = &Apache::lonnet::current_machine_domains();
 5096:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5097:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5098:             @lines = <$fh>;
 5099:             close($fh);
 5100:         } else {
 5101:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5102:             @lines = <$fh>;
 5103:             close($fh);
 5104:         }
 5105:     }
 5106:     return @lines;
 5107: }
 5108: 
 5109: =pod 
 5110: 
 5111: =item scantron_CODElist
 5112: 
 5113:   Returns html drop down of the saved CODE lists from current course,
 5114:   generated from earlier printings.
 5115: 
 5116: =cut
 5117: 
 5118: sub scantron_CODElist {
 5119:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5120:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5121:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5122:     my $namechoice='<option></option>';
 5123:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5124: 	if ($name =~ /^error: 2 /) { next; }
 5125: 	if ($name =~ /^type\0/) { next; }
 5126: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5127:     }
 5128:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5129:     return $namechoice;
 5130: }
 5131: 
 5132: =pod 
 5133: 
 5134: =item scantron_CODEunique
 5135: 
 5136:   Returns the html for "Each CODE to be used once" radio.
 5137: 
 5138: =cut
 5139: 
 5140: sub scantron_CODEunique {
 5141:     my $result='<span class="LC_nobreak">
 5142:                  <label><input type="radio" name="scantron_CODEunique"
 5143:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5144:                 </span>
 5145:                 <span class="LC_nobreak">
 5146:                  <label><input type="radio" name="scantron_CODEunique"
 5147:                         value="no" />'.&mt('No').' </label>
 5148:                 </span>';
 5149:     return $result;
 5150: }
 5151: 
 5152: =pod 
 5153: 
 5154: =item scantron_selectphase
 5155: 
 5156:   Generates the initial screen to start the bubble sheet process.
 5157:   Allows for - starting a grading run.
 5158:              - downloading existing scan data (original, corrected
 5159:                                                 or skipped info)
 5160: 
 5161:              - uploading new scan data
 5162: 
 5163:  Arguments:
 5164:   $r          - The Apache request object
 5165:   $file2grade - name of the file that contain the scanned data to score
 5166: 
 5167: =cut
 5168: 
 5169: sub scantron_selectphase {
 5170:     my ($r,$file2grade) = @_;
 5171:     my ($symb)=&get_symb($r);
 5172:     if (!$symb) {return '';}
 5173:     my $map_error;
 5174:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5175:     if ($map_error) {
 5176:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5177:         return;
 5178:     }
 5179:     my $default_form_data=&defaultFormData($symb);
 5180:     my $grading_menu_button=&show_grading_menu_form($symb);
 5181:     my $file_selector=&scantron_uploads($file2grade);
 5182:     my $format_selector=&scantron_scantab();
 5183:     my $CODE_selector=&scantron_CODElist();
 5184:     my $CODE_unique=&scantron_CODEunique();
 5185:     my $result;
 5186: 
 5187:     $ssi_error = 0;
 5188: 
 5189:     # Chunk of form to prompt for a file to grade and how:
 5190: 
 5191:     $result.= '
 5192:     <br />
 5193:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5194:     <input type="hidden" name="command" value="scantron_warning" />
 5195:     '.$default_form_data.'
 5196:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5197:        '.&Apache::loncommon::start_data_table_header_row().'
 5198:             <th colspan="2">
 5199:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5200:             </th>
 5201:        '.&Apache::loncommon::end_data_table_header_row().'
 5202:        '.&Apache::loncommon::start_data_table_row().'
 5203:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5204:        '.&Apache::loncommon::end_data_table_row().'
 5205:        '.&Apache::loncommon::start_data_table_row().'
 5206:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5207:        '.&Apache::loncommon::end_data_table_row().'
 5208:        '.&Apache::loncommon::start_data_table_row().'
 5209:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5210:        '.&Apache::loncommon::end_data_table_row().'
 5211:        '.&Apache::loncommon::start_data_table_row().'
 5212:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5213:        '.&Apache::loncommon::end_data_table_row().'
 5214:        '.&Apache::loncommon::start_data_table_row().'
 5215:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5216:        '.&Apache::loncommon::end_data_table_row().'
 5217:        '.&Apache::loncommon::start_data_table_row().'
 5218: 	    <td> '.&mt('Options:').' </td>
 5219:             <td>
 5220: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5221:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5222:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5223: 	    </td>
 5224:        '.&Apache::loncommon::end_data_table_row().'
 5225:        '.&Apache::loncommon::start_data_table_row().'
 5226:             <td colspan="2">
 5227:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5228:             </td>
 5229:        '.&Apache::loncommon::end_data_table_row().'
 5230:     '.&Apache::loncommon::end_data_table().'
 5231:     </form>
 5232: ';
 5233:    
 5234:     $r->print($result);
 5235: 
 5236:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5237:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5238: 
 5239: 	# Chunk of form to prompt for a scantron file upload.
 5240: 
 5241:         $r->print('
 5242:     <br />
 5243:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5244:        '.&Apache::loncommon::start_data_table_header_row().'
 5245:             <th>
 5246:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5247:             </th>
 5248:        '.&Apache::loncommon::end_data_table_header_row().'
 5249:        '.&Apache::loncommon::start_data_table_row().'
 5250:             <td>
 5251: ');
 5252:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5253:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5254:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5255:     $r->print('
 5256:               <script type="text/javascript" language="javascript">
 5257:     function checkUpload(formname) {
 5258: 	if (formname.upfile.value == "") {
 5259: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5260: 	    return false;
 5261: 	}
 5262: 	formname.submit();
 5263:     }
 5264:               </script>
 5265: 
 5266:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5267:                 '.$default_form_data.'
 5268:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5269:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5270:                 <input name="command" value="scantronupload_save" type="hidden" />
 5271:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5272:                 <br />
 5273:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5274:               </form>
 5275: ');
 5276: 
 5277:         $r->print('
 5278:             </td>
 5279:        '.&Apache::loncommon::end_data_table_row().'
 5280:        '.&Apache::loncommon::end_data_table().'
 5281: ');
 5282:     }
 5283: 
 5284:     # Chunk of the form that prompts to view a scoring office file,
 5285:     # corrected file, skipped records in a file.
 5286: 
 5287:     $r->print('
 5288:    <br />
 5289:    <form action="/adm/grades" name="scantron_download">
 5290:      '.$default_form_data.'
 5291:      <input type="hidden" name="command" value="scantron_download" />
 5292:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5293:        '.&Apache::loncommon::start_data_table_header_row().'
 5294:               <th>
 5295:                 &nbsp;'.&mt('Download a scoring office file').'
 5296:               </th>
 5297:        '.&Apache::loncommon::end_data_table_header_row().'
 5298:        '.&Apache::loncommon::start_data_table_row().'
 5299:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5300:                 <br />
 5301:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5302:        '.&Apache::loncommon::end_data_table_row().'
 5303:      '.&Apache::loncommon::end_data_table().'
 5304:    </form>
 5305:    <br />
 5306: ');
 5307: 
 5308:     &Apache::lonpickcode::code_list($r,2);
 5309: 
 5310:     $r->print('<br /><form method="post" name="checkscantron">'.
 5311:              $default_form_data."\n".
 5312:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5313:              &Apache::loncommon::start_data_table_header_row()."\n".
 5314:              '<th colspan="2">
 5315:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5316:              '</th>'."\n".
 5317:               &Apache::loncommon::end_data_table_header_row()."\n".
 5318:               &Apache::loncommon::start_data_table_row()."\n".
 5319:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5320:               '<td> '.$sequence_selector.' </td>'.
 5321:               &Apache::loncommon::end_data_table_row()."\n".
 5322:               &Apache::loncommon::start_data_table_row()."\n".
 5323:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5324:               '<td> '.$file_selector.' </td>'."\n".
 5325:               &Apache::loncommon::end_data_table_row()."\n".
 5326:               &Apache::loncommon::start_data_table_row()."\n".
 5327:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5328:               '<td> '.$format_selector.' </td>'."\n".
 5329:               &Apache::loncommon::end_data_table_row()."\n".
 5330:               &Apache::loncommon::start_data_table_row()."\n".
 5331:               '<td> '.&mt('Options').' </td>'."\n".
 5332:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5333:               &Apache::loncommon::end_data_table_row()."\n".
 5334:               &Apache::loncommon::start_data_table_row()."\n".
 5335:               '<td colspan="2">'."\n".
 5336:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5337:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5338:               '</td>'."\n".
 5339:               &Apache::loncommon::end_data_table_row()."\n".
 5340:               &Apache::loncommon::end_data_table()."\n".
 5341:               '</form><br />');
 5342:     $r->print($grading_menu_button);
 5343:     return;
 5344: }
 5345: 
 5346: =pod
 5347: 
 5348: =item get_scantron_config
 5349: 
 5350:    Parse and return the scantron configuration line selected as a
 5351:    hash of configuration file fields.
 5352: 
 5353:  Arguments:
 5354:     which - the name of the configuration to parse from the file.
 5355: 
 5356: 
 5357:  Returns:
 5358:             If the named configuration is not in the file, an empty
 5359:             hash is returned.
 5360:     a hash with the fields
 5361:       name         - internal name for the this configuration setup
 5362:       description  - text to display to operator that describes this config
 5363:       CODElocation - if 0 or the string 'none'
 5364:                           - no CODE exists for this config
 5365:                      if -1 || the string 'letter'
 5366:                           - a CODE exists for this config and is
 5367:                             a string of letters
 5368:                      Unsupported value (but planned for future support)
 5369:                           if a positive integer
 5370:                                - The CODE exists as the first n items from
 5371:                                  the question section of the form
 5372:                           if the string 'number'
 5373:                                - The CODE exists for this config and is
 5374:                                  a string of numbers
 5375:       CODEstart   - (only matter if a CODE exists) column in the line where
 5376:                      the CODE starts
 5377:       CODElength  - length of the CODE
 5378:       IDstart     - column where the student/employee ID starts
 5379:       IDlength    - length of the student/employee ID info
 5380:       Qstart      - column where the information from the bubbled
 5381:                     'questions' start
 5382:       Qlength     - number of columns comprising a single bubble line from
 5383:                     the sheet. (usually either 1 or 10)
 5384:       Qon         - either a single character representing the character used
 5385:                     to signal a bubble was chosen in the positional setup, or
 5386:                     the string 'letter' if the letter of the chosen bubble is
 5387:                     in the final, or 'number' if a number representing the
 5388:                     chosen bubble is in the file (1->A 0->J)
 5389:       Qoff        - the character used to represent that a bubble was
 5390:                     left blank
 5391:       PaperID     - if the scanning process generates a unique number for each
 5392:                     sheet scanned the column that this ID number starts in
 5393:       PaperIDlength - number of columns that comprise the unique ID number
 5394:                       for the sheet of paper
 5395:       FirstName   - column that the first name starts in
 5396:       FirstNameLength - number of columns that the first name spans
 5397:  
 5398:       LastName    - column that the last name starts in
 5399:       LastNameLength - number of columns that the last name spans
 5400: 
 5401: =cut
 5402: 
 5403: sub get_scantron_config {
 5404:     my ($which) = @_;
 5405:     my @lines = &get_scantronformat_file();
 5406:     my %config;
 5407:     #FIXME probably should move to XML it has already gotten a bit much now
 5408:     foreach my $line (@lines) {
 5409: 	my ($name,$descrip)=split(/:/,$line);
 5410: 	if ($name ne $which ) { next; }
 5411: 	chomp($line);
 5412: 	my @config=split(/:/,$line);
 5413: 	$config{'name'}=$config[0];
 5414: 	$config{'description'}=$config[1];
 5415: 	$config{'CODElocation'}=$config[2];
 5416: 	$config{'CODEstart'}=$config[3];
 5417: 	$config{'CODElength'}=$config[4];
 5418: 	$config{'IDstart'}=$config[5];
 5419: 	$config{'IDlength'}=$config[6];
 5420: 	$config{'Qstart'}=$config[7];
 5421:  	$config{'Qlength'}=$config[8];
 5422: 	$config{'Qoff'}=$config[9];
 5423: 	$config{'Qon'}=$config[10];
 5424: 	$config{'PaperID'}=$config[11];
 5425: 	$config{'PaperIDlength'}=$config[12];
 5426: 	$config{'FirstName'}=$config[13];
 5427: 	$config{'FirstNamelength'}=$config[14];
 5428: 	$config{'LastName'}=$config[15];
 5429: 	$config{'LastNamelength'}=$config[16];
 5430: 	last;
 5431:     }
 5432:     return %config;
 5433: }
 5434: 
 5435: =pod 
 5436: 
 5437: =item username_to_idmap
 5438: 
 5439:     creates a hash keyed by student/employee ID with values of the corresponding
 5440:     student username:domain.
 5441: 
 5442:   Arguments:
 5443: 
 5444:     $classlist - reference to the class list hash. This is a hash
 5445:                  keyed by student name:domain  whose elements are references
 5446:                  to arrays containing various chunks of information
 5447:                  about the student. (See loncoursedata for more info).
 5448: 
 5449:   Returns
 5450:     %idmap - the constructed hash
 5451: 
 5452: =cut
 5453: 
 5454: sub username_to_idmap {
 5455:     my ($classlist)= @_;
 5456:     my %idmap;
 5457:     foreach my $student (keys(%$classlist)) {
 5458: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5459: 	    $student;
 5460:     }
 5461:     return %idmap;
 5462: }
 5463: 
 5464: =pod
 5465: 
 5466: =item scantron_fixup_scanline
 5467: 
 5468:    Process a requested correction to a scanline.
 5469: 
 5470:   Arguments:
 5471:     $scantron_config   - hash from &get_scantron_config()
 5472:     $scan_data         - hash of correction information 
 5473:                           (see &scantron_getfile())
 5474:     $line              - existing scanline
 5475:     $whichline         - line number of the passed in scanline
 5476:     $field             - type of change to process 
 5477:                          (either 
 5478:                           'ID'     -> correct the student/employee ID
 5479:                           'CODE'   -> correct the CODE
 5480:                           'answer' -> fixup the submitted answers)
 5481:     
 5482:    $args               - hash of additional info,
 5483:                           - 'ID' 
 5484:                                'newid' -> studentID to use in replacement
 5485:                                           of existing one
 5486:                           - 'CODE' 
 5487:                                'CODE_ignore_dup' - set to true if duplicates
 5488:                                                    should be ignored.
 5489: 	                       'CODE' - is new code or 'use_unfound'
 5490:                                         if the existing unfound code should
 5491:                                         be used as is
 5492:                           - 'answer'
 5493:                                'response' - new answer or 'none' if blank
 5494:                                'question' - the bubble line to change
 5495:                                'questionnum' - the question identifier,
 5496:                                                may include subquestion. 
 5497: 
 5498:   Returns:
 5499:     $line - the modified scanline
 5500: 
 5501:   Side effects: 
 5502:     $scan_data - may be updated
 5503: 
 5504: =cut
 5505: 
 5506: 
 5507: sub scantron_fixup_scanline {
 5508:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5509:     if ($field eq 'ID') {
 5510: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5511: 	    return ($line,1,'New value too large');
 5512: 	}
 5513: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5514: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5515: 				     $args->{'newid'});
 5516: 	}
 5517: 	substr($line,$$scantron_config{'IDstart'}-1,
 5518: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5519: 	if ($args->{'newid'}=~/^\s*$/) {
 5520: 	    &scan_data($scan_data,"$whichline.user",
 5521: 		       $args->{'username'}.':'.$args->{'domain'});
 5522: 	}
 5523:     } elsif ($field eq 'CODE') {
 5524: 	if ($args->{'CODE_ignore_dup'}) {
 5525: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5526: 	}
 5527: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5528: 	if ($args->{'CODE'} ne 'use_unfound') {
 5529: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5530: 		return ($line,1,'New CODE value too large');
 5531: 	    }
 5532: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5533: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5534: 	    }
 5535: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5536: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5537: 	}
 5538:     } elsif ($field eq 'answer') {
 5539: 	my $length=$scantron_config->{'Qlength'};
 5540: 	my $off=$scantron_config->{'Qoff'};
 5541: 	my $on=$scantron_config->{'Qon'};
 5542: 	my $answer=${off}x$length;
 5543: 	if ($args->{'response'} eq 'none') {
 5544: 	    &scan_data($scan_data,
 5545: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5546: 	} else {
 5547: 	    if ($on eq 'letter') {
 5548: 		my @alphabet=('A'..'Z');
 5549: 		$answer=$alphabet[$args->{'response'}];
 5550: 	    } elsif ($on eq 'number') {
 5551: 		$answer=$args->{'response'}+1;
 5552: 		if ($answer == 10) { $answer = '0'; }
 5553: 	    } else {
 5554: 		substr($answer,$args->{'response'},1)=$on;
 5555: 	    }
 5556: 	    &scan_data($scan_data,
 5557: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5558: 	}
 5559: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5560: 	substr($line,$where-1,$length)=$answer;
 5561:     }
 5562:     return $line;
 5563: }
 5564: 
 5565: =pod
 5566: 
 5567: =item scan_data
 5568: 
 5569:     Edit or look up  an item in the scan_data hash.
 5570: 
 5571:   Arguments:
 5572:     $scan_data  - The hash (see scantron_getfile)
 5573:     $key        - shorthand of the key to edit (actual key is
 5574:                   scantronfilename_key).
 5575:     $data        - New value of the hash entry.
 5576:     $delete      - If true, the entry is removed from the hash.
 5577: 
 5578:   Returns:
 5579:     The new value of the hash table field (undefined if deleted).
 5580: 
 5581: =cut
 5582: 
 5583: 
 5584: sub scan_data {
 5585:     my ($scan_data,$key,$value,$delete)=@_;
 5586:     my $filename=$env{'form.scantron_selectfile'};
 5587:     if (defined($value)) {
 5588: 	$scan_data->{$filename.'_'.$key} = $value;
 5589:     }
 5590:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5591:     return $scan_data->{$filename.'_'.$key};
 5592: }
 5593: 
 5594: # ----- These first few routines are general use routines.----
 5595: 
 5596: # Return the number of occurences of a pattern in a string.
 5597: 
 5598: sub occurence_count {
 5599:     my ($string, $pattern) = @_;
 5600: 
 5601:     my @matches = ($string =~ /$pattern/g);
 5602: 
 5603:     return scalar(@matches);
 5604: }
 5605: 
 5606: 
 5607: # Take a string known to have digits and convert all the
 5608: # digits into letters in the range J,A..I.
 5609: 
 5610: sub digits_to_letters {
 5611:     my ($input) = @_;
 5612: 
 5613:     my @alphabet = ('J', 'A'..'I');
 5614: 
 5615:     my @input    = split(//, $input);
 5616:     my $output ='';
 5617:     for (my $i = 0; $i < scalar(@input); $i++) {
 5618: 	if ($input[$i] =~ /\d/) {
 5619: 	    $output .= $alphabet[$input[$i]];
 5620: 	} else {
 5621: 	    $output .= $input[$i];
 5622: 	}
 5623:     }
 5624:     return $output;
 5625: }
 5626: 
 5627: =pod 
 5628: 
 5629: =item scantron_parse_scanline
 5630: 
 5631:   Decodes a scanline from the selected scantron file
 5632: 
 5633:  Arguments:
 5634:     line             - The text of the scantron file line to process
 5635:     whichline        - Line number
 5636:     scantron_config  - Hash describing the format of the scantron lines.
 5637:     scan_data        - Hash of extra information about the scanline
 5638:                        (see scantron_getfile for more information)
 5639:     just_header      - True if should not process question answers but only
 5640:                        the stuff to the left of the answers.
 5641:  Returns:
 5642:    Hash containing the result of parsing the scanline
 5643: 
 5644:    Keys are all proceeded by the string 'scantron.'
 5645: 
 5646:        CODE    - the CODE in use for this scanline
 5647:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5648:                  by the operator
 5649:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5650:                             CODEs were selected, but the usage has been
 5651:                             forced by the operator
 5652:        ID  - student/employee ID
 5653:        PaperID - if used, the ID number printed on the sheet when the 
 5654:                  paper was scanned
 5655:        FirstName - first name from the sheet
 5656:        LastName  - last name from the sheet
 5657: 
 5658:      if just_header was not true these key may also exist
 5659: 
 5660:        missingerror - a list of bubble ranges that are considered to be answers
 5661:                       to a single question that don't have any bubbles filled in.
 5662:                       Of the form questionnumber:firstbubblenumber:count.
 5663:        doubleerror  - a list of bubble ranges that are considered to be answers
 5664:                       to a single question that have more than one bubble filled in.
 5665:                       Of the form questionnumber::firstbubblenumber:count
 5666:    
 5667:                 In the above, count is the number of bubble responses in the
 5668:                 input line needed to represent the possible answers to the question.
 5669:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5670:                 per line would have count = 2.
 5671: 
 5672:        maxquest     - the number of the last bubble line that was parsed
 5673: 
 5674:        (<number> starts at 1)
 5675:        <number>.answer - zero or more letters representing the selected
 5676:                          letters from the scanline for the bubble line 
 5677:                          <number>.
 5678:                          if blank there was either no bubble or there where
 5679:                          multiple bubbles, (consult the keys missingerror and
 5680:                          doubleerror if this is an error condition)
 5681: 
 5682: =cut
 5683: 
 5684: sub scantron_parse_scanline {
 5685:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5686: 
 5687:     my %record;
 5688:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5689:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5690:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5691:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5692: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5693: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5694: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5695: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5696: 	    $record{'scantron.CODE'}=substr($data,
 5697: 					    $$scantron_config{'CODEstart'}-1,
 5698: 					    $$scantron_config{'CODElength'});
 5699: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5700: 		$record{'scantron.useCODE'}=1;
 5701: 	    }
 5702: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5703: 		$record{'scantron.CODE_ignore_dup'}=1;
 5704: 	    }
 5705: 	} else {
 5706: 	    #FIXME interpret first N questions
 5707: 	}
 5708:     }
 5709:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5710: 				  $$scantron_config{'IDlength'});
 5711:     $record{'scantron.PaperID'}=
 5712: 	substr($data,$$scantron_config{'PaperID'}-1,
 5713: 	       $$scantron_config{'PaperIDlength'});
 5714:     $record{'scantron.FirstName'}=
 5715: 	substr($data,$$scantron_config{'FirstName'}-1,
 5716: 	       $$scantron_config{'FirstNamelength'});
 5717:     $record{'scantron.LastName'}=
 5718: 	substr($data,$$scantron_config{'LastName'}-1,
 5719: 	       $$scantron_config{'LastNamelength'});
 5720:     if ($just_header) { return \%record; }
 5721: 
 5722:     my @alphabet=('A'..'Z');
 5723:     my $questnum=0;
 5724:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5725: 
 5726:     chomp($questions);		# Get rid of any trailing \n.
 5727:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5728:     while (length($questions)) {
 5729: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5730:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5731:                              || 1;
 5732:         $questnum++;
 5733:         my $quest_id = $questnum;
 5734:         my $currentquest = substr($questions,0,$answer_length);
 5735:         $questions       = substr($questions,$answer_length);
 5736:         if (length($currentquest) < $answer_length) { next; }
 5737: 
 5738:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5739:             my $subquestnum = 1;
 5740:             my $subquestions = $currentquest;
 5741:             my @subanswers_needed = 
 5742:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5743:             foreach my $subans (@subanswers_needed) {
 5744:                 my $subans_length =
 5745:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5746:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5747:                 $subquestions   = substr($subquestions,$subans_length);
 5748:                 $quest_id = "$questnum.$subquestnum";
 5749:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5750:                     ($$scantron_config{'Qon'} eq 'number')) {
 5751:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5752:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5753:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5754:                 } else {
 5755:                     $ansnum = &scantron_validator_positional($ansnum,
 5756:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5757:                 }
 5758:                 $subquestnum ++;
 5759:             }
 5760:         } else {
 5761:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5762:                 ($$scantron_config{'Qon'} eq 'number')) {
 5763:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5764:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5765:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5766:             } else {
 5767:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5768:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5769:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5770:             }
 5771:         }
 5772:     }
 5773:     $record{'scantron.maxquest'}=$questnum;
 5774:     return \%record;
 5775: }
 5776: 
 5777: sub scantron_validator_lettnum {
 5778:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5779:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5780: 
 5781:     # Qon 'letter' implies for each slot in currquest we have:
 5782:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5783:     #    about anything else (esp. a value of Qoff) for missing
 5784:     #    bubbles.
 5785:     #
 5786:     # Qon 'number' implies each slot gives a digit that indexes the
 5787:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5788:     #    and * or ? for double bubbles on a single line.
 5789:     #
 5790: 
 5791:     my $matchon;
 5792:     if ($$scantron_config{'Qon'} eq 'letter') {
 5793:         $matchon = '[A-Z]';
 5794:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5795:         $matchon = '\d';
 5796:     }
 5797:     my $occurrences = 0;
 5798:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5799:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5800:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5801:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5802:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5803:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5804:         my @singlelines = split('',$currquest);
 5805:         foreach my $entry (@singlelines) {
 5806:             $occurrences = &occurence_count($entry,$matchon);
 5807:             if ($occurrences > 1) {
 5808:                 last;
 5809:             }
 5810:         } 
 5811:     } else {
 5812:         $occurrences = &occurence_count($currquest,$matchon); 
 5813:     }
 5814:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5815:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5816:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5817:             my $bubble = substr($currquest,$ans,1);
 5818:             if ($bubble =~ /$matchon/ ) {
 5819:                 if ($$scantron_config{'Qon'} eq 'number') {
 5820:                     if ($bubble == 0) {
 5821:                         $bubble = 10; 
 5822:                     }
 5823:                     $record->{"scantron.$ansnum.answer"} = 
 5824:                         $alphabet->[$bubble-1];
 5825:                 } else {
 5826:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5827:                 }
 5828:             } else {
 5829:                 $record->{"scantron.$ansnum.answer"}='';
 5830:             }
 5831:             $ansnum++;
 5832:         }
 5833:     } elsif (!defined($currquest)
 5834:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5835:             || (&occurence_count($currquest,$matchon) == 0)) {
 5836:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5837:             $record->{"scantron.$ansnum.answer"}='';
 5838:             $ansnum++;
 5839:         }
 5840:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5841:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5842:         }
 5843:     } else {
 5844:         if ($$scantron_config{'Qon'} eq 'number') {
 5845:             $currquest = &digits_to_letters($currquest);            
 5846:         }
 5847:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5848:             my $bubble = substr($currquest,$ans,1);
 5849:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5850:             $ansnum++;
 5851:         }
 5852:     }
 5853:     return $ansnum;
 5854: }
 5855: 
 5856: sub scantron_validator_positional {
 5857:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5858:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5859: 
 5860:     # Otherwise there's a positional notation;
 5861:     # each bubble line requires Qlength items, and there are filled in
 5862:     # bubbles for each case where there 'Qon' characters.
 5863:     #
 5864: 
 5865:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5866: 
 5867:     # If the split only gives us one element.. the full length of the
 5868:     # answer string, no bubbles are filled in:
 5869: 
 5870:     if ($answers_needed eq '') {
 5871:         return;
 5872:     }
 5873: 
 5874:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5875:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5876:             $record->{"scantron.$ansnum.answer"}='';
 5877:             $ansnum++;
 5878:         }
 5879:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5880:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5881:         }
 5882:     } elsif (scalar(@array) == 2) {
 5883:         my $location = length($array[0]);
 5884:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5885:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5886:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5887:             if ($ans eq $line_num) {
 5888:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5889:             } else {
 5890:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5891:             }
 5892:             $ansnum++;
 5893:          }
 5894:     } else {
 5895:         #  If there's more than one instance of a bubble character
 5896:         #  That's a double bubble; with positional notation we can
 5897:         #  record all the bubbles filled in as well as the
 5898:         #  fact this response consists of multiple bubbles.
 5899:         #
 5900:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5901:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5902:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5903:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5904:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5905:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5906:             my $doubleerror = 0;
 5907:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5908:                    (!$doubleerror)) {
 5909:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5910:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5911:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5912:                if (length(@currarray) > 2) {
 5913:                    $doubleerror = 1;
 5914:                } 
 5915:             }
 5916:             if ($doubleerror) {
 5917:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5918:             }
 5919:         } else {
 5920:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5921:         }
 5922:         my $item = $ansnum;
 5923:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5924:             $record->{"scantron.$item.answer"} = '';
 5925:             $item ++;
 5926:         }
 5927: 
 5928:         my @ans=@array;
 5929:         my $i=0;
 5930:         my $increment = 0;
 5931:         while ($#ans) {
 5932:             $i+=length($ans[0]) + $increment;
 5933:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5934:             my $bubble = $i%$$scantron_config{'Qlength'};
 5935:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5936:             shift(@ans);
 5937:             $increment = 1;
 5938:         }
 5939:         $ansnum += $answers_needed;
 5940:     }
 5941:     return $ansnum;
 5942: }
 5943: 
 5944: =pod
 5945: 
 5946: =item scantron_add_delay
 5947: 
 5948:    Adds an error message that occurred during the grading phase to a
 5949:    queue of messages to be shown after grading pass is complete
 5950: 
 5951:  Arguments:
 5952:    $delayqueue  - arrary ref of hash ref of error messages
 5953:    $scanline    - the scanline that caused the error
 5954:    $errormesage - the error message
 5955:    $errorcode   - a numeric code for the error
 5956: 
 5957:  Side Effects:
 5958:    updates the $delayqueue to have a new hash ref of the error
 5959: 
 5960: =cut
 5961: 
 5962: sub scantron_add_delay {
 5963:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5964:     push(@$delayqueue,
 5965: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5966: 	  'ecode' => $errorcode }
 5967: 	 );
 5968: }
 5969: 
 5970: =pod
 5971: 
 5972: =item scantron_find_student
 5973: 
 5974:    Finds the username for the current scanline
 5975: 
 5976:   Arguments:
 5977:    $scantron_record - hash result from scantron_parse_scanline
 5978:    $scan_data       - hash of correction information 
 5979:                       (see &scantron_getfile() form more information)
 5980:    $idmap           - hash from &username_to_idmap()
 5981:    $line            - number of current scanline
 5982:  
 5983:   Returns:
 5984:    Either 'username:domain' or undef if unknown
 5985: 
 5986: =cut
 5987: 
 5988: sub scantron_find_student {
 5989:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5990:     my $scanID=$$scantron_record{'scantron.ID'};
 5991:     if ($scanID =~ /^\s*$/) {
 5992:  	return &scan_data($scan_data,"$line.user");
 5993:     }
 5994:     foreach my $id (keys(%$idmap)) {
 5995:  	if (lc($id) eq lc($scanID)) {
 5996:  	    return $$idmap{$id};
 5997:  	}
 5998:     }
 5999:     return undef;
 6000: }
 6001: 
 6002: =pod
 6003: 
 6004: =item scantron_filter
 6005: 
 6006:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 6007:    hidden resources was selected
 6008: 
 6009: =cut
 6010: 
 6011: sub scantron_filter {
 6012:     my ($curres)=@_;
 6013: 
 6014:     if (ref($curres) && $curres->is_problem()) {
 6015: 	# if the user has asked to not have either hidden
 6016: 	# or 'randomout' controlled resources to be graded
 6017: 	# don't include them
 6018: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6019: 	    && $curres->randomout) {
 6020: 	    return 0;
 6021: 	}
 6022: 	return 1;
 6023:     }
 6024:     return 0;
 6025: }
 6026: 
 6027: =pod
 6028: 
 6029: =item scantron_process_corrections
 6030: 
 6031:    Gets correction information out of submitted form data and corrects
 6032:    the scanline
 6033: 
 6034: =cut
 6035: 
 6036: sub scantron_process_corrections {
 6037:     my ($r) = @_;
 6038:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6039:     my ($scanlines,$scan_data)=&scantron_getfile();
 6040:     my $classlist=&Apache::loncoursedata::get_classlist();
 6041:     my $which=$env{'form.scantron_line'};
 6042:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6043:     my ($skip,$err,$errmsg);
 6044:     if ($env{'form.scantron_skip_record'}) {
 6045: 	$skip=1;
 6046:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6047: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6048: 	    $env{'form.scantron_domain'};
 6049: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6050: 	($line,$err,$errmsg)=
 6051: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6052: 				     'ID',{'newid'=>$newid,
 6053: 				    'username'=>$env{'form.scantron_username'},
 6054: 				    'domain'=>$env{'form.scantron_domain'}});
 6055:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6056: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6057: 	my $newCODE;
 6058: 	my %args;
 6059: 	if      ($resolution eq 'use_unfound') {
 6060: 	    $newCODE='use_unfound';
 6061: 	} elsif ($resolution eq 'use_found') {
 6062: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6063: 	} elsif ($resolution eq 'use_typed') {
 6064: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6065: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6066: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6067: 	}
 6068: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6069: 	    $args{'CODE_ignore_dup'}=1;
 6070: 	}
 6071: 	$args{'CODE'}=$newCODE;
 6072: 	($line,$err,$errmsg)=
 6073: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6074: 				     'CODE',\%args);
 6075:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6076: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6077: 	    ($line,$err,$errmsg)=
 6078: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6079: 					 $which,'answer',
 6080: 					 { 'question'=>$question,
 6081: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6082:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6083: 	    if ($err) { last; }
 6084: 	}
 6085:     }
 6086:     if ($err) {
 6087: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6088:     } else {
 6089: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6090: 	&scantron_putfile($scanlines,$scan_data);
 6091:     }
 6092: }
 6093: 
 6094: =pod
 6095: 
 6096: =item reset_skipping_status
 6097: 
 6098:    Forgets the current set of remember skipped scanlines (and thus
 6099:    reverts back to considering all lines in the
 6100:    scantron_skipped_<filename> file)
 6101: 
 6102: =cut
 6103: 
 6104: sub reset_skipping_status {
 6105:     my ($scanlines,$scan_data)=&scantron_getfile();
 6106:     &scan_data($scan_data,'remember_skipping',undef,1);
 6107:     &scantron_putfile(undef,$scan_data);
 6108: }
 6109: 
 6110: =pod
 6111: 
 6112: =item start_skipping
 6113: 
 6114:    Marks a scanline to be skipped. 
 6115: 
 6116: =cut
 6117: 
 6118: sub start_skipping {
 6119:     my ($scan_data,$i)=@_;
 6120:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6121:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6122: 	$remembered{$i}=2;
 6123:     } else {
 6124: 	$remembered{$i}=1;
 6125:     }
 6126:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item should_be_skipped
 6132: 
 6133:    Checks whether a scanline should be skipped.
 6134: 
 6135: =cut
 6136: 
 6137: sub should_be_skipped {
 6138:     my ($scanlines,$scan_data,$i)=@_;
 6139:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6140: 	# not redoing old skips
 6141: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6142: 	return 0;
 6143:     }
 6144:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6145: 
 6146:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6147: 	return 0;
 6148:     }
 6149:     return 1;
 6150: }
 6151: 
 6152: =pod
 6153: 
 6154: =item remember_current_skipped
 6155: 
 6156:    Discovers what scanlines are in the scantron_skipped_<filename>
 6157:    file and remembers them into scan_data for later use.
 6158: 
 6159: =cut
 6160: 
 6161: sub remember_current_skipped {
 6162:     my ($scanlines,$scan_data)=&scantron_getfile();
 6163:     my %to_remember;
 6164:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6165: 	if ($scanlines->{'skipped'}[$i]) {
 6166: 	    $to_remember{$i}=1;
 6167: 	}
 6168:     }
 6169: 
 6170:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6171:     &scantron_putfile(undef,$scan_data);
 6172: }
 6173: 
 6174: =pod
 6175: 
 6176: =item check_for_error
 6177: 
 6178:     Checks if there was an error when attempting to remove a specific
 6179:     scantron_.. bubble sheet data file. Prints out an error if
 6180:     something went wrong.
 6181: 
 6182: =cut
 6183: 
 6184: sub check_for_error {
 6185:     my ($r,$result)=@_;
 6186:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6187: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6188:     }
 6189: }
 6190: 
 6191: =pod
 6192: 
 6193: =item scantron_warning_screen
 6194: 
 6195:    Interstitial screen to make sure the operator has selected the
 6196:    correct options before we start the validation phase.
 6197: 
 6198: =cut
 6199: 
 6200: sub scantron_warning_screen {
 6201:     my ($button_text)=@_;
 6202:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6204:     my $CODElist;
 6205:     if ($scantron_config{'CODElocation'} &&
 6206: 	$scantron_config{'CODEstart'} &&
 6207: 	$scantron_config{'CODElength'}) {
 6208: 	$CODElist=$env{'form.scantron_CODElist'};
 6209: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6210: 	$CODElist=
 6211: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6212: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6213:     }
 6214:     return ('
 6215: <p>
 6216: <span class="LC_warning">
 6217: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6218: </p>
 6219: <table>
 6220: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6221: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6222: '.$CODElist.'
 6223: </table>
 6224: <br />
 6225: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6226: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6227: 
 6228: <br />
 6229: ');
 6230: }
 6231: 
 6232: =pod
 6233: 
 6234: =item scantron_do_warning
 6235: 
 6236:    Check if the operator has picked something for all required
 6237:    fields. Error out if something is missing.
 6238: 
 6239: =cut
 6240: 
 6241: sub scantron_do_warning {
 6242:     my ($r)=@_;
 6243:     my ($symb)=&get_symb($r);
 6244:     if (!$symb) {return '';}
 6245:     my $default_form_data=&defaultFormData($symb);
 6246:     $r->print(&scantron_form_start().$default_form_data);
 6247:     if ( $env{'form.selectpage'} eq '' ||
 6248: 	 $env{'form.scantron_selectfile'} eq '' ||
 6249: 	 $env{'form.scantron_format'} eq '' ) {
 6250: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6251: 	if ( $env{'form.selectpage'} eq '') {
 6252: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6253: 	} 
 6254: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6255: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6256: 	} 
 6257: 	if ( $env{'form.scantron_format'} eq '') {
 6258: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6259: 	} 
 6260:     } else {
 6261: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6262: 	$r->print('
 6263: '.$warning.'
 6264: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6265: <input type="hidden" name="command" value="scantron_validate" />
 6266: ');
 6267:     }
 6268:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6269:     return '';
 6270: }
 6271: 
 6272: =pod
 6273: 
 6274: =item scantron_form_start
 6275: 
 6276:     html hidden input for remembering all selected grading options
 6277: 
 6278: =cut
 6279: 
 6280: sub scantron_form_start {
 6281:     my ($max_bubble)=@_;
 6282:     my $result= <<SCANTRONFORM;
 6283: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6284:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6285:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6286:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6287:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6288:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6289:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6290:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6291:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6292:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6293: SCANTRONFORM
 6294: 
 6295:   my $line = 0;
 6296:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6297:        my $chunk =
 6298: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6299:        $chunk .=
 6300: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6301:        $chunk .= 
 6302:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6303:        $chunk .=
 6304:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6305:        $result .= $chunk;
 6306:        $line++;
 6307:    }
 6308:     return $result;
 6309: }
 6310: 
 6311: =pod
 6312: 
 6313: =item scantron_validate_file
 6314: 
 6315:     Dispatch routine for doing validation of a bubble sheet data file.
 6316: 
 6317:     Also processes any necessary information resets that need to
 6318:     occur before validation begins (ignore previous corrections,
 6319:     restarting the skipped records processing)
 6320: 
 6321: =cut
 6322: 
 6323: sub scantron_validate_file {
 6324:     my ($r) = @_;
 6325:     my ($symb)=&get_symb($r);
 6326:     if (!$symb) {return '';}
 6327:     my $default_form_data=&defaultFormData($symb);
 6328:     
 6329:     # do the detection of only doing skipped records first befroe we delete
 6330:     # them when doing the corrections reset
 6331:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6332: 	&reset_skipping_status();
 6333:     }
 6334:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6335: 	&remember_current_skipped();
 6336: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6337:     }
 6338: 
 6339:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6340: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6341: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6342: 	&check_for_error($r,&scantron_remove_scan_data());
 6343: 	$env{'form.scantron_options_ignore'}='done';
 6344:     }
 6345: 
 6346:     if ($env{'form.scantron_corrections'}) {
 6347: 	&scantron_process_corrections($r);
 6348:     }
 6349:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6350:     #get the student pick code ready
 6351:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6352:     my $nav_error;
 6353:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6354:     if ($nav_error) {
 6355:         $r->print(&navmap_errormsg());
 6356:         return '';
 6357:     }
 6358:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6359:     $r->print($result);
 6360:     
 6361:     my @validate_phases=( 'sequence',
 6362: 			  'ID',
 6363: 			  'CODE',
 6364: 			  'doublebubble',
 6365: 			  'missingbubbles');
 6366:     if (!$env{'form.validatepass'}) {
 6367: 	$env{'form.validatepass'} = 0;
 6368:     }
 6369:     my $currentphase=$env{'form.validatepass'};
 6370: 
 6371: 
 6372:     my $stop=0;
 6373:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6374: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6375: 	$r->rflush();
 6376: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6377: 	{
 6378: 	    no strict 'refs';
 6379: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6380: 	}
 6381:     }
 6382:     if (!$stop) {
 6383: 	my $warning=&scantron_warning_screen('Start Grading');
 6384: 	$r->print(&mt('Validation process complete.').'<br />'.
 6385:                   $warning.
 6386:                   &mt('Perform verification for each student after storage of submissions?').
 6387:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6388:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6389:                   ('&nbsp;'x3).'<label>'.
 6390:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6391:                   '</label></span><br />'.
 6392:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6393:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6394:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6395:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6396:     } else {
 6397: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6398: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6399:     }
 6400:     if ($stop) {
 6401: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6402: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6403: 	    $r->print(' '.&mt('this error').' <br />');
 6404: 
 6405: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6406: 	} else {
 6407:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6408: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6409:             } else {
 6410:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6411:             }
 6412: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6413: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6414: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6415: 	}
 6416:     }
 6417:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6418:     return '';
 6419: }
 6420: 
 6421: 
 6422: =pod
 6423: 
 6424: =item scantron_remove_file
 6425: 
 6426:    Removes the requested bubble sheet data file, makes sure that
 6427:    scantron_original_<filename> is never removed
 6428: 
 6429: 
 6430: =cut
 6431: 
 6432: sub scantron_remove_file {
 6433:     my ($which)=@_;
 6434:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6435:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6436:     my $file='scantron_';
 6437:     if ($which eq 'corrected' || $which eq 'skipped') {
 6438: 	$file.=$which.'_';
 6439:     } else {
 6440: 	return 'refused';
 6441:     }
 6442:     $file.=$env{'form.scantron_selectfile'};
 6443:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6444: }
 6445: 
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_remove_scan_data
 6450: 
 6451:    Removes all scan_data correction for the requested bubble sheet
 6452:    data file.  (In the case that both the are doing skipped records we need
 6453:    to remember the old skipped lines for the time being so that element
 6454:    persists for a while.)
 6455: 
 6456: =cut
 6457: 
 6458: sub scantron_remove_scan_data {
 6459:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6460:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6461:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6462:     my @todelete;
 6463:     my $filename=$env{'form.scantron_selectfile'};
 6464:     foreach my $key (@keys) {
 6465: 	if ($key=~/^\Q$filename\E_/) {
 6466: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6467: 		$key=~/remember_skipping/) {
 6468: 		next;
 6469: 	    }
 6470: 	    push(@todelete,$key);
 6471: 	}
 6472:     }
 6473:     my $result;
 6474:     if (@todelete) {
 6475: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6476: 				       \@todelete,$cdom,$cname);
 6477:     } else {
 6478: 	$result = 'ok';
 6479:     }
 6480:     return $result;
 6481: }
 6482: 
 6483: 
 6484: =pod
 6485: 
 6486: =item scantron_getfile
 6487: 
 6488:     Fetches the requested bubble sheet data file (all 3 versions), and
 6489:     the scan_data hash
 6490:   
 6491:   Arguments:
 6492:     None
 6493: 
 6494:   Returns:
 6495:     2 hash references
 6496: 
 6497:      - first one has 
 6498:          orig      -
 6499:          corrected -
 6500:          skipped   -  each of which points to an array ref of the specified
 6501:                       file broken up into individual lines
 6502:          count     - number of scanlines
 6503:  
 6504:      - second is the scan_data hash possible keys are
 6505:        ($number refers to scanline numbered $number and thus the key affects
 6506:         only that scanline
 6507:         $bubline refers to the specific bubble line element and the aspects
 6508:         refers to that specific bubble line element)
 6509: 
 6510:        $number.user - username:domain to use
 6511:        $number.CODE_ignore_dup 
 6512:                     - ignore the duplicate CODE error 
 6513:        $number.useCODE
 6514:                     - use the CODE in the scanline as is
 6515:        $number.no_bubble.$bubline
 6516:                     - it is valid that there is no bubbled in bubble
 6517:                       at $number $bubline
 6518:        remember_skipping
 6519:                     - a frozen hash containing keys of $number and values
 6520:                       of either 
 6521:                         1 - we are on a 'do skipped records pass' and plan
 6522:                             on processing this line
 6523:                         2 - we are on a 'do skipped records pass' and this
 6524:                             scanline has been marked to skip yet again
 6525: 
 6526: =cut
 6527: 
 6528: sub scantron_getfile {
 6529:     #FIXME really would prefer a scantron directory
 6530:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6531:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6532:     my $lines;
 6533:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6534: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6535:     my %scanlines;
 6536:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6537:     my $temp=$scanlines{'orig'};
 6538:     $scanlines{'count'}=$#$temp;
 6539: 
 6540:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6541: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6542:     if ($lines eq '-1') {
 6543: 	$scanlines{'corrected'}=[];
 6544:     } else {
 6545: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6546:     }
 6547:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6548: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6549:     if ($lines eq '-1') {
 6550: 	$scanlines{'skipped'}=[];
 6551:     } else {
 6552: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6553:     }
 6554:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6555:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6556:     my %scan_data = @tmp;
 6557:     return (\%scanlines,\%scan_data);
 6558: }
 6559: 
 6560: =pod
 6561: 
 6562: =item lonnet_putfile
 6563: 
 6564:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6565: 
 6566:  Arguments:
 6567:    $contents - data to store
 6568:    $filename - filename to store $contents into
 6569: 
 6570:  Returns:
 6571:    result value from &Apache::lonnet::finishuserfileupload
 6572: 
 6573: =cut
 6574: 
 6575: sub lonnet_putfile {
 6576:     my ($contents,$filename)=@_;
 6577:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6578:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6579:     $env{'form.sillywaytopassafilearound'}=$contents;
 6580:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6581: 
 6582: }
 6583: 
 6584: =pod
 6585: 
 6586: =item scantron_putfile
 6587: 
 6588:     Stores the current version of the bubble sheet data files, and the
 6589:     scan_data hash. (Does not modify the original version only the
 6590:     corrected and skipped versions.
 6591: 
 6592:  Arguments:
 6593:     $scanlines - hash ref that looks like the first return value from
 6594:                  &scantron_getfile()
 6595:     $scan_data - hash ref that looks like the second return value from
 6596:                  &scantron_getfile()
 6597: 
 6598: =cut
 6599: 
 6600: sub scantron_putfile {
 6601:     my ($scanlines,$scan_data) = @_;
 6602:     #FIXME really would prefer a scantron directory
 6603:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6604:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6605:     if ($scanlines) {
 6606: 	my $prefix='scantron_';
 6607: # no need to update orig, shouldn't change
 6608: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6609: #		    $env{'form.scantron_selectfile'});
 6610: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6611: 			$prefix.'corrected_'.
 6612: 			$env{'form.scantron_selectfile'});
 6613: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6614: 			$prefix.'skipped_'.
 6615: 			$env{'form.scantron_selectfile'});
 6616:     }
 6617:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6618: }
 6619: 
 6620: =pod
 6621: 
 6622: =item scantron_get_line
 6623: 
 6624:    Returns the correct version of the scanline
 6625: 
 6626:  Arguments:
 6627:     $scanlines - hash ref that looks like the first return value from
 6628:                  &scantron_getfile()
 6629:     $scan_data - hash ref that looks like the second return value from
 6630:                  &scantron_getfile()
 6631:     $i         - number of the requested line (starts at 0)
 6632: 
 6633:  Returns:
 6634:    A scanline, (either the original or the corrected one if it
 6635:    exists), or undef if the requested scanline should be
 6636:    skipped. (Either because it's an skipped scanline, or it's an
 6637:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6638:    pass.
 6639: 
 6640: =cut
 6641: 
 6642: sub scantron_get_line {
 6643:     my ($scanlines,$scan_data,$i)=@_;
 6644:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6645:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6646:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6647:     return $scanlines->{'orig'}[$i]; 
 6648: }
 6649: 
 6650: =pod
 6651: 
 6652: =item scantron_todo_count
 6653: 
 6654:     Counts the number of scanlines that need processing.
 6655: 
 6656:  Arguments:
 6657:     $scanlines - hash ref that looks like the first return value from
 6658:                  &scantron_getfile()
 6659:     $scan_data - hash ref that looks like the second return value from
 6660:                  &scantron_getfile()
 6661: 
 6662:  Returns:
 6663:     $count - number of scanlines to process
 6664: 
 6665: =cut
 6666: 
 6667: sub get_todo_count {
 6668:     my ($scanlines,$scan_data)=@_;
 6669:     my $count=0;
 6670:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6671: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6672: 	if ($line=~/^[\s\cz]*$/) { next; }
 6673: 	$count++;
 6674:     }
 6675:     return $count;
 6676: }
 6677: 
 6678: =pod
 6679: 
 6680: =item scantron_put_line
 6681: 
 6682:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6683:     data file.
 6684: 
 6685:  Arguments:
 6686:     $scanlines - hash ref that looks like the first return value from
 6687:                  &scantron_getfile()
 6688:     $scan_data - hash ref that looks like the second return value from
 6689:                  &scantron_getfile()
 6690:     $i         - line number to update
 6691:     $newline   - contents of the updated scanline
 6692:     $skip      - if true make the line for skipping and update the
 6693:                  'skipped' file
 6694: 
 6695: =cut
 6696: 
 6697: sub scantron_put_line {
 6698:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6699:     if ($skip) {
 6700: 	$scanlines->{'skipped'}[$i]=$newline;
 6701: 	&start_skipping($scan_data,$i);
 6702: 	return;
 6703:     }
 6704:     $scanlines->{'corrected'}[$i]=$newline;
 6705: }
 6706: 
 6707: =pod
 6708: 
 6709: =item scantron_clear_skip
 6710: 
 6711:    Remove a line from the 'skipped' file
 6712: 
 6713:  Arguments:
 6714:     $scanlines - hash ref that looks like the first return value from
 6715:                  &scantron_getfile()
 6716:     $scan_data - hash ref that looks like the second return value from
 6717:                  &scantron_getfile()
 6718:     $i         - line number to update
 6719: 
 6720: =cut
 6721: 
 6722: sub scantron_clear_skip {
 6723:     my ($scanlines,$scan_data,$i)=@_;
 6724:     if (exists($scanlines->{'skipped'}[$i])) {
 6725: 	undef($scanlines->{'skipped'}[$i]);
 6726: 	return 1;
 6727:     }
 6728:     return 0;
 6729: }
 6730: 
 6731: =pod
 6732: 
 6733: =item scantron_filter_not_exam
 6734: 
 6735:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6736:    filter out resources that are not marked as 'exam' mode
 6737: 
 6738: =cut
 6739: 
 6740: sub scantron_filter_not_exam {
 6741:     my ($curres)=@_;
 6742:     
 6743:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6744: 	# if the user has asked to not have either hidden
 6745: 	# or 'randomout' controlled resources to be graded
 6746: 	# don't include them
 6747: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6748: 	    && $curres->randomout) {
 6749: 	    return 0;
 6750: 	}
 6751: 	return 1;
 6752:     }
 6753:     return 0;
 6754: }
 6755: 
 6756: =pod
 6757: 
 6758: =item scantron_validate_sequence
 6759: 
 6760:     Validates the selected sequence, checking for resource that are
 6761:     not set to exam mode.
 6762: 
 6763: =cut
 6764: 
 6765: sub scantron_validate_sequence {
 6766:     my ($r,$currentphase) = @_;
 6767: 
 6768:     my $navmap=Apache::lonnavmaps::navmap->new();
 6769:     unless (ref($navmap)) {
 6770:         $r->print(&navmap_errormsg());
 6771:         return (1,$currentphase);
 6772:     }
 6773:     my (undef,undef,$sequence)=
 6774: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6775: 
 6776:     my $map=$navmap->getResourceByUrl($sequence);
 6777: 
 6778:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6779:                                     value="ignore" />');
 6780:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6781: 	my @resources=
 6782: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6783: 	if (@resources) {
 6784: 	    $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>");
 6785: 	    return (1,$currentphase);
 6786: 	}
 6787:     }
 6788: 
 6789:     return (0,$currentphase+1);
 6790: }
 6791: 
 6792: 
 6793: 
 6794: sub scantron_validate_ID {
 6795:     my ($r,$currentphase) = @_;
 6796:     
 6797:     #get student info
 6798:     my $classlist=&Apache::loncoursedata::get_classlist();
 6799:     my %idmap=&username_to_idmap($classlist);
 6800: 
 6801:     #get scantron line setup
 6802:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6803:     my ($scanlines,$scan_data)=&scantron_getfile();
 6804: 
 6805:     my $nav_error;
 6806:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6807:     if ($nav_error) {
 6808:         $r->print(&navmap_errormsg());
 6809:         return(1,$currentphase);
 6810:     }
 6811: 
 6812:     my %found=('ids'=>{},'usernames'=>{});
 6813:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6814: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6815: 	if ($line=~/^[\s\cz]*$/) { next; }
 6816: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6817: 						 $scan_data);
 6818: 	my $id=$$scan_record{'scantron.ID'};
 6819: 	my $found;
 6820: 	foreach my $checkid (keys(%idmap)) {
 6821: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6822: 	}
 6823: 	if ($found) {
 6824: 	    my $username=$idmap{$found};
 6825: 	    if ($found{'ids'}{$found}) {
 6826: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6827: 					 $line,'duplicateID',$found);
 6828: 		return(1,$currentphase);
 6829: 	    } elsif ($found{'usernames'}{$username}) {
 6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6831: 					 $line,'duplicateID',$username);
 6832: 		return(1,$currentphase);
 6833: 	    }
 6834: 	    #FIXME store away line we previously saw the ID on to use above
 6835: 	    $found{'ids'}{$found}++;
 6836: 	    $found{'usernames'}{$username}++;
 6837: 	} else {
 6838: 	    if ($id =~ /^\s*$/) {
 6839: 		my $username=&scan_data($scan_data,"$i.user");
 6840: 		if (defined($username) && $found{'usernames'}{$username}) {
 6841: 		    &scantron_get_correction($r,$i,$scan_record,
 6842: 					     \%scantron_config,
 6843: 					     $line,'duplicateID',$username);
 6844: 		    return(1,$currentphase);
 6845: 		} elsif (!defined($username)) {
 6846: 		    &scantron_get_correction($r,$i,$scan_record,
 6847: 					     \%scantron_config,
 6848: 					     $line,'incorrectID');
 6849: 		    return(1,$currentphase);
 6850: 		}
 6851: 		$found{'usernames'}{$username}++;
 6852: 	    } else {
 6853: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6854: 					 $line,'incorrectID');
 6855: 		return(1,$currentphase);
 6856: 	    }
 6857: 	}
 6858:     }
 6859: 
 6860:     return (0,$currentphase+1);
 6861: }
 6862: 
 6863: 
 6864: sub scantron_get_correction {
 6865:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6866: #FIXME in the case of a duplicated ID the previous line, probably need
 6867: #to show both the current line and the previous one and allow skipping
 6868: #the previous one or the current one
 6869: 
 6870:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6871: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6872: 			    " for PaperID <tt>[_1]</tt>",
 6873: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6874:     } else {
 6875: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6876: 			    " in scanline [_1] <pre>[_2]</pre>",
 6877: 			    $i,$line)."</p> \n");
 6878:     }
 6879:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6880: 			  "The name on the paper is [_2],[_3]",
 6881: 			  $$scan_record{'scantron.ID'},
 6882: 			  $$scan_record{'scantron.LastName'},
 6883: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6884: 
 6885:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6886:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6887:                            # Array populated for doublebubble or
 6888:     my @lines_to_correct;  # missingbubble errors to build javascript
 6889:                            # to validate radio button checking   
 6890: 
 6891:     if ($error =~ /ID$/) {
 6892: 	if ($error eq 'incorrectID') {
 6893: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6894: 		      "</p>\n");
 6895: 	} elsif ($error eq 'duplicateID') {
 6896: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6897: 	}
 6898: 	$r->print($message);
 6899: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6900: 	$r->print("\n<ul><li> ");
 6901: 	#FIXME it would be nice if this sent back the user ID and
 6902: 	#could do partial userID matches
 6903: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6904: 				       'scantron_username','scantron_domain'));
 6905: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6906: 	$r->print("\n@".
 6907: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6908: 
 6909: 	$r->print('</li>');
 6910:     } elsif ($error =~ /CODE$/) {
 6911: 	if ($error eq 'incorrectCODE') {
 6912: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6913: 	} elsif ($error eq 'duplicateCODE') {
 6914: 	    $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");
 6915: 	}
 6916: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6917: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6918: 	$r->print($message);
 6919: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6920: 	$r->print("\n<br /> ");
 6921: 	my $i=0;
 6922: 	if ($error eq 'incorrectCODE' 
 6923: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6924: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6925: 	    if ($closest > 0) {
 6926: 		foreach my $testcode (@{$closest}) {
 6927: 		    my $checked='';
 6928: 		    if (!$i) { $checked=' checked="checked"'; }
 6929: 		    $r->print("
 6930:    <label>
 6931:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6932:        ".&mt("Use the similar CODE [_1] instead.",
 6933: 	    "<b><tt>".$testcode."</tt></b>")."
 6934:     </label>
 6935:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6936: 		    $r->print("\n<br />");
 6937: 		    $i++;
 6938: 		}
 6939: 	    }
 6940: 	}
 6941: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6942: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6943: 	    $r->print("
 6944:     <label>
 6945:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6946:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6947: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6948:     </label>");
 6949: 	    $r->print("\n<br />");
 6950: 	}
 6951: 
 6952: 	$r->print(<<ENDSCRIPT);
 6953: <script type="text/javascript">
 6954: function change_radio(field) {
 6955:     var slct=document.scantronupload.scantron_CODE_resolution;
 6956:     var i;
 6957:     for (i=0;i<slct.length;i++) {
 6958:         if (slct[i].value==field) { slct[i].checked=true; }
 6959:     }
 6960: }
 6961: </script>
 6962: ENDSCRIPT
 6963: 	my $href="/adm/pickcode?".
 6964: 	   "form=".&escape("scantronupload").
 6965: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6966: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6967: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6968: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6969: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6970: 	    $r->print("
 6971:     <label>
 6972:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6973:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6974: 	     "<a target='_blank' href='$href'>","</a>")."
 6975:     </label> 
 6976:     ".&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\')" />'));
 6977: 	    $r->print("\n<br />");
 6978: 	}
 6979: 	$r->print("
 6980:     <label>
 6981:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6982:        ".&mt("Use [_1] as the CODE.",
 6983: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6984: 	$r->print("\n<br /><br />");
 6985:     } elsif ($error eq 'doublebubble') {
 6986: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6987: 
 6988: 	# The form field scantron_questions is acutally a list of line numbers.
 6989: 	# represented by this form so:
 6990: 
 6991: 	my $line_list = &questions_to_line_list($arg);
 6992: 
 6993: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6994: 		  $line_list.'" />');
 6995: 	$r->print($message);
 6996: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6997: 	foreach my $question (@{$arg}) {
 6998: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6999:                                                    $scan_record, $error);
 7000:             push(@lines_to_correct,@linenums);
 7001: 	}
 7002:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7003:     } elsif ($error eq 'missingbubble') {
 7004: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 7005: 	$r->print($message);
 7006: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 7007: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 7008: 
 7009: 	# The form field scantron_questions is actually a list of line numbers not
 7010: 	# a list of question numbers. Therefore:
 7011: 	#
 7012: 	
 7013: 	my $line_list = &questions_to_line_list($arg);
 7014: 
 7015: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 7016: 		  $line_list.'" />');
 7017: 	foreach my $question (@{$arg}) {
 7018: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 7019:                                                    $scan_record, $error);
 7020:             push(@lines_to_correct,@linenums);
 7021: 	}
 7022:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7023:     } else {
 7024: 	$r->print("\n<ul>");
 7025:     }
 7026:     $r->print("\n</li></ul>");
 7027: }
 7028: 
 7029: sub verify_bubbles_checked {
 7030:     my (@ansnums) = @_;
 7031:     my $ansnumstr = join('","',@ansnums);
 7032:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7033:     my $output = (<<ENDSCRIPT);
 7034: <script type="text/javascript">
 7035: function verify_bubble_radio(form) {
 7036:     var ansnumArray = new Array ("$ansnumstr");
 7037:     var need_bubble_count = 0;
 7038:     for (var i=0; i<ansnumArray.length; i++) {
 7039:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7040:             var bubble_picked = 0; 
 7041:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7042:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7043:                     bubble_picked = 1;
 7044:                 }
 7045:             }
 7046:             if (bubble_picked == 0) {
 7047:                 need_bubble_count ++;
 7048:             }
 7049:         }
 7050:     }
 7051:     if (need_bubble_count) {
 7052:         alert("$warning");
 7053:         return;
 7054:     }
 7055:     form.submit(); 
 7056: }
 7057: </script>
 7058: ENDSCRIPT
 7059:     return $output;
 7060: }
 7061: 
 7062: =pod
 7063: 
 7064: =item  questions_to_line_list
 7065: 
 7066: Converts a list of questions into a string of comma separated
 7067: line numbers in the answer sheet used by the questions.  This is
 7068: used to fill in the scantron_questions form field.
 7069: 
 7070:   Arguments:
 7071:      questions    - Reference to an array of questions.
 7072: 
 7073: =cut
 7074: 
 7075: 
 7076: sub questions_to_line_list {
 7077:     my ($questions) = @_;
 7078:     my @lines;
 7079: 
 7080:     foreach my $item (@{$questions}) {
 7081:         my $question = $item;
 7082:         my ($first,$count,$last);
 7083:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7084:             $question = $1;
 7085:             my $subquestion = $2;
 7086:             $first = $first_bubble_line{$question-1} + 1;
 7087:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7088:             my $subcount = 1;
 7089:             while ($subcount<$subquestion) {
 7090:                 $first += $subans[$subcount-1];
 7091:                 $subcount ++;
 7092:             }
 7093:             $count = $subans[$subquestion-1];
 7094:         } else {
 7095: 	    $first   = $first_bubble_line{$question-1} + 1;
 7096: 	    $count   = $bubble_lines_per_response{$question-1};
 7097:         }
 7098:         $last = $first+$count-1;
 7099:         push(@lines, ($first..$last));
 7100:     }
 7101:     return join(',', @lines);
 7102: }
 7103: 
 7104: =pod 
 7105: 
 7106: =item prompt_for_corrections
 7107: 
 7108: Prompts for a potentially multiline correction to the
 7109: user's bubbling (factors out common code from scantron_get_correction
 7110: for multi and missing bubble cases).
 7111: 
 7112:  Arguments:
 7113:    $r           - Apache request object.
 7114:    $question    - The question number to prompt for.
 7115:    $scan_config - The scantron file configuration hash.
 7116:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7117:    $error       - Type of error
 7118: 
 7119:  Implicit inputs:
 7120:    %bubble_lines_per_response   - Starting line numbers for each question.
 7121:                                   Numbered from 0 (but question numbers are from
 7122:                                   1.
 7123:    %first_bubble_line           - Starting bubble line for each question.
 7124:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7125:                                   type problems render as separate sub-questions, 
 7126:                                   in exam mode. This hash contains a 
 7127:                                   comma-separated list of the lines per 
 7128:                                   sub-question.
 7129:    %responsetype_per_response   - essayresponse, formularesponse,
 7130:                                   stringresponse, imageresponse, reactionresponse,
 7131:                                   and organicresponse type problem parts can have
 7132:                                   multiple lines per response if the weight
 7133:                                   assigned exceeds 10.  In this case, only
 7134:                                   one bubble per line is permitted, but more 
 7135:                                   than one line might contain bubbles, e.g.
 7136:                                   bubbling of: line 1 - J, line 2 - J, 
 7137:                                   line 3 - B would assign 22 points.  
 7138: 
 7139: =cut
 7140: 
 7141: sub prompt_for_corrections {
 7142:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7143:     my ($current_line,$lines);
 7144:     my @linenums;
 7145:     my $questionnum = $question;
 7146:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7147:         $question = $1;
 7148:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7149:         my $subquestion = $2;
 7150:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7151:         my $subcount = 1;
 7152:         while ($subcount<$subquestion) {
 7153:             $current_line += $subans[$subcount-1];
 7154:             $subcount ++;
 7155:         }
 7156:         $lines = $subans[$subquestion-1];
 7157:     } else {
 7158:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7159:         $lines        = $bubble_lines_per_response{$question-1};
 7160:     }
 7161:     if ($lines > 1) {
 7162:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7163:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7164:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7165:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7166:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7167:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7168:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7169:             $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 />');
 7170:         } else {
 7171:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7172:         }
 7173:     }
 7174:     for (my $i =0; $i < $lines; $i++) {
 7175:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7176: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7177: 	        		  $questionnum,$error,split('', $selected));
 7178:         push(@linenums,$current_line);
 7179: 	$current_line++;
 7180:     }
 7181:     if ($lines > 1) {
 7182: 	$r->print("<hr /><br />");
 7183:     }
 7184:     return @linenums;
 7185: }
 7186: 
 7187: =pod
 7188: 
 7189: =item scantron_bubble_selector
 7190:   
 7191:    Generates the html radiobuttons to correct a single bubble line
 7192:    possibly showing the existing the selected bubbles if known
 7193: 
 7194:  Arguments:
 7195:     $r           - Apache request object
 7196:     $scan_config - hash from &get_scantron_config()
 7197:     $line        - Number of the line being displayed.
 7198:     $questionnum - Question number (may include subquestion)
 7199:     $error       - Type of error.
 7200:     @selected    - Array of bubbles picked on this line.
 7201: 
 7202: =cut
 7203: 
 7204: sub scantron_bubble_selector {
 7205:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7206:     my $max=$$scan_config{'Qlength'};
 7207: 
 7208:     my $scmode=$$scan_config{'Qon'};
 7209:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7210: 
 7211:     my @alphabet=('A'..'Z');
 7212:     $r->print(&Apache::loncommon::start_data_table().
 7213:               &Apache::loncommon::start_data_table_row());
 7214:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7215:     for (my $i=0;$i<$max+1;$i++) {
 7216: 	$r->print("\n".'<td align="center">');
 7217: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7218: 	else { $r->print('&nbsp;'); }
 7219: 	$r->print('</td>');
 7220:     }
 7221:     $r->print(&Apache::loncommon::end_data_table_row().
 7222:               &Apache::loncommon::start_data_table_row());
 7223:     for (my $i=0;$i<$max;$i++) {
 7224: 	$r->print("\n".
 7225: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7226: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7227:     }
 7228:     my $nobub_checked = ' ';
 7229:     if ($error eq 'missingbubble') {
 7230:         $nobub_checked = ' checked = "checked" ';
 7231:     }
 7232:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7233: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7234:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7235:               $line.'" value="'.$questionnum.'" /></td>');
 7236:     $r->print(&Apache::loncommon::end_data_table_row().
 7237:               &Apache::loncommon::end_data_table());
 7238: }
 7239: 
 7240: =pod
 7241: 
 7242: =item num_matches
 7243: 
 7244:    Counts the number of characters that are the same between the two arguments.
 7245: 
 7246:  Arguments:
 7247:    $orig - CODE from the scanline
 7248:    $code - CODE to match against
 7249: 
 7250:  Returns:
 7251:    $count - integer count of the number of same characters between the
 7252:             two arguments
 7253: 
 7254: =cut
 7255: 
 7256: sub num_matches {
 7257:     my ($orig,$code) = @_;
 7258:     my @code=split(//,$code);
 7259:     my @orig=split(//,$orig);
 7260:     my $same=0;
 7261:     for (my $i=0;$i<scalar(@code);$i++) {
 7262: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7263:     }
 7264:     return $same;
 7265: }
 7266: 
 7267: =pod
 7268: 
 7269: =item scantron_get_closely_matching_CODEs
 7270: 
 7271:    Cycles through all CODEs and finds the set that has the greatest
 7272:    number of same characters as the provided CODE
 7273: 
 7274:  Arguments:
 7275:    $allcodes - hash ref returned by &get_codes()
 7276:    $CODE     - CODE from the current scanline
 7277: 
 7278:  Returns:
 7279:    2 element list
 7280:     - first elements is number of how closely matching the best fit is 
 7281:       (5 means best set has 5 matching characters)
 7282:     - second element is an arrary ref containing the set of valid CODEs
 7283:       that best fit the passed in CODE
 7284: 
 7285: =cut
 7286: 
 7287: sub scantron_get_closely_matching_CODEs {
 7288:     my ($allcodes,$CODE)=@_;
 7289:     my @CODEs;
 7290:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7291: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7292:     }
 7293: 
 7294:     return ($#CODEs,$CODEs[-1]);
 7295: }
 7296: 
 7297: =pod
 7298: 
 7299: =item get_codes
 7300: 
 7301:    Builds a hash which has keys of all of the valid CODEs from the selected
 7302:    set of remembered CODEs.
 7303: 
 7304:  Arguments:
 7305:   $old_name - name of the set of remembered CODEs
 7306:   $cdom     - domain of the course
 7307:   $cnum     - internal course name
 7308: 
 7309:  Returns:
 7310:   %allcodes - keys are the valid CODEs, values are all 1
 7311: 
 7312: =cut
 7313: 
 7314: sub get_codes {
 7315:     my ($old_name, $cdom, $cnum) = @_;
 7316:     if (!$old_name) {
 7317: 	$old_name=$env{'form.scantron_CODElist'};
 7318:     }
 7319:     if (!$cdom) {
 7320: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7321:     }
 7322:     if (!$cnum) {
 7323: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7324:     }
 7325:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7326: 				    $cdom,$cnum);
 7327:     my %allcodes;
 7328:     if ($result{"type\0$old_name"} eq 'number') {
 7329: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7330:     } else {
 7331: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7332:     }
 7333:     return %allcodes;
 7334: }
 7335: 
 7336: =pod
 7337: 
 7338: =item scantron_validate_CODE
 7339: 
 7340:    Validates all scanlines in the selected file to not have any
 7341:    invalid or underspecified CODEs and that none of the codes are
 7342:    duplicated if this was requested.
 7343: 
 7344: =cut
 7345: 
 7346: sub scantron_validate_CODE {
 7347:     my ($r,$currentphase) = @_;
 7348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7349:     if ($scantron_config{'CODElocation'} &&
 7350: 	$scantron_config{'CODEstart'} &&
 7351: 	$scantron_config{'CODElength'}) {
 7352: 	if (!defined($env{'form.scantron_CODElist'})) {
 7353: 	    &FIXME_blow_up()
 7354: 	}
 7355:     } else {
 7356: 	return (0,$currentphase+1);
 7357:     }
 7358:     
 7359:     my %usedCODEs;
 7360: 
 7361:     my %allcodes=&get_codes();
 7362: 
 7363:     my $nav_error;
 7364:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7365:     if ($nav_error) {
 7366:         $r->print(&navmap_errormsg());
 7367:         return(1,$currentphase);
 7368:     }
 7369: 
 7370:     my ($scanlines,$scan_data)=&scantron_getfile();
 7371:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7372: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7373: 	if ($line=~/^[\s\cz]*$/) { next; }
 7374: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7375: 						 $scan_data);
 7376: 	my $CODE=$$scan_record{'scantron.CODE'};
 7377: 	my $error=0;
 7378: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7379: 	    &scantron_get_correction($r,$i,$scan_record,
 7380: 				     \%scantron_config,
 7381: 				     $line,'incorrectCODE',\%allcodes);
 7382: 	    return(1,$currentphase);
 7383: 	}
 7384: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7385: 	    && !$$scan_record{'scantron.useCODE'}) {
 7386: 	    &scantron_get_correction($r,$i,$scan_record,
 7387: 				     \%scantron_config,
 7388: 				     $line,'incorrectCODE',\%allcodes);
 7389: 	    return(1,$currentphase);
 7390: 	}
 7391: 	if (exists($usedCODEs{$CODE}) 
 7392: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7393: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7394: 	    &scantron_get_correction($r,$i,$scan_record,
 7395: 				     \%scantron_config,
 7396: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7397: 	    return(1,$currentphase);
 7398: 	}
 7399: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7400:     }
 7401:     return (0,$currentphase+1);
 7402: }
 7403: 
 7404: =pod
 7405: 
 7406: =item scantron_validate_doublebubble
 7407: 
 7408:    Validates all scanlines in the selected file to not have any
 7409:    bubble lines with multiple bubbles marked.
 7410: 
 7411: =cut
 7412: 
 7413: sub scantron_validate_doublebubble {
 7414:     my ($r,$currentphase) = @_;
 7415:     #get student info
 7416:     my $classlist=&Apache::loncoursedata::get_classlist();
 7417:     my %idmap=&username_to_idmap($classlist);
 7418: 
 7419:     #get scantron line setup
 7420:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7421:     my ($scanlines,$scan_data)=&scantron_getfile();
 7422:     my $nav_error;
 7423:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7424:     if ($nav_error) {
 7425:         $r->print(&navmap_errormsg());
 7426:         return(1,$currentphase);
 7427:     }
 7428: 
 7429:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7430: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7431: 	if ($line=~/^[\s\cz]*$/) { next; }
 7432: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7433: 						 $scan_data);
 7434: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7435: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7436: 				 'doublebubble',
 7437: 				 $$scan_record{'scantron.doubleerror'});
 7438:     	return (1,$currentphase);
 7439:     }
 7440:     return (0,$currentphase+1);
 7441: }
 7442: 
 7443: 
 7444: sub scantron_get_maxbubble {
 7445:     my ($nav_error) = @_;
 7446:     if (defined($env{'form.scantron_maxbubble'}) &&
 7447: 	$env{'form.scantron_maxbubble'}) {
 7448: 	&restore_bubble_lines();
 7449: 	return $env{'form.scantron_maxbubble'};
 7450:     }
 7451: 
 7452:     my (undef, undef, $sequence) =
 7453: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7454: 
 7455:     my $navmap=Apache::lonnavmaps::navmap->new();
 7456:     unless (ref($navmap)) {
 7457:         if (ref($nav_error)) {
 7458:             $$nav_error = 1;
 7459:         }
 7460:     }
 7461:     my $map=$navmap->getResourceByUrl($sequence);
 7462:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7463: 
 7464:     &Apache::lonxml::clear_problem_counter();
 7465: 
 7466:     my $uname       = $env{'user.name'};
 7467:     my $udom        = $env{'user.domain'};
 7468:     my $cid         = $env{'request.course.id'};
 7469:     my $total_lines = 0;
 7470:     %bubble_lines_per_response = ();
 7471:     %first_bubble_line         = ();
 7472:     %subdivided_bubble_lines   = ();
 7473:     %responsetype_per_response = ();
 7474: 
 7475:     my $response_number = 0;
 7476:     my $bubble_line     = 0;
 7477:     foreach my $resource (@resources) {
 7478:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7479:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7480: 	    foreach my $part_id (@{$parts}) {
 7481:                 my $lines;
 7482: 
 7483: 	        # TODO - make this a persistent hash not an array.
 7484: 
 7485:                 # optionresponse, matchresponse and rankresponse type items 
 7486:                 # render as separate sub-questions in exam mode.
 7487:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7488:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7489:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7490:                     my ($numbub,$numshown);
 7491:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7492:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7493:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7494:                         }
 7495:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7496:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7497:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7498:                         }
 7499:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7500:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7501:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7502:                         }
 7503:                     }
 7504:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7505:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7506:                     }
 7507:                     my $bubbles_per_line = 10;
 7508:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7509:                     if (($numbub % $bubbles_per_line) != 0) {
 7510:                         $inner_bubble_lines++;
 7511:                     }
 7512:                     for (my $i=0; $i<$numshown; $i++) {
 7513:                         $subdivided_bubble_lines{$response_number} .= 
 7514:                             $inner_bubble_lines.',';
 7515:                     }
 7516:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7517:                     $lines = $numshown * $inner_bubble_lines;
 7518:                 } else {
 7519:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7520:                 } 
 7521: 
 7522:                 $first_bubble_line{$response_number} = $bubble_line;
 7523: 	        $bubble_lines_per_response{$response_number} = $lines;
 7524:                 $responsetype_per_response{$response_number} = 
 7525:                     $analysis->{$part_id.'.type'};
 7526: 	        $response_number++;
 7527: 
 7528: 	        $bubble_line +=  $lines;
 7529: 	        $total_lines +=  $lines;
 7530: 	    }
 7531:         }
 7532:     }
 7533:     &Apache::lonnet::delenv('scantron.');
 7534: 
 7535:     &save_bubble_lines();
 7536:     $env{'form.scantron_maxbubble'} =
 7537: 	$total_lines;
 7538:     return $env{'form.scantron_maxbubble'};
 7539: }
 7540: 
 7541: sub scantron_validate_missingbubbles {
 7542:     my ($r,$currentphase) = @_;
 7543:     #get student info
 7544:     my $classlist=&Apache::loncoursedata::get_classlist();
 7545:     my %idmap=&username_to_idmap($classlist);
 7546: 
 7547:     #get scantron line setup
 7548:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7549:     my ($scanlines,$scan_data)=&scantron_getfile();
 7550:     my $nav_error;
 7551:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7552:     if ($nav_error) {
 7553:         return(1,$currentphase);
 7554:     }
 7555:     if (!$max_bubble) { $max_bubble=2**31; }
 7556:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7557: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7558: 	if ($line=~/^[\s\cz]*$/) { next; }
 7559: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7560: 						 $scan_data);
 7561: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7562: 	my @to_correct;
 7563: 	
 7564: 	# Probably here's where the error is...
 7565: 
 7566: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7567:             my $lastbubble;
 7568:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7569:                my $question = $1;
 7570:                my $subquestion = $2;
 7571:                if (!defined($first_bubble_line{$question -1})) { next; }
 7572:                my $first = $first_bubble_line{$question-1};
 7573:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7574:                my $subcount = 1;
 7575:                while ($subcount<$subquestion) {
 7576:                    $first += $subans[$subcount-1];
 7577:                    $subcount ++;
 7578:                }
 7579:                my $count = $subans[$subquestion-1];
 7580:                $lastbubble = $first + $count;
 7581:             } else {
 7582:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7583:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7584:             }
 7585:             if ($lastbubble > $max_bubble) { next; }
 7586: 	    push(@to_correct,$missing);
 7587: 	}
 7588: 	if (@to_correct) {
 7589: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7590: 				     $line,'missingbubble',\@to_correct);
 7591: 	    return (1,$currentphase);
 7592: 	}
 7593: 
 7594:     }
 7595:     return (0,$currentphase+1);
 7596: }
 7597: 
 7598: 
 7599: sub scantron_process_students {
 7600:     my ($r) = @_;
 7601: 
 7602:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7603:     my ($symb)=&get_symb($r);
 7604:     if (!$symb) {
 7605: 	return '';
 7606:     }
 7607:     my $default_form_data=&defaultFormData($symb);
 7608: 
 7609:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7610:     my ($scanlines,$scan_data)=&scantron_getfile();
 7611:     my $classlist=&Apache::loncoursedata::get_classlist();
 7612:     my %idmap=&username_to_idmap($classlist);
 7613:     my $navmap=Apache::lonnavmaps::navmap->new();
 7614:     unless (ref($navmap)) {
 7615:         $r->print(&navmap_errormsg());
 7616:         return '';
 7617:     }  
 7618:     my $map=$navmap->getResourceByUrl($sequence);
 7619:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7620:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7621:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7622:                             \%grader_randomlists_by_symb);
 7623:     foreach my $resource (@resources) {
 7624:         my $ressymb = $resource->symb();
 7625:         my ($analysis,$parts) =
 7626:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7627:                                       $env{'user.name'},$env{'user.domain'},1);
 7628:         $grader_partids_by_symb{$ressymb} = $parts;
 7629:         if (ref($analysis) eq 'HASH') {
 7630:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7631:                 $grader_randomlists_by_symb{$ressymb} = 
 7632:                     $analysis->{'parts_withrandomlist'};
 7633:             }
 7634:         }
 7635:     }
 7636: 
 7637:     my ($uname,$udom);
 7638:     my $result= <<SCANTRONFORM;
 7639: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7640:   <input type="hidden" name="command" value="scantron_configphase" />
 7641:   $default_form_data
 7642: SCANTRONFORM
 7643:     $r->print($result);
 7644: 
 7645:     my @delayqueue;
 7646:     my (%completedstudents,%scandata);
 7647:     
 7648:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7649:     my $count=&get_todo_count($scanlines,$scan_data);
 7650:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7651:  				    'Bubblesheet Progress',$count,
 7652: 				    'inline',undef,'scantronupload');
 7653:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7654: 					  'Processing first student');
 7655:     $r->print('<br />');
 7656:     my $start=&Time::HiRes::time();
 7657:     my $i=-1;
 7658:     my $started;
 7659: 
 7660:     my $nav_error;
 7661:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7662:     if ($nav_error) {
 7663:         $r->print(&navmap_errormsg());
 7664:         return '';
 7665:     }
 7666: 
 7667:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7668:     # the user and return.
 7669: 
 7670:     if ($ssi_error) {
 7671: 	$r->print("</form>");
 7672: 	&ssi_print_error($r);
 7673: 	$r->print(&show_grading_menu_form($symb));
 7674:         &Apache::lonnet::remove_lock($lock);
 7675: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7676:     }
 7677: 
 7678:     my %lettdig = &letter_to_digits();
 7679:     my $numletts = scalar(keys(%lettdig));
 7680: 
 7681:     while ($i<$scanlines->{'count'}) {
 7682:  	($uname,$udom)=('','');
 7683:  	$i++;
 7684:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7685:  	if ($line=~/^[\s\cz]*$/) { next; }
 7686: 	if ($started) {
 7687: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7688: 						     'last student');
 7689: 	}
 7690: 	$started=1;
 7691:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7692:  						 $scan_data);
 7693:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7694:  					      \%idmap,$i)) {
 7695:   	    &scantron_add_delay(\@delayqueue,$line,
 7696:  				'Unable to find a student that matches',1);
 7697:  	    next;
 7698:   	}
 7699:  	if (exists $completedstudents{$uname}) {
 7700:  	    &scantron_add_delay(\@delayqueue,$line,
 7701:  				'Student '.$uname.' has multiple sheets',2);
 7702:  	    next;
 7703:  	}
 7704:   	($uname,$udom)=split(/:/,$uname);
 7705: 
 7706:         my %partids_by_symb;
 7707:         foreach my $resource (@resources) {
 7708:             my $ressymb = $resource->symb();
 7709:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7710:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7711:                 my ($analysis,$parts) =
 7712:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7713:                 $partids_by_symb{$ressymb} = $parts;
 7714:             } else {
 7715:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7716:             }
 7717:         }
 7718: 
 7719: 	&Apache::lonxml::clear_problem_counter();
 7720:   	&Apache::lonnet::appenv($scan_record);
 7721: 
 7722: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7723: 	    &scantron_putfile($scanlines,$scan_data);
 7724: 	}
 7725: 	
 7726:         my $scancode;
 7727:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7728:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7729:             $scancode = $scan_record->{'scantron.CODE'};
 7730:         } else {
 7731:             $scancode = '';
 7732:         }
 7733: 
 7734:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7735:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7736:             $ssi_error = 0; # So end of handler error message does not trigger.
 7737:             $r->print("</form>");
 7738:             &ssi_print_error($r);
 7739:             $r->print(&show_grading_menu_form($symb));
 7740:             &Apache::lonnet::remove_lock($lock);
 7741:             return '';      # Why return ''?  Beats me.
 7742:         }
 7743: 
 7744: 	$completedstudents{$uname}={'line'=>$line};
 7745:         if ($env{'form.verifyrecord'}) {
 7746:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7747:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7748:             chomp($studentdata);
 7749:             $studentdata =~ s/\r$//;
 7750:             my $studentrecord = '';
 7751:             my $counter = -1;
 7752:             foreach my $resource (@resources) {
 7753:                 my $ressymb = $resource->symb();
 7754:                 ($counter,my $recording) =
 7755:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7756:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7757:                                              \%scantron_config,\%lettdig,$numletts);
 7758:                 $studentrecord .= $recording;
 7759:             }
 7760:             if ($studentrecord ne $studentdata) {
 7761:                 &Apache::lonxml::clear_problem_counter();
 7762:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7763:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7764:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7765:                     $r->print("</form>");
 7766:                     &ssi_print_error($r);
 7767:                     $r->print(&show_grading_menu_form($symb));
 7768:                     &Apache::lonnet::remove_lock($lock);
 7769:                     delete($completedstudents{$uname});
 7770:                     return '';
 7771:                 }
 7772:                 $counter = -1;
 7773:                 $studentrecord = '';
 7774:                 foreach my $resource (@resources) {
 7775:                     my $ressymb = $resource->symb();
 7776:                     ($counter,my $recording) =
 7777:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7778:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7779:                                                  \%scantron_config,\%lettdig,$numletts);
 7780:                     $studentrecord .= $recording;
 7781:                 }
 7782:                 if ($studentrecord ne $studentdata) {
 7783:                     $r->print('<p><span class="LC_error">');
 7784:                     if ($scancode eq '') {
 7785:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7786:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7787:                     } else {
 7788:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7789:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7790:                     }
 7791:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7792:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7793:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7794:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7795:                               &Apache::loncommon::start_data_table_row().
 7796:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7797:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7798:                               &Apache::loncommon::end_data_table_row().
 7799:                               &Apache::loncommon::start_data_table_row().
 7800:                               '<td>Stored submissions</td>'.
 7801:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7802:                               &Apache::loncommon::end_data_table_row().
 7803:                               &Apache::loncommon::end_data_table().'</p>');
 7804:                 } else {
 7805:                     $r->print('<br /><span class="LC_warning">'.
 7806:                              &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 />'.
 7807:                              &mt("As a consequence, this user's submission history records two tries.").
 7808:                                  '</span><br />');
 7809:                 }
 7810:             }
 7811:         }
 7812:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7813:     } continue {
 7814: 	&Apache::lonxml::clear_problem_counter();
 7815: 	&Apache::lonnet::delenv('scantron.');
 7816:     }
 7817:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7818:     &Apache::lonnet::remove_lock($lock);
 7819: #    my $lasttime = &Time::HiRes::time()-$start;
 7820: #    $r->print("<p>took $lasttime</p>");
 7821: 
 7822:     $r->print("</form>");
 7823:     $r->print(&show_grading_menu_form($symb));
 7824:     return '';
 7825: }
 7826: 
 7827: sub graders_resources_pass {
 7828:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7829:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7830:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7831:         foreach my $resource (@{$resources}) {
 7832:             my $ressymb = $resource->symb();
 7833:             my ($analysis,$parts) =
 7834:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7835:                                           $env{'user.name'},$env{'user.domain'},1);
 7836:             $grader_partids_by_symb->{$ressymb} = $parts;
 7837:             if (ref($analysis) eq 'HASH') {
 7838:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7839:                     $grader_randomlists_by_symb->{$ressymb} =
 7840:                         $analysis->{'parts_withrandomlist'};
 7841:                 }
 7842:             }
 7843:         }
 7844:     }
 7845:     return;
 7846: }
 7847: 
 7848: sub grade_student_bubbles {
 7849:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7850:     if (ref($resources) eq 'ARRAY') {
 7851:         my $count = 0;
 7852:         foreach my $resource (@{$resources}) {
 7853:             my $ressymb = $resource->symb();
 7854:             my %form = ('submitted'      => 'scantron',
 7855:                         'grade_target'   => 'grade',
 7856:                         'grade_username' => $uname,
 7857:                         'grade_domain'   => $udom,
 7858:                         'grade_courseid' => $env{'request.course.id'},
 7859:                         'grade_symb'     => $ressymb,
 7860:                         'CODE'           => $scancode
 7861:                        );
 7862:             if (ref($parts) eq 'HASH') {
 7863:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7864:                     foreach my $part (@{$parts->{$ressymb}}) {
 7865:                         $form{'scantron_questnum_start.'.$part} =
 7866:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7867:                         $count++;
 7868:                     }
 7869:                 }
 7870:             }
 7871:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7872:             return 'ssi_error' if ($ssi_error);
 7873:             last if (&Apache::loncommon::connection_aborted($r));
 7874:         }
 7875:     }
 7876:     return;
 7877: }
 7878: 
 7879: sub scantron_upload_scantron_data {
 7880:     my ($r)=@_;
 7881:     my $dom = $env{'request.role.domain'};
 7882:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7883:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7884:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7885: 							  'domainid',
 7886: 							  'coursename',$dom);
 7887:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7888:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7889:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7890:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7891:     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.");
 7892:     $r->print('
 7893: <script type="text/javascript" language="javascript">
 7894:     function checkUpload(formname) {
 7895: 	if (formname.upfile.value == "") {
 7896: 	    alert("'.$nofile_alert.'");
 7897: 	    return false;
 7898: 	}
 7899:         if (formname.courseid.value == "") {
 7900:             alert("'.$nocourseid_alert.'");
 7901:             return false;
 7902:         }
 7903: 	formname.submit();
 7904:     }
 7905: 
 7906:     function ToSyllabus() {
 7907:         var cdom = '."'$dom'".';
 7908:         var cnum = document.rules.courseid.value;
 7909:         if (cdom == "" || cdom == null) {
 7910:             return;
 7911:         }
 7912:         if (cnum == "" || cnum == null) {
 7913:            return;
 7914:         }
 7915:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7916:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7917:         return;
 7918:     }
 7919: 
 7920: </script>
 7921: 
 7922: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7923: 
 7924: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7925: '.$default_form_data.
 7926:   &Apache::lonhtmlcommon::start_pick_box().
 7927:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7928:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7929:   &Apache::lonhtmlcommon::row_closure().
 7930:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7931:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7932:   &Apache::lonhtmlcommon::row_closure().
 7933:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7934:   '<input name="domainid" type="hidden" />'.$domdesc.
 7935:   &Apache::lonhtmlcommon::row_closure().
 7936:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7937:   '<input type="file" name="upfile" size="50" />'.
 7938:   &Apache::lonhtmlcommon::row_closure(1).
 7939:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7940: 
 7941: <input name="command" value="scantronupload_save" type="hidden" />
 7942: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7943: </form>
 7944: ');
 7945:     return '';
 7946: }
 7947: 
 7948: 
 7949: sub scantron_upload_scantron_data_save {
 7950:     my($r)=@_;
 7951:     my ($symb)=&get_symb($r,1);
 7952:     my $doanotherupload=
 7953: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7954: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7955: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7956: 	'</form>'."\n";
 7957:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7958: 	!&Apache::lonnet::allowed('usc',
 7959: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7960: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7961: 	if ($symb) {
 7962: 	    $r->print(&show_grading_menu_form($symb));
 7963: 	} else {
 7964: 	    $r->print($doanotherupload);
 7965: 	}
 7966: 	return '';
 7967:     }
 7968:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7969:     my $uploadedfile;
 7970:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7971:     if (length($env{'form.upfile'}) < 2) {
 7972:         $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>'));
 7973:     } else {
 7974:         my $result = 
 7975:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7976:                                             $env{'form.courseid'},$env{'form.domainid'});
 7977: 	if ($result =~ m{^/uploaded/}) {
 7978: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7979:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7980: 			  '<span class="LC_filename">'.$result.'</span>'));
 7981:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7982:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7983:                                                        $env{'form.courseid'},$uploadedfile));
 7984: 	} else {
 7985: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7986:                           '<span class="LC_error">','</span>',$result,
 7987: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7988: 	}
 7989:     }
 7990:     if ($symb) {
 7991: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7992:     } else {
 7993: 	$r->print($doanotherupload);
 7994:     }
 7995:     return '';
 7996: }
 7997: 
 7998: sub validate_uploaded_scantron_file {
 7999:     my ($cdom,$cname,$fname) = @_;
 8000:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 8001:     my @lines;
 8002:     if ($scanlines ne '-1') {
 8003:         @lines=split("\n",$scanlines,-1);
 8004:     }
 8005:     my $output;
 8006:     if (@lines) {
 8007:         my (%counts,$max_match_format);
 8008:         my ($max_match_count,$max_match_pct) = (0,0);
 8009:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 8010:         my %idmap = &username_to_idmap($classlist);
 8011:         foreach my $key (keys(%idmap)) {
 8012:             my $lckey = lc($key);
 8013:             $idmap{$lckey} = $idmap{$key};
 8014:         }
 8015:         my %unique_formats;
 8016:         my @formatlines = &get_scantronformat_file();
 8017:         foreach my $line (@formatlines) {
 8018:             chomp($line);
 8019:             my @config = split(/:/,$line);
 8020:             my $idstart = $config[5];
 8021:             my $idlength = $config[6];
 8022:             if (($idstart ne '') && ($idlength > 0)) {
 8023:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8024:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8025:                 } else {
 8026:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8027:                 }
 8028:             }
 8029:         }
 8030:         foreach my $key (keys(%unique_formats)) {
 8031:             my ($idstart,$idlength) = split(':',$key);
 8032:             %{$counts{$key}} = (
 8033:                                'found'   => 0,
 8034:                                'total'   => 0,
 8035:                               );
 8036:             foreach my $line (@lines) {
 8037:                 next if ($line =~ /^#/);
 8038:                 next if ($line =~ /^[\s\cz]*$/);
 8039:                 my $id = substr($line,$idstart-1,$idlength);
 8040:                 $id = lc($id);
 8041:                 if (exists($idmap{$id})) {
 8042:                     $counts{$key}{'found'} ++;
 8043:                 }
 8044:                 $counts{$key}{'total'} ++;
 8045:             }
 8046:             if ($counts{$key}{'total'}) {
 8047:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8048:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8049:                     $max_match_pct = $percent_match;
 8050:                     $max_match_format = $key;
 8051:                     $max_match_count = $counts{$key}{'total'};
 8052:                 }
 8053:             }
 8054:         }
 8055:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8056:             my $format_descs;
 8057:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8058:             for (my $i=0; $i<$numwithformat; $i++) {
 8059:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8060:                 if ($i<$numwithformat-2) {
 8061:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8062:                 } elsif ($i==$numwithformat-2) {
 8063:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8064:                 } elsif ($i==$numwithformat-1) {
 8065:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8066:                 }
 8067:             }
 8068:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8069:             $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).
 8070:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8071:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8072:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8073:                                   '<i>'.$cdom.'</i>').'</li>'.
 8074:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8075:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8076:                        '</ul>';
 8077:         }
 8078:     } else {
 8079:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8080:     }
 8081:     return $output;
 8082: }
 8083: 
 8084: sub valid_file {
 8085:     my ($requested_file)=@_;
 8086:     foreach my $filename (sort(&scantron_filenames())) {
 8087: 	if ($requested_file eq $filename) { return 1; }
 8088:     }
 8089:     return 0;
 8090: }
 8091: 
 8092: sub scantron_download_scantron_data {
 8093:     my ($r)=@_;
 8094:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8095:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8096:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8097:     my $file=$env{'form.scantron_selectfile'};
 8098:     if (! &valid_file($file)) {
 8099: 	$r->print('
 8100: 	<p>
 8101: 	    '.&mt('The requested file name was invalid.').'
 8102:         </p>
 8103: ');
 8104: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8105: 	return;
 8106:     }
 8107:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8108:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8109:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8110:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8111:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8112:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8113:     $r->print('
 8114:     <p>
 8115: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8116: 	      '<a href="'.$orig.'">','</a>').'
 8117:     </p>
 8118:     <p>
 8119: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8120: 	      '<a href="'.$corrected.'">','</a>').'
 8121:     </p>
 8122:     <p>
 8123: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8124: 	      '<a href="'.$skipped.'">','</a>').'
 8125:     </p>
 8126: ');
 8127:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8128:     return '';
 8129: }
 8130: 
 8131: sub checkscantron_results {
 8132:     my ($r) = @_;
 8133:     my ($symb)=&get_symb($r);
 8134:     if (!$symb) {return '';}
 8135:     my $grading_menu_button=&show_grading_menu_form($symb);
 8136:     my $cid = $env{'request.course.id'};
 8137:     my %lettdig = &letter_to_digits();
 8138:     my $numletts = scalar(keys(%lettdig));
 8139:     my $cnum = $env{'course.'.$cid.'.num'};
 8140:     my $cdom = $env{'course.'.$cid.'.domain'};
 8141:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8142:     my %record;
 8143:     my %scantron_config =
 8144:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8145:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8146:     my $classlist=&Apache::loncoursedata::get_classlist();
 8147:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8148:     my $navmap=Apache::lonnavmaps::navmap->new();
 8149:     unless (ref($navmap)) {
 8150:         $r->print(&navmap_errormsg());
 8151:         return '';
 8152:     }
 8153:     my $map=$navmap->getResourceByUrl($sequence);
 8154:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8155:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8156:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8157: 
 8158:     my ($uname,$udom);
 8159:     my (%scandata,%lastname,%bylast);
 8160:     $r->print('
 8161: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8162: 
 8163:     my @delayqueue;
 8164:     my %completedstudents;
 8165: 
 8166:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8167:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8168:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8169:                                     'inline',undef,'checkscantron');
 8170:     my ($username,$domain,$started);
 8171:     my $nav_error;
 8172:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8173:     if ($nav_error) {
 8174:         $r->print(&navmap_errormsg());
 8175:         return '';
 8176:     }
 8177: 
 8178:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8179:                                           'Processing first student');
 8180:     my $start=&Time::HiRes::time();
 8181:     my $i=-1;
 8182: 
 8183:     while ($i<$scanlines->{'count'}) {
 8184:         ($username,$domain,$uname)=('','','');
 8185:         $i++;
 8186:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8187:         if ($line=~/^[\s\cz]*$/) { next; }
 8188:         if ($started) {
 8189:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8190:                                                      'last student');
 8191:         }
 8192:         $started=1;
 8193:         my $scan_record=
 8194:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8195:                                                      $scan_data);
 8196:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8197:                                                               \%idmap,$i)) {
 8198:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8199:                                 'Unable to find a student that matches',1);
 8200:             next;
 8201:         }
 8202:         if (exists $completedstudents{$uname}) {
 8203:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8204:                                 'Student '.$uname.' has multiple sheets',2);
 8205:             next;
 8206:         }
 8207:         my $pid = $scan_record->{'scantron.ID'};
 8208:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8209:         push(@{$bylast{$lastname{$pid}}},$pid);
 8210:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8211:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8212:         chomp($scandata{$pid});
 8213:         $scandata{$pid} =~ s/\r$//;
 8214:         ($username,$domain)=split(/:/,$uname);
 8215:         my $counter = -1;
 8216:         foreach my $resource (@resources) {
 8217:             my $parts;
 8218:             my $ressymb = $resource->symb();
 8219:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8220:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8221:                 (my $analysis,$parts) =
 8222:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8223:             } else {
 8224:                 $parts = $grader_partids_by_symb{$ressymb};
 8225:             }
 8226:             ($counter,my $recording) =
 8227:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8228:                                          $scandata{$pid},$parts,
 8229:                                          \%scantron_config,\%lettdig,$numletts);
 8230:             $record{$pid} .= $recording;
 8231:         }
 8232:     }
 8233:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8234:     $r->print('<br />');
 8235:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8236:     $passed = 0;
 8237:     $failed = 0;
 8238:     $numstudents = 0;
 8239:     foreach my $last (sort(keys(%bylast))) {
 8240:         if (ref($bylast{$last}) eq 'ARRAY') {
 8241:             foreach my $pid (sort(@{$bylast{$last}})) {
 8242:                 my $showscandata = $scandata{$pid};
 8243:                 my $showrecord = $record{$pid};
 8244:                 $showscandata =~ s/\s/&nbsp;/g;
 8245:                 $showrecord =~ s/\s/&nbsp;/g;
 8246:                 if ($scandata{$pid} eq $record{$pid}) {
 8247:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8248:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8249: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8250: '</tr>'."\n".
 8251: '<tr class="'.$css_class.'">'."\n".
 8252: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8253:                     $passed ++;
 8254:                 } else {
 8255:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8256:                     $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".
 8257: '</tr>'."\n".
 8258: '<tr class="'.$css_class.'">'."\n".
 8259: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8260: '</tr>'."\n";
 8261:                     $failed ++;
 8262:                 }
 8263:                 $numstudents ++;
 8264:             }
 8265:         }
 8266:     }
 8267:     $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>');
 8268:     $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>');
 8269:     if ($passed) {
 8270:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8271:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8272:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8273:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8274:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8275:                  $okstudents."\n".
 8276:                  &Apache::loncommon::end_data_table().'<br />');
 8277:     }
 8278:     if ($failed) {
 8279:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8280:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8281:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8282:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8283:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8284:                  $badstudents."\n".
 8285:                  &Apache::loncommon::end_data_table()).'<br />'.
 8286:                  &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.');  
 8287:     }
 8288:     $r->print('</form><br />'.$grading_menu_button);
 8289:     return;
 8290: }
 8291: 
 8292: sub verify_scantron_grading {
 8293:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8294:         $scantron_config,$lettdig,$numletts) = @_;
 8295:     my ($record,%expected,%startpos);
 8296:     return ($counter,$record) if (!ref($resource));
 8297:     return ($counter,$record) if (!$resource->is_problem());
 8298:     my $symb = $resource->symb();
 8299:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8300:     foreach my $part_id (@{$partids}) {
 8301:         $counter ++;
 8302:         $expected{$part_id} = 0;
 8303:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8304:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8305:             foreach my $item (@sub_lines) {
 8306:                 $expected{$part_id} += $item;
 8307:             }
 8308:         } else {
 8309:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8310:         }
 8311:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8312:     }
 8313:     if ($symb) {
 8314:         my %recorded;
 8315:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8316:         if ($returnhash{'version'}) {
 8317:             my %lasthash=();
 8318:             my $version;
 8319:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8320:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8321:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8322:                 }
 8323:             }
 8324:             foreach my $key (keys(%lasthash)) {
 8325:                 if ($key =~ /\.scantron$/) {
 8326:                     my $value = &unescape($lasthash{$key});
 8327:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8328:                     if ($value eq '') {
 8329:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8330:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8331:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8332:                             }
 8333:                         }
 8334:                     } else {
 8335:                         my @tocheck;
 8336:                         my @items = split(//,$value);
 8337:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8338:                             ($scantron_config->{'Qon'} eq 'number')) {
 8339:                             if (@items < $expected{$part_id}) {
 8340:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8341:                                 my @singles = split(//,$fragment);
 8342:                                 foreach my $pos (@singles) {
 8343:                                     if ($pos eq ' ') {
 8344:                                         push(@tocheck,$pos);
 8345:                                     } else {
 8346:                                         my $next = shift(@items);
 8347:                                         push(@tocheck,$next);
 8348:                                     }
 8349:                                 }
 8350:                             } else {
 8351:                                 @tocheck = @items;
 8352:                             }
 8353:                             foreach my $letter (@tocheck) {
 8354:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8355:                                     if ($letter !~ /^[A-J]$/) {
 8356:                                         $letter = $scantron_config->{'Qoff'};
 8357:                                     }
 8358:                                     $recorded{$part_id} .= $letter;
 8359:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8360:                                     my $digit;
 8361:                                     if ($letter !~ /^[A-J]$/) {
 8362:                                         $digit = $scantron_config->{'Qoff'};
 8363:                                     } else {
 8364:                                         $digit = $lettdig->{$letter};
 8365:                                     }
 8366:                                     $recorded{$part_id} .= $digit;
 8367:                                 }
 8368:                             }
 8369:                         } else {
 8370:                             @tocheck = @items;
 8371:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8372:                                 my $curr_sub = shift(@tocheck);
 8373:                                 my $digit;
 8374:                                 if ($curr_sub =~ /^[A-J]$/) {
 8375:                                     $digit = $lettdig->{$curr_sub}-1;
 8376:                                 }
 8377:                                 if ($curr_sub eq 'J') {
 8378:                                     $digit += scalar($numletts);
 8379:                                 }
 8380:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8381:                                     if ($j == $digit) {
 8382:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8383:                                     } else {
 8384:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8385:                                     }
 8386:                                 }
 8387:                             }
 8388:                         }
 8389:                     }
 8390:                 }
 8391:             }
 8392:         }
 8393:         foreach my $part_id (@{$partids}) {
 8394:             if ($recorded{$part_id} eq '') {
 8395:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8396:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8397:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8398:                     }
 8399:                 }
 8400:             }
 8401:             $record .= $recorded{$part_id};
 8402:         }
 8403:     }
 8404:     return ($counter,$record);
 8405: }
 8406: 
 8407: sub letter_to_digits { 
 8408:     my %lettdig = (
 8409:                     A => 1,
 8410:                     B => 2,
 8411:                     C => 3,
 8412:                     D => 4,
 8413:                     E => 5,
 8414:                     F => 6,
 8415:                     G => 7,
 8416:                     H => 8,
 8417:                     I => 9,
 8418:                     J => 0,
 8419:                   );
 8420:     return %lettdig;
 8421: }
 8422: 
 8423: 
 8424: #-------- end of section for handling grading scantron forms -------
 8425: #
 8426: #-------------------------------------------------------------------
 8427: 
 8428: #-------------------------- Menu interface -------------------------
 8429: #
 8430: #--- Show a Grading Menu button - Calls the next routine ---
 8431: sub show_grading_menu_form {
 8432:     my ($symb)=@_;
 8433:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8434: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8435: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8436: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8437: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8438: 	'</form>'."\n";
 8439:     return $result;
 8440: }
 8441: 
 8442: # -- Retrieve choices for grading form
 8443: sub savedState {
 8444:     my %savedState = ();
 8445:     if ($env{'form.saveState'}) {
 8446: 	foreach (split(/:/,$env{'form.saveState'})) {
 8447: 	    my ($key,$value) = split(/=/,$_,2);
 8448: 	    $savedState{$key} = $value;
 8449: 	}
 8450:     }
 8451:     return \%savedState;
 8452: }
 8453: 
 8454: sub grading_menu {
 8455:     my ($request) = @_;
 8456:     my ($symb)=&get_symb($request);
 8457:     if (!$symb) {return '';}
 8458:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8459:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8460: 
 8461:     $request->print($table);
 8462:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8463:                   'handgrade'=>$hdgrade,
 8464:                   'probTitle'=>$probTitle,
 8465:                   'command'=>'submit_options',
 8466:                   'saveState'=>"",
 8467:                   'gradingMenu'=>1,
 8468:                   'showgrading'=>"yes");
 8469:     
 8470:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8471:     
 8472:     $fields{'command'} = 'csvform';
 8473:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8474:     
 8475:     $fields{'command'} = 'processclicker';
 8476:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8477:     
 8478:     $fields{'command'} = 'scantron_selectphase';
 8479:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8480:     
 8481:     my @menu = ({	categorytitle=>'Course Grading',
 8482:             items =>[
 8483:                         {	linktext => 'Manual Grading/View Submissions',
 8484:                     		url => $url1,
 8485:                     		permission => 'F',
 8486:                     		icon => 'edit-find-replace.png',
 8487:                     		linktitle => 'Start the process of hand grading submissions.'
 8488:                         },
 8489:                 	    {	linktext => 'Upload Scores',
 8490:                     		url => $url2,
 8491:                     		permission => 'F',
 8492:                     		icon => 'uploadscores.png',
 8493:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8494:                 	    },
 8495:                 	    {	linktext => 'Process Clicker',
 8496:                     		url => $url3,
 8497:                     		permission => 'F',
 8498:                     		icon => 'addClickerInfoFile.png',
 8499:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8500:                 	    },
 8501:                 	    {	linktext => 'Grade/Manage/Review Bubblesheet Forms',
 8502:                     		url => $url4,
 8503:                     		permission => 'F',
 8504:                     		icon => 'stat.png',
 8505:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8506:                 	    }
 8507:                     ]
 8508:             });
 8509: 
 8510:     #$fields{'command'} = 'verify';
 8511:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8512:     #
 8513:     # Create the menu
 8514:     my $Str;
 8515:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8516:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8517:     $Str .= '<input type="hidden" name="command" value="" />'.
 8518:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8519: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8520: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8521: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8522: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8523: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8524: 
 8525:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8526:     #$menudata->{'jscript'}
 8527:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8528:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8529:         ' /> '.
 8530:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8531:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8532: 
 8533:     $Str .="</form>\n";
 8534:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8535:     $request->print(<<GRADINGMENUJS);
 8536: <script type="text/javascript" language="javascript">
 8537:     function checkChoice(formname,val,cmdx) {
 8538: 	if (val <= 2) {
 8539: 	    var cmd = radioSelection(formname.radioChoice);
 8540: 	    var cmdsave = cmd;
 8541: 	} else {
 8542: 	    cmd = cmdx;
 8543: 	    cmdsave = 'submission';
 8544: 	}
 8545: 	formname.command.value = cmd;
 8546: 	if (val < 5) formname.submit();
 8547: 	if (val == 5) {
 8548: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8549: 	        return false;
 8550: 	    } else {
 8551: 	        formname.submit();
 8552: 	    }
 8553: 	}
 8554:     }
 8555: 
 8556:     function checkReceiptNo(formname,nospace) {
 8557: 	var receiptNo = formname.receipt.value;
 8558: 	var checkOpt = false;
 8559: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8560: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8561: 	if (checkOpt) {
 8562: 	    alert("$receiptalert");
 8563: 	    formname.receipt.value = "";
 8564: 	    formname.receipt.focus();
 8565: 	    return false;
 8566: 	}
 8567: 	return true;
 8568:     }
 8569: </script>
 8570: GRADINGMENUJS
 8571:     &commonJSfunctions($request);
 8572:     return $Str;    
 8573: }
 8574: 
 8575: 
 8576: #--- Displays the submissions first page -------
 8577: sub submit_options {
 8578:     my ($request) = @_;
 8579:     my ($symb)=&get_symb($request);
 8580:     if (!$symb) {return '';}
 8581:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8582: 
 8583:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8584:     $request->print(<<GRADINGMENUJS);
 8585: <script type="text/javascript" language="javascript">
 8586:     function checkChoice(formname,val,cmdx) {
 8587: 	if (val <= 2) {
 8588: 	    var cmd = radioSelection(formname.radioChoice);
 8589: 	    var cmdsave = cmd;
 8590: 	} else {
 8591: 	    cmd = cmdx;
 8592: 	    cmdsave = 'submission';
 8593: 	}
 8594: 	formname.command.value = cmd;
 8595: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8596: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8597: 	if (val < 5) formname.submit();
 8598: 	if (val == 5) {
 8599: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8600: 	    formname.submit();
 8601: 	}
 8602: 	if (val < 7) formname.submit();
 8603:     }
 8604: 
 8605:     function checkReceiptNo(formname,nospace) {
 8606: 	var receiptNo = formname.receipt.value;
 8607: 	var checkOpt = false;
 8608: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8609: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8610: 	if (checkOpt) {
 8611: 	    alert("$receiptalert");
 8612: 	    formname.receipt.value = "";
 8613: 	    formname.receipt.focus();
 8614: 	    return false;
 8615: 	}
 8616: 	return true;
 8617:     }
 8618: </script>
 8619: GRADINGMENUJS
 8620:     &commonJSfunctions($request);
 8621:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8622:     my $result;
 8623:     my (undef,$sections) = &getclasslist('all','0');
 8624:     my $savedState = &savedState();
 8625:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8626:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8627:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8628:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8629: 
 8630:     # Preselect sections
 8631:     my $selsec="";
 8632:     if (ref($sections)) {
 8633:         foreach my $section (sort(@$sections)) {
 8634:             $selsec.='<option value="'.$section.'" '.
 8635:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8636:         }
 8637:     }
 8638: 
 8639:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8640: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8641: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8642: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8643: 	'<input type="hidden" name="command"     value="" />'."\n".
 8644: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8645: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8646: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8647: 
 8648:     $result.='
 8649: <h2>
 8650:   '.&mt('Grade Current Resource').'
 8651: </h2>
 8652: <div>
 8653:   '.$table.'
 8654: </div>
 8655: 
 8656: <div class="LC_columnSection">
 8657:   
 8658:     <fieldset>
 8659:       <legend>
 8660:        '.&mt('Sections').'
 8661:       </legend>
 8662:       <select name="section" multiple="multiple" size="5">'."\n";
 8663:     $result.= $selsec;
 8664:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8665:     $result.='
 8666:     </fieldset>
 8667:   
 8668:     <fieldset>
 8669:       <legend>
 8670:         '.&mt('Groups').'
 8671:       </legend>
 8672:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8673:     </fieldset>
 8674:   
 8675:     <fieldset>
 8676:       <legend>
 8677:         '.&mt('Access Status').'
 8678:       </legend>
 8679:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8680:     </fieldset>
 8681:   
 8682:     <fieldset>
 8683:       <legend>
 8684:         '.&mt('Submission Status').'
 8685:       </legend>
 8686:       <select name="submitonly" size="5">
 8687: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8688: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8689: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8690: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8691:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8692:       </select>
 8693:     </fieldset>
 8694:   
 8695: </div>
 8696: 
 8697: <br />
 8698:           <div>
 8699:             <div>
 8700:               <label>
 8701:                 <input type="radio" name="radioChoice" value="submission" '.
 8702:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8703:              &mt('Select individual students to grade and view submissions.').'
 8704: 	      </label> 
 8705:             </div>
 8706:             <div>
 8707: 	      <label>
 8708:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8709:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8710:                     &mt('Grade all selected students in a grading table.').'
 8711:               </label>
 8712:             </div>
 8713:             <div>
 8714: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8715:             </div>
 8716:           </div>
 8717: 
 8718: 
 8719:         <h2>
 8720:          '.&mt('Grade Complete Folder for One Student').'
 8721:         </h2>
 8722:         <div>
 8723:             <div>
 8724:               <label>
 8725:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8726: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8727:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 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:   </form>';
 8735:     $result .= &show_grading_menu_form($symb);
 8736:     return $result;
 8737: }
 8738: 
 8739: sub reset_perm {
 8740:     undef(%perm);
 8741: }
 8742: 
 8743: sub init_perm {
 8744:     &reset_perm();
 8745:     foreach my $test_perm ('vgr','mgr','opa') {
 8746: 
 8747: 	my $scope = $env{'request.course.id'};
 8748: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8749: 
 8750: 	    $scope .= '/'.$env{'request.course.sec'};
 8751: 	    if ( $perm{$test_perm}=
 8752: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8753: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8754: 	    } else {
 8755: 		delete($perm{$test_perm});
 8756: 	    }
 8757: 	}
 8758:     }
 8759: }
 8760: 
 8761: sub gather_clicker_ids {
 8762:     my %clicker_ids;
 8763: 
 8764:     my $classlist = &Apache::loncoursedata::get_classlist();
 8765: 
 8766:     # Set up a couple variables.
 8767:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8768:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8769:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8770: 
 8771:     foreach my $student (keys(%$classlist)) {
 8772:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8773:         my $username = $classlist->{$student}->[$username_idx];
 8774:         my $domain   = $classlist->{$student}->[$domain_idx];
 8775:         my $clickers =
 8776: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8777:         foreach my $id (split(/\,/,$clickers)) {
 8778:             $id=~s/^[\#0]+//;
 8779:             $id=~s/[\-\:]//g;
 8780:             if (exists($clicker_ids{$id})) {
 8781: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8782:             } else {
 8783: 		$clicker_ids{$id}=$username.':'.$domain;
 8784:             }
 8785:         }
 8786:     }
 8787:     return %clicker_ids;
 8788: }
 8789: 
 8790: sub gather_adv_clicker_ids {
 8791:     my %clicker_ids;
 8792:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8793:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8794:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8795:     foreach my $element (sort(keys(%coursepersonnel))) {
 8796:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8797:             my ($puname,$pudom)=split(/\:/,$person);
 8798:             my $clickers =
 8799: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8800:             foreach my $id (split(/\,/,$clickers)) {
 8801: 		$id=~s/^[\#0]+//;
 8802:                 $id=~s/[\-\:]//g;
 8803: 		if (exists($clicker_ids{$id})) {
 8804: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8805: 		} else {
 8806: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8807: 		}
 8808:             }
 8809:         }
 8810:     }
 8811:     return %clicker_ids;
 8812: }
 8813: 
 8814: sub clicker_grading_parameters {
 8815:     return ('gradingmechanism' => 'scalar',
 8816:             'upfiletype' => 'scalar',
 8817:             'specificid' => 'scalar',
 8818:             'pcorrect' => 'scalar',
 8819:             'pincorrect' => 'scalar');
 8820: }
 8821: 
 8822: sub process_clicker {
 8823:     my ($r)=@_;
 8824:     my ($symb)=&get_symb($r);
 8825:     if (!$symb) {return '';}
 8826:     my $result=&checkforfile_js();
 8827:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8828:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8829:     $result.=$table;
 8830:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8831:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8832:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8833:         '</b></td></tr>'."\n";
 8834:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8835: # Attempt to restore parameters from last session, set defaults if not present
 8836:     my %Saveable_Parameters=&clicker_grading_parameters();
 8837:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8838:                                                  \%Saveable_Parameters);
 8839:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8840:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8841:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8842:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8843: 
 8844:     my %checked;
 8845:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8846:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8847:           $checked{$gradingmechanism}=' checked="checked"';
 8848:        }
 8849:     }
 8850: 
 8851:     my $upload=&mt("Upload File");
 8852:     my $type=&mt("Type");
 8853:     my $attendance=&mt("Award points just for participation");
 8854:     my $personnel=&mt("Correctness determined from response by course personnel");
 8855:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8856:     my $given=&mt("Correctness determined from given list of answers").' '.
 8857:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8858:     my $pcorrect=&mt("Percentage points for correct solution");
 8859:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8860:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8861: 						   ('iclicker' => 'i>clicker',
 8862:                                                     'interwrite' => 'interwrite PRS'));
 8863:     $symb = &Apache::lonenc::check_encrypt($symb);
 8864:     $result.=<<ENDUPFORM;
 8865: <script type="text/javascript">
 8866: function sanitycheck() {
 8867: // Accept only integer percentages
 8868:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8869:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8870: // Find out grading choice
 8871:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8872:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8873:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8874:       }
 8875:    }
 8876: // By default, new choice equals user selection
 8877:    newgradingchoice=gradingchoice;
 8878: // Not good to give more points for false answers than correct ones
 8879:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8880:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8881:    }
 8882: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8883:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8884:       document.forms.gradesupload.pcorrect.value=100;
 8885:       document.forms.gradesupload.pincorrect.value=100;
 8886:    }
 8887: // If the values are different, cannot be attendance only
 8888:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8889:        (gradingchoice=='attendance')) {
 8890:        newgradingchoice='personnel';
 8891:    }
 8892: // Change grading choice to new one
 8893:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8894:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8895:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8896:       } else {
 8897:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8898:       }
 8899:    }
 8900: // Remember the old state
 8901:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8902: }
 8903: </script>
 8904: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8905: <input type="hidden" name="symb" value="$symb" />
 8906: <input type="hidden" name="command" value="processclickerfile" />
 8907: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8908: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8909: <input type="file" name="upfile" size="50" />
 8910: <br /><label>$type: $selectform</label>
 8911: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8912: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8913: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8914: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8915: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8916: <br />&nbsp;&nbsp;&nbsp;
 8917: <input type="text" name="givenanswer" size="50" />
 8918: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8919: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8920: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8921: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8922: </form>
 8923: ENDUPFORM
 8924:     $result.='</td></tr></table>'."\n".
 8925:              '</td></tr></table><br /><br />'."\n";
 8926:     $result.=&show_grading_menu_form($symb);
 8927:     return $result;
 8928: }
 8929: 
 8930: sub process_clicker_file {
 8931:     my ($r)=@_;
 8932:     my ($symb)=&get_symb($r);
 8933:     if (!$symb) {return '';}
 8934: 
 8935:     my %Saveable_Parameters=&clicker_grading_parameters();
 8936:     &Apache::loncommon::store_course_settings('grades_clicker',
 8937:                                               \%Saveable_Parameters);
 8938: 
 8939:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8940:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8941: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8942: 	return $result.&show_grading_menu_form($symb);
 8943:     }
 8944:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8945:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8946:         return $result.&show_grading_menu_form($symb);
 8947:     }
 8948:     my $foundgiven=0;
 8949:     if ($env{'form.gradingmechanism'} eq 'given') {
 8950:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8951:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8952:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8953:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8954:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8955:         $foundgiven=$#answers+1;
 8956:     }
 8957:     my %clicker_ids=&gather_clicker_ids();
 8958:     my %correct_ids;
 8959:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8960: 	%correct_ids=&gather_adv_clicker_ids();
 8961:     }
 8962:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8963: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8964: 	   $correct_id=~tr/a-z/A-Z/;
 8965: 	   $correct_id=~s/\s//gs;
 8966: 	   $correct_id=~s/^[\#0]+//;
 8967:            $correct_id=~s/[\-\:]//g;
 8968:            if ($correct_id) {
 8969: 	      $correct_ids{$correct_id}='specified';
 8970:            }
 8971:         }
 8972:     }
 8973:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8974: 	$result.=&mt('Score based on attendance only');
 8975:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8976:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8977:     } else {
 8978: 	my $number=0;
 8979: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8980: 	foreach my $id (sort(keys(%correct_ids))) {
 8981: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8982: 	    if ($correct_ids{$id} eq 'specified') {
 8983: 		$result.=&mt('specified');
 8984: 	    } else {
 8985: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8986: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8987: 	    }
 8988: 	    $number++;
 8989: 	}
 8990:         $result.="</p>\n";
 8991: 	if ($number==0) {
 8992: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8993: 	    return $result.&show_grading_menu_form($symb);
 8994: 	}
 8995:     }
 8996:     if (length($env{'form.upfile'}) < 2) {
 8997:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8998: 		     '<span class="LC_error">',
 8999: 		     '</span>',
 9000: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 9001:         return $result.&show_grading_menu_form($symb);
 9002:     }
 9003: 
 9004: # Were able to get all the info needed, now analyze the file
 9005: 
 9006:     $result.=&Apache::loncommon::studentbrowser_javascript();
 9007:     $symb = &Apache::lonenc::check_encrypt($symb);
 9008:     my $heading=&mt('Scanning clicker file');
 9009:     $result.=(<<ENDHEADER);
 9010: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9011: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9012: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9013: <form method="post" action="/adm/grades" name="clickeranalysis">
 9014: <input type="hidden" name="symb" value="$symb" />
 9015: <input type="hidden" name="command" value="assignclickergrades" />
 9016: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9017: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9018: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9019: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9020: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9021: ENDHEADER
 9022:     if ($env{'form.gradingmechanism'} eq 'given') {
 9023:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9024:     } 
 9025:     my %responses;
 9026:     my @questiontitles;
 9027:     my $errormsg='';
 9028:     my $number=0;
 9029:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9030: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9031:     }
 9032:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9033:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9034:     }
 9035:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9036:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9037:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9038:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9039:              '<br />';
 9040:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9041:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9042:        return $result.&show_grading_menu_form($symb);
 9043:     } 
 9044: # Remember Question Titles
 9045: # FIXME: Possibly need delimiter other than ":"
 9046:     for (my $i=0;$i<$number;$i++) {
 9047:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9048:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9049:     }
 9050:     my $correct_count=0;
 9051:     my $student_count=0;
 9052:     my $unknown_count=0;
 9053: # Match answers with usernames
 9054: # FIXME: Possibly need delimiter other than ":"
 9055:     foreach my $id (keys(%responses)) {
 9056:        if ($correct_ids{$id}) {
 9057:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9058:           $correct_count++;
 9059:        } elsif ($clicker_ids{$id}) {
 9060:           if ($clicker_ids{$id}=~/\,/) {
 9061: # More than one user with the same clicker!
 9062:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9063:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9064:                            "<select name='multi".$id."'>";
 9065:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9066:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9067:              }
 9068:              $result.='</select>';
 9069:              $unknown_count++;
 9070:           } else {
 9071: # Good: found one and only one user with the right clicker
 9072:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9073:              $student_count++;
 9074:           }
 9075:        } else {
 9076:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9077:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9078:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9079:                    "\n".&mt("Domain").": ".
 9080:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9081:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9082:           $unknown_count++;
 9083:        }
 9084:     }
 9085:     $result.='<hr />'.
 9086:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9087:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9088:        if ($correct_count==0) {
 9089:           $errormsg.="Found no correct answers answers for grading!";
 9090:        } elsif ($correct_count>1) {
 9091:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9092:        }
 9093:     }
 9094:     if ($number<1) {
 9095:        $errormsg.="Found no questions.";
 9096:     }
 9097:     if ($errormsg) {
 9098:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9099:     } else {
 9100:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9101:     }
 9102:     $result.='</form></td></tr></table>'."\n".
 9103:              '</td></tr></table><br /><br />'."\n";
 9104:     return $result.&show_grading_menu_form($symb);
 9105: }
 9106: 
 9107: sub iclicker_eval {
 9108:     my ($questiontitles,$responses)=@_;
 9109:     my $number=0;
 9110:     my $errormsg='';
 9111:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9112:         my %components=&Apache::loncommon::record_sep($line);
 9113:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9114: 	if ($entries[0] eq 'Question') {
 9115: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9116: 		$$questiontitles[$number]=$entries[$i];
 9117: 		$number++;
 9118: 	    }
 9119: 	}
 9120: 	if ($entries[0]=~/^\#/) {
 9121: 	    my $id=$entries[0];
 9122: 	    my @idresponses;
 9123: 	    $id=~s/^[\#0]+//;
 9124: 	    for (my $i=0;$i<$number;$i++) {
 9125: 		my $idx=3+$i*6;
 9126: 		push(@idresponses,$entries[$idx]);
 9127: 	    }
 9128: 	    $$responses{$id}=join(',',@idresponses);
 9129: 	}
 9130:     }
 9131:     return ($errormsg,$number);
 9132: }
 9133: 
 9134: sub interwrite_eval {
 9135:     my ($questiontitles,$responses)=@_;
 9136:     my $number=0;
 9137:     my $errormsg='';
 9138:     my $skipline=1;
 9139:     my $questionnumber=0;
 9140:     my %idresponses=();
 9141:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9142:         my %components=&Apache::loncommon::record_sep($line);
 9143:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9144:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9145:         if ($entries[1] eq 'Response') { $skipline=1; }
 9146:         next if $skipline;
 9147:         if ($entries[0]!=$questionnumber) {
 9148:            $questionnumber=$entries[0];
 9149:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9150:            $number++;
 9151:         }
 9152:         my $id=$entries[4];
 9153:         $id=~s/^[\#0]+//;
 9154:         $id=~s/^v\d*\://i;
 9155:         $id=~s/[\-\:]//g;
 9156:         $idresponses{$id}[$number]=$entries[6];
 9157:     }
 9158:     foreach my $id (keys(%idresponses)) {
 9159:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9160:        $$responses{$id}=~s/^\s*\,//;
 9161:     }
 9162:     return ($errormsg,$number);
 9163: }
 9164: 
 9165: sub assign_clicker_grades {
 9166:     my ($r)=@_;
 9167:     my ($symb)=&get_symb($r);
 9168:     if (!$symb) {return '';}
 9169: # See which part we are saving to
 9170:     my $res_error;
 9171:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9172:     if ($res_error) {
 9173:         return &navmap_errormsg();
 9174:     }
 9175: # FIXME: This should probably look for the first handgradeable part
 9176:     my $part=$$partlist[0];
 9177: # Start screen output
 9178:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9179: 
 9180:     my $heading=&mt('Assigning grades based on clicker file');
 9181:     $result.=(<<ENDHEADER);
 9182: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9183: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9184: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9185: ENDHEADER
 9186: # Get correct result
 9187: # FIXME: Possibly need delimiter other than ":"
 9188:     my @correct=();
 9189:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9190:     my $number=$env{'form.number'};
 9191:     if ($gradingmechanism ne 'attendance') {
 9192:        foreach my $key (keys(%env)) {
 9193:           if ($key=~/^form\.correct\:/) {
 9194:              my @input=split(/\,/,$env{$key});
 9195:              for (my $i=0;$i<=$#input;$i++) {
 9196:                  if (($correct[$i]) && ($input[$i]) &&
 9197:                      ($correct[$i] ne $input[$i])) {
 9198:                     $result.='<br /><span class="LC_warning">'.
 9199:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9200:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9201:                  } elsif ($input[$i]) {
 9202:                     $correct[$i]=$input[$i];
 9203:                  }
 9204:              }
 9205:           }
 9206:        }
 9207:        for (my $i=0;$i<$number;$i++) {
 9208:           if (!$correct[$i]) {
 9209:              $result.='<br /><span class="LC_error">'.
 9210:                       &mt('No correct result given for question "[_1]"!',
 9211:                           $env{'form.question:'.$i}).'</span>';
 9212:           }
 9213:        }
 9214:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9215:     }
 9216: # Start grading
 9217:     my $pcorrect=$env{'form.pcorrect'};
 9218:     my $pincorrect=$env{'form.pincorrect'};
 9219:     my $storecount=0;
 9220:     foreach my $key (keys(%env)) {
 9221:        my $user='';
 9222:        if ($key=~/^form\.student\:(.*)$/) {
 9223:           $user=$1;
 9224:        }
 9225:        if ($key=~/^form\.unknown\:(.*)$/) {
 9226:           my $id=$1;
 9227:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9228:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9229:           } elsif ($env{'form.multi'.$id}) {
 9230:              $user=$env{'form.multi'.$id};
 9231:           }
 9232:        }
 9233:        if ($user) { 
 9234:           my @answer=split(/\,/,$env{$key});
 9235:           my $sum=0;
 9236:           my $realnumber=$number;
 9237:           for (my $i=0;$i<$number;$i++) {
 9238:              if  ($correct[$i] eq '-') {
 9239:                 $realnumber--;
 9240:              } elsif ($answer[$i]) {
 9241:                 if ($gradingmechanism eq 'attendance') {
 9242:                    $sum+=$pcorrect;
 9243:                 } elsif ($correct[$i] eq '*') {
 9244:                    $sum+=$pcorrect;
 9245:                 } else {
 9246:                    if ($answer[$i] eq $correct[$i]) {
 9247:                       $sum+=$pcorrect;
 9248:                    } else {
 9249:                       $sum+=$pincorrect;
 9250:                    }
 9251:                 }
 9252:              }
 9253:           }
 9254:           my $ave=$sum/(100*$realnumber);
 9255: # Store
 9256:           my ($username,$domain)=split(/\:/,$user);
 9257:           my %grades=();
 9258:           $grades{"resource.$part.solved"}='correct_by_override';
 9259:           $grades{"resource.$part.awarded"}=$ave;
 9260:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9261:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9262:                                                  $env{'request.course.id'},
 9263:                                                  $domain,$username);
 9264:           if ($returncode ne 'ok') {
 9265:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9266:           } else {
 9267:              $storecount++;
 9268:           }
 9269:        }
 9270:     }
 9271: # We are done
 9272:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9273:              '</td></tr></table>'."\n".
 9274:              '</td></tr></table><br /><br />'."\n";
 9275:     return $result.&show_grading_menu_form($symb);
 9276: }
 9277: 
 9278: sub navmap_errormsg {
 9279:     return '<div class="LC_error">'.
 9280:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9281:            &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>').
 9282:            '</div>';
 9283: }
 9284: 
 9285: sub handler {
 9286:     my $request=$_[0];
 9287:     &reset_caches();
 9288:     if ($env{'browser.mathml'}) {
 9289: 	&Apache::loncommon::content_type($request,'text/xml');
 9290:     } else {
 9291: 	&Apache::loncommon::content_type($request,'text/html');
 9292:     }
 9293:     $request->send_http_header;
 9294:     return '' if $request->header_only;
 9295:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9296:     my $symb=&get_symb($request,1);
 9297:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9298:     my $command=$commands[0];
 9299: 
 9300:     if ($#commands > 0) {
 9301: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9302:     }
 9303: 
 9304:     $ssi_error = 0;
 9305:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9306:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9307:                                           {'bread_crumbs' => $brcrum}));
 9308:     if ($symb eq '' && $command eq '') {
 9309: 	if ($env{'user.adv'}) {
 9310: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9311: 		($env{'form.codethree'})) {
 9312: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9313: 		    $env{'form.codethree'};
 9314: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9315: 		    &Apache::lonnet::checkin($token);
 9316: 		if ($tsymb) {
 9317: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9318: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9319: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9320: 					  ('grade_username' => $tuname,
 9321: 					   'grade_domain' => $tudom,
 9322: 					   'grade_courseid' => $tcrsid,
 9323: 					   'grade_symb' => $tsymb)));
 9324: 		    } else {
 9325: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9326: 		    }
 9327: 		} else {
 9328: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9329: 		}
 9330: 	    } else {
 9331: 		$request->print(&Apache::lonxml::tokeninputfield());
 9332: 	    }
 9333: 	}
 9334:     } else {
 9335: 	&init_perm();
 9336: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9337: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9338: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9339: 	    &pickStudentPage($request);
 9340: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9341: 	    &displayPage($request);
 9342: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9343: 	    &updateGradeByPage($request);
 9344: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9345: 	    &processGroup($request);
 9346: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9347: 	    $request->print(&grading_menu($request));
 9348: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9349: 	    $request->print(&submit_options($request));
 9350: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9351: 	    $request->print(&viewgrades($request));
 9352: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9353: 	    $request->print(&processHandGrade($request));
 9354: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9355: 	    $request->print(&editgrades($request));
 9356: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9357: 	    $request->print(&verifyreceipt($request));
 9358:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9359:             $request->print(&process_clicker($request));
 9360:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9361:             $request->print(&process_clicker_file($request));
 9362:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9363:             $request->print(&assign_clicker_grades($request));
 9364: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9365: 	    $request->print(&upcsvScores_form($request));
 9366: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9367: 	    $request->print(&csvupload($request));
 9368: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9369: 	    $request->print(&csvuploadmap($request));
 9370: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9371: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9372: 		$request->print(&csvuploadoptions($request));
 9373: 	    } else {
 9374: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9375: 		    $env{'form.upfile_associate'} = 'reverse';
 9376: 		} else {
 9377: 		    $env{'form.upfile_associate'} = 'forward';
 9378: 		}
 9379: 		$request->print(&csvuploadmap($request));
 9380: 	    }
 9381: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9382: 	    $request->print(&csvuploadassign($request));
 9383: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9384: 	    $request->print(&scantron_selectphase($request));
 9385:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9386:  	    $request->print(&scantron_do_warning($request));
 9387: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9388: 	    $request->print(&scantron_validate_file($request));
 9389: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9390: 	    $request->print(&scantron_process_students($request));
 9391:  	} elsif ($command eq 'scantronupload' && 
 9392:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9393: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9394:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9395:  	} elsif ($command eq 'scantronupload_save' &&
 9396:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9397: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9398:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9399:  	} elsif ($command eq 'scantron_download' &&
 9400: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9401:  	    $request->print(&scantron_download_scantron_data($request));
 9402:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9403:             $request->print(&checkscantron_results($request));     
 9404: 	} elsif ($command) {
 9405: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9406: 	}
 9407:     }
 9408:     if ($ssi_error) {
 9409: 	&ssi_print_error($request);
 9410:     }
 9411:     $request->print(&Apache::loncommon::end_page());
 9412:     &reset_caches();
 9413:     return '';
 9414: }
 9415: 
 9416: 1;
 9417: 
 9418: __END__;
 9419: 
 9420: 
 9421: =head1 NAME
 9422: 
 9423: Apache::grades
 9424: 
 9425: =head1 SYNOPSIS
 9426: 
 9427: Handles the viewing of grades.
 9428: 
 9429: This is part of the LearningOnline Network with CAPA project
 9430: described at http://www.lon-capa.org.
 9431: 
 9432: =head1 OVERVIEW
 9433: 
 9434: Do an ssi with retries:
 9435: While I'd love to factor out this with the vesrion in lonprintout,
 9436: 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
 9437: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9438: 
 9439: At least the logic that drives this has been pulled out into loncommon.
 9440: 
 9441: 
 9442: 
 9443: ssi_with_retries - Does the server side include of a resource.
 9444:                      if the ssi call returns an error we'll retry it up to
 9445:                      the number of times requested by the caller.
 9446:                      If we still have a proble, no text is appended to the
 9447:                      output and we set some global variables.
 9448:                      to indicate to the caller an SSI error occurred.  
 9449:                      All of this is supposed to deal with the issues described
 9450:                      in LonCAPA BZ 5631 see:
 9451:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9452:                      by informing the user that this happened.
 9453: 
 9454: Parameters:
 9455:   resource   - The resource to include.  This is passed directly, without
 9456:                interpretation to lonnet::ssi.
 9457:   form       - The form hash parameters that guide the interpretation of the resource
 9458:                
 9459:   retries    - Number of retries allowed before giving up completely.
 9460: Returns:
 9461:   On success, returns the rendered resource identified by the resource parameter.
 9462: Side Effects:
 9463:   The following global variables can be set:
 9464:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9465:                               It is up to the caller to initialize this to false
 9466:                               if desired.
 9467:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9468:                               of the resource that could not be rendered by the ssi
 9469:                               call.
 9470:    ssi_error_message   - The error string fetched from the ssi response
 9471:                               in the event of an error.
 9472: 
 9473: 
 9474: =head1 HANDLER SUBROUTINE
 9475: 
 9476: ssi_with_retries()
 9477: 
 9478: =head1 SUBROUTINES
 9479: 
 9480: =over
 9481: 
 9482: =item scantron_get_correction() : 
 9483: 
 9484:    Builds the interface screen to interact with the operator to fix a
 9485:    specific error condition in a specific scanline
 9486: 
 9487:  Arguments:
 9488:     $r           - Apache request object
 9489:     $i           - number of the current scanline
 9490:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9491:     $scan_config - hash ref as returned from &get_scantron_config()
 9492:     $line        - full contents of the current scanline
 9493:     $error       - error condition, valid values are
 9494:                    'incorrectCODE', 'duplicateCODE',
 9495:                    'doublebubble', 'missingbubble',
 9496:                    'duplicateID', 'incorrectID'
 9497:     $arg         - extra information needed
 9498:        For errors:
 9499:          - duplicateID   - paper number that this studentID was seen before on
 9500:          - duplicateCODE - array ref of the paper numbers this CODE was
 9501:                            seen on before
 9502:          - incorrectCODE - current incorrect CODE 
 9503:          - doublebubble  - array ref of the bubble lines that have double
 9504:                            bubble errors
 9505:          - missingbubble - array ref of the bubble lines that have missing
 9506:                            bubble errors
 9507: 
 9508: =item  scantron_get_maxbubble() : 
 9509: 
 9510:    Arguments:
 9511:        $nav_error  - Reference to scalar which is a flag to indicate a
 9512:                       failure to retrieve a navmap object.
 9513:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9514:        calling routine should trap the error condition and display the warning
 9515:        found in &navmap_errormsg().
 9516: 
 9517:    Returns the maximum number of bubble lines that are expected to
 9518:    occur. Does this by walking the selected sequence rendering the
 9519:    resource and then checking &Apache::lonxml::get_problem_counter()
 9520:    for what the current value of the problem counter is.
 9521: 
 9522:    Caches the results to $env{'form.scantron_maxbubble'},
 9523:    $env{'form.scantron.bubble_lines.n'}, 
 9524:    $env{'form.scantron.first_bubble_line.n'} and
 9525:    $env{"form.scantron.sub_bubblelines.n"}
 9526:    which are the total number of bubble, lines, the number of bubble
 9527:    lines for response n and number of the first bubble line for response n,
 9528:    and a comma separated list of numbers of bubble lines for sub-questions
 9529:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9530: 
 9531: 
 9532: =item  scantron_validate_missingbubbles() : 
 9533: 
 9534:    Validates all scanlines in the selected file to not have any
 9535:     answers that don't have bubbles that have not been verified
 9536:     to be bubble free.
 9537: 
 9538: =item  scantron_process_students() : 
 9539: 
 9540:    Routine that does the actual grading of the bubble sheet information.
 9541: 
 9542:    The parsed scanline hash is added to %env 
 9543: 
 9544:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9545:    foreach resource , with the form data of
 9546: 
 9547: 	'submitted'     =>'scantron' 
 9548: 	'grade_target'  =>'grade',
 9549: 	'grade_username'=> username of student
 9550: 	'grade_domain'  => domain of student
 9551: 	'grade_courseid'=> of course
 9552: 	'grade_symb'    => symb of resource to grade
 9553: 
 9554:     This triggers a grading pass. The problem grading code takes care
 9555:     of converting the bubbled letter information (now in %env) into a
 9556:     valid submission.
 9557: 
 9558: =item  scantron_upload_scantron_data() :
 9559: 
 9560:     Creates the screen for adding a new bubble sheet data file to a course.
 9561: 
 9562: =item  scantron_upload_scantron_data_save() : 
 9563: 
 9564:    Adds a provided bubble information data file to the course if user
 9565:    has the correct privileges to do so. 
 9566: 
 9567: =item  valid_file() :
 9568: 
 9569:    Validates that the requested bubble data file exists in the course.
 9570: 
 9571: =item  scantron_download_scantron_data() : 
 9572: 
 9573:    Shows a list of the three internal files (original, corrected,
 9574:    skipped) for a specific bubble sheet data file that exists in the
 9575:    course.
 9576: 
 9577: =item  scantron_validate_ID() : 
 9578: 
 9579:    Validates all scanlines in the selected file to not have any
 9580:    invalid or underspecified student/employee IDs
 9581: 
 9582: =item navmap_errormsg() :
 9583: 
 9584:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9585:    Should be called whenever the request to instantiate a navmap object fails.  
 9586: 
 9587: =back
 9588: 
 9589: =cut

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