File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.584: download - view: text, annotated - select for diffs
Tue Dec 15 18:26:18 2009 UTC (14 years, 4 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- Problem Part table:
    - Standard data_table
    - Added headlines
    - Translate problem type
    - font-weight normal
    - Removed unused variable $col
- "Receipt Number":
    - Consistent Wording
    - Updated &mt() calls and kept translation file entries (already up-to-date)
    - Added warning style to "no match" message

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.584 2009/12/15 18:26:18 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: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1715: sub gradeBox {
 1716:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1717:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1718: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1719:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1720:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1721:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1722:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1723:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1724: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1725:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1726:     my $display_part= &get_display_part($partid,$symb);
 1727:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1728: 				       [$partid]);
 1729:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1730:     if ($last_resets{$partid}) {
 1731:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1732:     }
 1733:     $result.='<table border="0"><tr>';
 1734:     my $ctr = 0;
 1735:     my $thisweight = 0;
 1736:     my $increment = &get_increment();
 1737: 
 1738:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1739:     while ($thisweight<=$wgt) {
 1740: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1741: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1742: 	    $thisweight.')" value="'.$thisweight.'" '.
 1743: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1744: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1745:         $thisweight += $increment;
 1746: 	$ctr++;
 1747:     }
 1748:     $radio.='</tr></table>';
 1749: 
 1750:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1751: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1752: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1753: 	$wgt.')" /></td>'."\n";
 1754:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1755: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1756: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1757:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1758: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1759:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1760: 	$line.='<option></option>'.
 1761: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1762:     } else {
 1763: 	$line.='<option selected="selected"></option>'.
 1764: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1765:     }
 1766:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1767: 
 1768: 
 1769: 	#&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);
 1770:     $result .= 
 1771: 	    '<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>';
 1772:     $result.='</tr></table>'."\n";
 1773:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1774: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1775: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1776: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1777:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1778:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1779:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1780:         $aggtries.'" />'."\n";
 1781:     my $res_error;
 1782:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1783:     if ($res_error) {
 1784:         return &navmap_errormsg();
 1785:     }
 1786:     return $result;
 1787: }
 1788: 
 1789: sub handback_box {
 1790:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1791:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1792:     my (@respids);
 1793:      my @part_response_id = &flatten_responseType($responseType);
 1794:     foreach my $part_response_id (@part_response_id) {
 1795:     	my ($part,$resp) = @{ $part_response_id };
 1796:         if ($part eq $partid) {
 1797:             push(@respids,$resp);
 1798:         }
 1799:     }
 1800:     my $result;
 1801:     foreach my $respid (@respids) {
 1802: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1803: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1804: 	next if (!@$files);
 1805: 	my $file_counter = 1;
 1806: 	foreach my $file (@$files) {
 1807: 	    if ($file =~ /\/portfolio\//) {
 1808:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1809:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1810:     	        $file_disp = "$name.$ext";
 1811:     	        $file = $file_path.$file_disp;
 1812:     	        $result.=&mt('Return commented version of [_1] to student.',
 1813:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1814:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1815:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1816:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1817:     	        $file_counter++;
 1818: 	    }
 1819: 	}
 1820:     }
 1821:     return $result;    
 1822: }
 1823: 
 1824: sub show_problem {
 1825:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1826:     my $rendered;
 1827:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1828:     &Apache::lonxml::remember_problem_counter();
 1829:     if ($mode eq 'both' or $mode eq 'text') {
 1830: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1831: 						       $env{'request.course.id'},
 1832: 						       undef,\%form);
 1833:     }
 1834:     if ($removeform) {
 1835: 	$rendered=~s|<form(.*?)>||g;
 1836: 	$rendered=~s|</form>||g;
 1837: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1838:     }
 1839:     my $companswer;
 1840:     if ($mode eq 'both' or $mode eq 'answer') {
 1841: 	&Apache::lonxml::restore_problem_counter();
 1842: 	$companswer=
 1843: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1844: 						    $env{'request.course.id'},
 1845: 						    %form);
 1846:     }
 1847:     if ($removeform) {
 1848: 	$companswer=~s|<form(.*?)>||g;
 1849: 	$companswer=~s|</form>||g;
 1850: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1851:     }
 1852:     $rendered=
 1853: 	'<div class="LC_grade_show_problem_header">'.
 1854: 	&mt('View of the problem').
 1855: 	'</div><div class="LC_grade_show_problem_problem">'.
 1856: 	$rendered.
 1857: 	'</div>';
 1858:     $companswer=
 1859: 	'<div class="LC_grade_show_problem_header">'.
 1860: 	&mt('Correct answer').
 1861: 	'</div><div class="LC_grade_show_problem_problem">'.
 1862: 	$companswer.
 1863: 	'</div>';
 1864:     my $result;
 1865:     if ($mode eq 'both') {
 1866: 	$result=$rendered.$companswer;
 1867:     } elsif ($mode eq 'text') {
 1868: 	$result=$rendered;
 1869:     } elsif ($mode eq 'answer') {
 1870: 	$result=$companswer;
 1871:     }
 1872:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1873:     return $result;
 1874: }
 1875: 
 1876: sub files_exist {
 1877:     my ($r, $symb) = @_;
 1878:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1879: 
 1880:     foreach my $student (@students) {
 1881:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1882:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1883: 					      $udom,$uname);
 1884:         my ($string,$timestamp)= &get_last_submission(\%record);
 1885:         foreach my $submission (@$string) {
 1886:             my ($partid,$respid) =
 1887: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1888:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1889: 					   \%record);
 1890:             return 1 if (@$files);
 1891:         }
 1892:     }
 1893:     return 0;
 1894: }
 1895: 
 1896: sub download_all_link {
 1897:     my ($r,$symb) = @_;
 1898:     my $all_students = 
 1899: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1900: 
 1901:     my $parts =
 1902: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1903: 
 1904:     my $identifier = &Apache::loncommon::get_cgi_id();
 1905:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1906:                              'cgi.'.$identifier.'.symb' => $symb,
 1907:                              'cgi.'.$identifier.'.parts' => $parts,});
 1908:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1909: 	      &mt('Download All Submitted Documents').'</a>');
 1910:     return
 1911: }
 1912: 
 1913: sub build_section_inputs {
 1914:     my $section_inputs;
 1915:     if ($env{'form.section'} eq '') {
 1916:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1917:     } else {
 1918:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1919:         foreach my $section (@sections) {
 1920:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1921:         }
 1922:     }
 1923:     return $section_inputs;
 1924: }
 1925: 
 1926: # --------------------------- show submissions of a student, option to grade 
 1927: sub submission {
 1928:     my ($request,$counter,$total) = @_;
 1929:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1930:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1931:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1932:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1933:     my $symb = &get_symb($request); 
 1934:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1935: 
 1936:     if (!&canview($usec)) {
 1937: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1938: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1939: 			$env{'request.course.id'}.')</span>');
 1940: 	$request->print(&show_grading_menu_form($symb));
 1941: 	return;
 1942:     }
 1943: 
 1944:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1945:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1946:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1947:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1948:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1949: 	'" src="'.$request->dir_config('lonIconsURL').
 1950: 	'/check.gif" height="16" border="0" />';
 1951: 
 1952:     my %old_essays;
 1953:     # header info
 1954:     if ($counter == 0) {
 1955: 	&sub_page_js($request);
 1956: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1957: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1958: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1959: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1960: 	    &download_all_link($request, $symb);
 1961: 	}
 1962: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1963: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1964: 
 1965: 	# option to display problem, only once else it cause problems 
 1966:         # with the form later since the problem has a form.
 1967: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1968: 	    my $mode;
 1969: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1970: 		$mode='both';
 1971: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1972: 		$mode='text';
 1973: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1974: 		$mode='answer';
 1975: 	    }
 1976: 	    &Apache::lonxml::clear_problem_counter();
 1977: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1978: 	}
 1979: 
 1980: 	# kwclr is the only variable that is guaranteed to be non blank 
 1981:         # if this subroutine has been called once.
 1982: 	my %keyhash = ();
 1983: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1984: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1985: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1986: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1987: 
 1988: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1989: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1990: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1991: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1992: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1993: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1994: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1995: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1996: 	}
 1997: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1998: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1999: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2000: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2001: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2002: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2003: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2004: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2005: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2006: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2007: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2008: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2009: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2010: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2011: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2012: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2013: 			&build_section_inputs().
 2014: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2015: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2016: 			'<input type="hidden" name="NCT"'.
 2017: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2018: 	if ($env{'form.handgrade'} eq 'yes') {
 2019: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2020: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2021: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2022: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2023: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2024: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2025: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2026: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2027: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2028: 	    }
 2029: 	}
 2030: 	
 2031: 	my ($cts,$prnmsg) = (1,'');
 2032: 	while ($cts <= $env{'form.savemsgN'}) {
 2033: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2034: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2035: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2036: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2037: 		'" />'."\n".
 2038: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2039: 	    $cts++;
 2040: 	}
 2041: 	$request->print($prnmsg);
 2042: 
 2043: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2044: #
 2045: # Print out the keyword options line
 2046: #
 2047: 	    $request->print(<<KEYWORDS);
 2048: &nbsp;<b>Keyword Options:</b>&nbsp;
 2049: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2050: <a href="#" onMouseDown="javascript:getSel(); return false"
 2051:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2052: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2053: KEYWORDS
 2054: #
 2055: # Load the other essays for similarity check
 2056: #
 2057:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2058: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2059: 	    $apath=&escape($apath);
 2060: 	    $apath=~s/\W/\_/gs;
 2061: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2062:         }
 2063:     }
 2064: 
 2065: # This is where output for one specific student would start
 2066:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2067:     $request->print("\n\n".
 2068:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2069: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2070: 		    '<div class="LC_grade_show_user_body">'."\n");
 2071: 
 2072:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2073: 	my $mode;
 2074: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2075: 	    $mode='both';
 2076: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2077: 	    $mode='text';
 2078: 	} elsif ($env{'form.vAns'} eq 'all') {
 2079: 	    $mode='answer';
 2080: 	}
 2081: 	&Apache::lonxml::clear_problem_counter();
 2082: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2083:     }
 2084: 
 2085:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2086:     my $res_error;
 2087:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2088:     if ($res_error) {
 2089:         $request->print(&navmap_errormsg());
 2090:         return;
 2091:     }
 2092: 
 2093:     # Display student info
 2094:     $request->print(($counter == 0 ? '' : '<br />'));
 2095:     my $result='<div class="LC_grade_submissions">';
 2096:     
 2097:     $result.='<div class="LC_grade_submissions_header">';
 2098:     $result.= &mt('Submissions');
 2099:     $result.='<input type="hidden" name="name'.$counter.
 2100: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2101:     if ($env{'form.handgrade'} eq 'no') {
 2102: 	$result.='<span class="LC_grade_check_note">'.
 2103: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2104: 
 2105:     }
 2106: 
 2107: 
 2108: 
 2109:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2110:     my $fullname;
 2111:     my $col_fullnames = [];
 2112:     if ($env{'form.handgrade'} eq 'yes') {
 2113: 	(my $sub_result,$fullname,$col_fullnames)=
 2114: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2115: 				 $counter);
 2116: 	$result.=$sub_result;
 2117:     }
 2118:     $request->print($result."\n");
 2119:     $request->print('</div>'."\n");
 2120:     # print student answer/submission
 2121:     # Options are (1) Handgaded submission only
 2122:     #             (2) Last submission, includes submission that is not handgraded 
 2123:     #                  (for multi-response type part)
 2124:     #             (3) Last submission plus the parts info
 2125:     #             (4) The whole record for this student
 2126:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2127: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2128: 	
 2129: 	my $lastsubonly;
 2130: 
 2131: 	if ($$timestamp eq '') {
 2132: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2133: 	} else {
 2134: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2135: 
 2136: 	    my %seenparts;
 2137: 	    my @part_response_id = &flatten_responseType($responseType);
 2138: 	    foreach my $part (@part_response_id) {
 2139: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2140: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2141: 
 2142: 		my ($partid,$respid) = @{ $part };
 2143: 		my $display_part=&get_display_part($partid,$symb);
 2144: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2145: 		    if (exists($seenparts{$partid})) { next; }
 2146: 		    $seenparts{$partid}=1;
 2147: 		    my $submitby='<b>Part:</b> '.$display_part.
 2148: 			' <b>Collaborative submission by:</b> '.
 2149: 			'<a href="javascript:viewSubmitter(\''.
 2150: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2151: 			'\');" target="_self">'.
 2152: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2153: 		    $request->print($submitby);
 2154: 		    next;
 2155: 		}
 2156: 		my $responsetype = $responseType->{$partid}->{$respid};
 2157: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2158:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2159:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2160:                         ' <span class="LC_internal_info">'.
 2161:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2162:                         '</span>&nbsp; &nbsp;'.
 2163: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2164: 		    next;
 2165: 		}
 2166: 		foreach my $submission (@$string) {
 2167: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2168: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2169: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2170: 		    # Similarity check
 2171: 		    my $similar='';
 2172: 		    if($env{'form.checkPlag'}){
 2173: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2174: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2175: 			if ($osim) {
 2176: 			    $osim=int($osim*100.0);
 2177: 			    my %old_course_desc = 
 2178: 				&Apache::lonnet::coursedescription($ocrsid,
 2179: 								   {'one_time' => 1});
 2180: 
 2181: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2182: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2183: 				    $osim,
 2184: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2185: 				    $old_course_desc{'description'},
 2186: 				    $old_course_desc{'num'},
 2187: 				    $old_course_desc{'domain'}).
 2188: 				'</span></h3><blockquote><i>'.
 2189: 				&keywords_highlight($oessay).
 2190: 				'</i></blockquote><hr />';
 2191: 			}
 2192: 		    }
 2193: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2194: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2195: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2196: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2197: 			my $display_part=&get_display_part($partid,$symb);
 2198:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2199:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2200:                             ' <span class="LC_internal_info">'.
 2201:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2202:                             '</b></span>&nbsp; &nbsp;';
 2203: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2204: 			if (@$files) {
 2205: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2206: 			    my $file_counter = 0;
 2207: 			    foreach my $file (@$files) {
 2208: 			        $file_counter++;
 2209: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2210: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2211: 			    }
 2212: 			    $lastsubonly.='<br />';
 2213: 			}
 2214: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2215: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2216: 					 $respid,\%record,$order,undef,$uname,$udom);
 2217: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2218: 			$lastsubonly.='</div>';
 2219: 		    }
 2220: 		}
 2221: 	    }
 2222: 	    $lastsubonly.='</div>'."\n";
 2223: 	}
 2224: 	$request->print($lastsubonly);
 2225:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2226: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2227: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2228:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2229: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2230: 								 $env{'request.course.id'},
 2231: 								 $last,'.submission',
 2232: 								 'Apache::grades::keywords_highlight'));
 2233:     }
 2234: 
 2235:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2236: 	.$udom.'" />'."\n");
 2237:     # return if view submission with no grading option
 2238:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2239: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2240: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2241: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2242: 	$toGrade.='</div>'."\n";
 2243: 	if (($env{'form.command'} eq 'submission') || 
 2244: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2245: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2246: 	}
 2247: 	$request->print($toGrade);
 2248: 	return;
 2249:     } else {
 2250: 	$request->print('</div>'."\n");
 2251:     }
 2252: 
 2253:     # essay grading message center
 2254:     if ($env{'form.handgrade'} eq 'yes') {
 2255: 	my $result='<div class="LC_grade_message_center">';
 2256:     
 2257: 	$result.='<div class="LC_grade_message_center_header">'.
 2258: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2259: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2260: 	my $msgfor = $givenn.' '.$lastname;
 2261: 	if (scalar(@$col_fullnames) > 0) {
 2262: 	    my $lastone = pop(@$col_fullnames);
 2263: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2264: 	}
 2265: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2266: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2267: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2268: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2269: 	    ',\''.$msgfor.'\');" target="_self">'.
 2270: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2271: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2272: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2273: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2274: 	    '<br />&nbsp;('.
 2275: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2276: 	$result.='</div></div>';
 2277: 	$request->print($result);
 2278:     }
 2279: 
 2280:     my %seen = ();
 2281:     my @partlist;
 2282:     my @gradePartRespid;
 2283:     my @part_response_id = &flatten_responseType($responseType);
 2284:     $request->print('<div class="LC_grade_assign">'.
 2285: 		    
 2286: 		    '<div class="LC_grade_assign_header">'.
 2287: 		    &mt('Assign Grades').'</div>'.
 2288: 		    '<div class="LC_grade_assign_body">');
 2289:     foreach my $part_response_id (@part_response_id) {
 2290:     	my ($partid,$respid) = @{ $part_response_id };
 2291: 	my $part_resp = join('_',@{ $part_response_id });
 2292: 	next if ($seen{$partid} > 0);
 2293: 	$seen{$partid}++;
 2294: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2295: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2296: 	push(@partlist,$partid);
 2297: 	push(@gradePartRespid,$partid.'.'.$respid);
 2298: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2299:     }
 2300:     $request->print('</div></div>');
 2301: 
 2302:     $request->print('<div class="LC_grade_info_links">');
 2303:     if ($perm{'vgr'}) {
 2304: 	$request->print(
 2305: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2306: 						   $uname,$udom,'check'));
 2307:     }
 2308:     if ($perm{'opa'}) {
 2309: 	$request->print(
 2310: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2311: 					 $uname,$udom,$symb,'check'));
 2312:     }
 2313:     $request->print('</div>');
 2314: 
 2315:     $result='<input type="hidden" name="partlist'.$counter.
 2316: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2317:     $result.='<input type="hidden" name="gradePartRespid'.
 2318: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2319:     my $ctr = 0;
 2320:     while ($ctr < scalar(@partlist)) {
 2321: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2322: 	    $partlist[$ctr].'" />'."\n";
 2323: 	$ctr++;
 2324:     }
 2325:     $request->print($result.''."\n");
 2326: 
 2327: # Done with printing info for one student
 2328: 
 2329:     $request->print('</div>');#LC_grade_show_user_body
 2330:     $request->print('</div>');#LC_grade_show_user
 2331: 
 2332: 
 2333:     # print end of form
 2334:     if ($counter == $total) {
 2335: 	my $endform='<table border="0"><tr><td>'."\n";
 2336: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2337: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2338: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2339: 	my $ntstu ='<select name="NTSTU">'.
 2340: 	    '<option>1</option><option>2</option>'.
 2341: 	    '<option>3</option><option>5</option>'.
 2342: 	    '<option>7</option><option>10</option></select>'."\n";
 2343: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2344: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2345:         $endform.=&mt('[_1]student(s)',$ntstu);
 2346: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2347: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2348: 	    '<input type="button" value="'.&mt('Next').'" '.
 2349: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2350: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2351:         $endform.="<input type='hidden' value='".&get_increment().
 2352:             "' name='increment' />";
 2353: 	$endform.='</td></tr></table></form>';
 2354: 	$endform.=&show_grading_menu_form($symb);
 2355: 	$request->print($endform);
 2356:     }
 2357:     return '';
 2358: }
 2359: 
 2360: sub check_collaborators {
 2361:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2362:     my ($result,@col_fullnames);
 2363:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2364:     foreach my $part (keys(%$handgrade)) {
 2365: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2366: 					'.maxcollaborators',
 2367: 					$symb,$udom,$uname);
 2368: 	next if ($ncol <= 0);
 2369: 	$part =~ s/\_/\./g;
 2370: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2371: 	my (@good_collaborators, @bad_collaborators);
 2372: 	foreach my $possible_collaborator
 2373: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2374: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2375: 	    next if ($possible_collaborator eq '');
 2376: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2377: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2378: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2379: 	    # Doing this grep allows 'fuzzy' specification
 2380: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2381: 			       keys(%$classlist));
 2382: 	    if (! scalar(@matches)) {
 2383: 		push(@bad_collaborators, $possible_collaborator);
 2384: 	    } else {
 2385: 		push(@good_collaborators, @matches);
 2386: 	    }
 2387: 	}
 2388: 	if (scalar(@good_collaborators) != 0) {
 2389: 	    $result.='<br />'.&mt('Collaborators: ');
 2390: 	    foreach my $name (@good_collaborators) {
 2391: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2392: 		push(@col_fullnames, $givenn.' '.$lastname);
 2393: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2394: 	    }
 2395: 	    $result.='<br />'."\n";
 2396: 	    my ($part)=split(/\./,$part);
 2397: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2398: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2399: 		"\n";
 2400: 	}
 2401: 	if (scalar(@bad_collaborators) > 0) {
 2402: 	    $result.='<div class="LC_warning">';
 2403: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2404: 	    $result .= '</div>';
 2405: 	}         
 2406: 	if (scalar(@bad_collaborators > $ncol)) {
 2407: 	    $result .= '<div class="LC_warning">';
 2408: 	    $result .= &mt('This student has submitted too many '.
 2409: 		'collaborators.  Maximum is [_1].',$ncol);
 2410: 	    $result .= '</div>';
 2411: 	}
 2412:     }
 2413:     return ($result,$fullname,\@col_fullnames);
 2414: }
 2415: 
 2416: #--- Retrieve the last submission for all the parts
 2417: sub get_last_submission {
 2418:     my ($returnhash)=@_;
 2419:     my (@string,$timestamp);
 2420:     if ($$returnhash{'version'}) {
 2421: 	my %lasthash=();
 2422: 	my ($version);
 2423: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2424: 	    foreach my $key (sort(split(/\:/,
 2425: 					$$returnhash{$version.':keys'}))) {
 2426: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2427: 		$timestamp = 
 2428: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2429: 	    }
 2430: 	}
 2431: 	foreach my $key (keys(%lasthash)) {
 2432: 	    next if ($key !~ /\.submission$/);
 2433: 
 2434: 	    my ($partid,$foo) = split(/submission$/,$key);
 2435: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2436: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2437: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2438: 	}
 2439:     }
 2440:     if (!@string) {
 2441: 	$string[0] =
 2442: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2443:     }
 2444:     return (\@string,\$timestamp);
 2445: }
 2446: 
 2447: #--- High light keywords, with style choosen by user.
 2448: sub keywords_highlight {
 2449:     my $string    = shift;
 2450:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2451:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2452:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2453:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2454:     foreach my $keyword (@keylist) {
 2455: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2456:     }
 2457:     return $string;
 2458: }
 2459: 
 2460: #--- Called from submission routine
 2461: sub processHandGrade {
 2462:     my ($request) = shift;
 2463:     my $symb   = &get_symb($request);
 2464:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2465:     my $button = $env{'form.gradeOpt'};
 2466:     my $ngrade = $env{'form.NCT'};
 2467:     my $ntstu  = $env{'form.NTSTU'};
 2468:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2469:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2470: 
 2471:     if ($button eq 'Save & Next') {
 2472: 	my $ctr = 0;
 2473: 	while ($ctr < $ngrade) {
 2474: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2475: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2476: 	    if ($errorflag eq 'no_score') {
 2477: 		$ctr++;
 2478: 		next;
 2479: 	    }
 2480: 	    if ($errorflag eq 'not_allowed') {
 2481: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2482: 		$ctr++;
 2483: 		next;
 2484: 	    }
 2485: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2486: 	    my ($subject,$message,$msgstatus) = ('','','');
 2487: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2488:             my ($feedurl,$showsymb) =
 2489: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2490: 	    my $messagetail;
 2491: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2492: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2493: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2494: 		$subject.=' ['.$restitle.']';
 2495: 		my (@msgnum) = split(/,/,$includemsg);
 2496: 		foreach (@msgnum) {
 2497: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2498: 		}
 2499: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2500: 		if ($env{'form.withgrades'.$ctr}) {
 2501: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2502: 		    $messagetail = " for <a href=\"".
 2503: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2504: 		}
 2505: 		$msgstatus = 
 2506:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2507: 						     $message.$messagetail,
 2508:                                                      undef,$feedurl,undef,
 2509:                                                      undef,undef,$showsymb,
 2510:                                                      $restitle);
 2511: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2512: 				$msgstatus);
 2513: 	    }
 2514: 	    if ($env{'form.collaborator'.$ctr}) {
 2515: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2516: 		foreach my $collabstr (@collabstrs) {
 2517: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2518: 		    foreach my $collaborator (@collaborators) {
 2519: 			my ($errorflag,$pts,$wgt) = 
 2520: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2521: 					   $env{'form.unamedom'.$ctr},$part);
 2522: 			if ($errorflag eq 'not_allowed') {
 2523: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2524: 			    next;
 2525: 			} elsif ($message ne '') {
 2526: 			    my ($baseurl,$showsymb) = 
 2527: 				&get_feedurl_and_symb($symb,$collaborator,
 2528: 						      $udom);
 2529: 			    if ($env{'form.withgrades'.$ctr}) {
 2530: 				$messagetail = " for <a href=\"".
 2531:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2532: 			    }
 2533: 			    $msgstatus = 
 2534: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2535: 			}
 2536: 		    }
 2537: 		}
 2538: 	    }
 2539: 	    $ctr++;
 2540: 	}
 2541:     }
 2542: 
 2543:     if ($env{'form.handgrade'} eq 'yes') {
 2544: 	# Keywords sorted in alphabatical order
 2545: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2546: 	my %keyhash = ();
 2547: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2548: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2549: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2550: 	$env{'form.keywords'} = join(' ',@keywords);
 2551: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2552: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2553: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2554: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2555: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2556: 
 2557: 	# message center - Order of message gets changed. Blank line is eliminated.
 2558: 	# New messages are saved in env for the next student.
 2559: 	# All messages are saved in nohist_handgrade.db
 2560: 	my ($ctr,$idx) = (1,1);
 2561: 	while ($ctr <= $env{'form.savemsgN'}) {
 2562: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2563: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2564: 		$idx++;
 2565: 	    }
 2566: 	    $ctr++;
 2567: 	}
 2568: 	$ctr = 0;
 2569: 	while ($ctr < $ngrade) {
 2570: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2571: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2572: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2573: 		$idx++;
 2574: 	    }
 2575: 	    $ctr++;
 2576: 	}
 2577: 	$env{'form.savemsgN'} = --$idx;
 2578: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2579: 	my $putresult = &Apache::lonnet::put
 2580: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2581:     }
 2582:     # Called by Save & Refresh from Highlight Attribute Window
 2583:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2584:     if ($env{'form.refresh'} eq 'on') {
 2585: 	my ($ctr,$total) = (0,0);
 2586: 	while ($ctr < $ngrade) {
 2587: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2588: 	    $ctr++;
 2589: 	}
 2590: 	$env{'form.NTSTU'}=$ngrade;
 2591: 	$ctr = 0;
 2592: 	while ($ctr < $total) {
 2593: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2594: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2595: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2596: 	    &submission($request,$ctr,$total-1);
 2597: 	    $ctr++;
 2598: 	}
 2599: 	return '';
 2600:     }
 2601: 
 2602: # Go directly to grade student - from submission or link from chart page
 2603:     if ($button eq 'Grade Student') {
 2604: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2605: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2606: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2607: 	$env{'form.fullname'} = $$fullname{$processUser};
 2608: 	&submission($request,0,0);
 2609: 	return '';
 2610:     }
 2611: 
 2612:     # Get the next/previous one or group of students
 2613:     my $firststu = $env{'form.unamedom0'};
 2614:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2615:     my $ctr = 2;
 2616:     while ($laststu eq '') {
 2617: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2618: 	$ctr++;
 2619: 	$laststu = $firststu if ($ctr > $ngrade);
 2620:     }
 2621: 
 2622:     my (@parsedlist,@nextlist);
 2623:     my ($nextflg) = 0;
 2624:     foreach my $item (sort 
 2625: 	     {
 2626: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2627: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2628: 		 }
 2629: 		 return $a cmp $b;
 2630: 	     } (keys(%$fullname))) {
 2631: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2632: 	    push(@parsedlist,$item);
 2633: 	}
 2634: 	$nextflg = 1 if ($item eq $laststu);
 2635: 	if ($button eq 'Previous') {
 2636: 	    last if ($item eq $firststu);
 2637: 	    push(@parsedlist,$item);
 2638: 	}
 2639:     }
 2640:     $ctr = 0;
 2641:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2642:     my $res_error;
 2643:     my ($partlist) = &response_type($symb,\$res_error);
 2644:     if ($res_error) {
 2645:         $request->print(&navmap_errormsg());
 2646:         return;
 2647:     }
 2648:     foreach my $student (@parsedlist) {
 2649: 	my $submitonly=$env{'form.submitonly'};
 2650: 	my ($uname,$udom) = split(/:/,$student);
 2651: 	
 2652: 	if ($submitonly eq 'queued') {
 2653: 	    my %queue_status = 
 2654: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2655: 							$udom,$uname);
 2656: 	    next if (!defined($queue_status{'gradingqueue'}));
 2657: 	}
 2658: 
 2659: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2660: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2661: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2662: 	    my $submitted = 0;
 2663: 	    my $ungraded = 0;
 2664: 	    my $incorrect = 0;
 2665: 	    foreach my $item (keys(%status)) {
 2666: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2667: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2668: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2669: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2670: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2671: 		    $submitted = 0;
 2672: 		}
 2673: 	    }
 2674: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2675: 				     $submitonly eq 'incorrect' ||
 2676: 				     $submitonly eq 'graded'));
 2677: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2678: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2679: 	}
 2680: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2681: 	last if ($ctr == $ntstu);
 2682: 	$ctr++;
 2683:     }
 2684: 
 2685:     $ctr = 0;
 2686:     my $total = scalar(@nextlist)-1;
 2687: 
 2688:     foreach (sort(@nextlist)) {
 2689: 	my ($uname,$udom,$submitter) = split(/:/);
 2690: 	$env{'form.student'}  = $uname;
 2691: 	$env{'form.userdom'}  = $udom;
 2692: 	$env{'form.fullname'} = $$fullname{$_};
 2693: 	&submission($request,$ctr,$total);
 2694: 	$ctr++;
 2695:     }
 2696:     if ($total < 0) {
 2697: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2698: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2699: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2700: 	$the_end.=&show_grading_menu_form($symb);
 2701: 	$request->print($the_end);
 2702:     }
 2703:     return '';
 2704: }
 2705: 
 2706: #---- Save the score and award for each student, if changed
 2707: sub saveHandGrade {
 2708:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2709:     my @version_parts;
 2710:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2711: 					   $env{'request.course.id'});
 2712:     if (!&canmodify($usec)) { return('not_allowed'); }
 2713:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2714:     my @parts_graded;
 2715:     my %newrecord  = ();
 2716:     my ($pts,$wgt) = ('','');
 2717:     my %aggregate = ();
 2718:     my $aggregateflag = 0;
 2719:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2720:     foreach my $new_part (@parts) {
 2721: 	#collaborator ($submi may vary for different parts
 2722: 	if ($submitter && $new_part ne $part) { next; }
 2723: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2724: 	if ($dropMenu eq 'excused') {
 2725: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2726: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2727: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2728: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2729: 		}
 2730: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2731: 	    }
 2732: 	} elsif ($dropMenu eq 'reset status'
 2733: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2734: 	    foreach my $key (keys(%record)) {
 2735: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2736: 	    }
 2737: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2738: 		"$env{'user.name'}:$env{'user.domain'}";
 2739:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2740: 
 2741:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2742: 					       [$new_part]);
 2743:             my $aggtries =$totaltries;
 2744:             if ($last_resets{$new_part}) {
 2745:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2746: 					   $new_part);
 2747:             }
 2748: 
 2749:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2750:             if ($aggtries > 0) {
 2751:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2752:                 $aggregateflag = 1;
 2753:             }
 2754: 	} elsif ($dropMenu eq '') {
 2755: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2756: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2757: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2758: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2759: 		next;
 2760: 	    }
 2761: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2762: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2763: 	    my $partial= $pts/$wgt;
 2764: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2765: 		#do not update score for part if not changed.
 2766:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2767: 		next;
 2768: 	    } else {
 2769: 	        push(@parts_graded,$new_part);
 2770: 	    }
 2771: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2772: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2773: 	    }
 2774: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2775: 	    if ($partial == 0) {
 2776: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2777: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2778: 		}
 2779: 	    } else {
 2780: 		if ($record{$reckey} ne 'correct_by_override') {
 2781: 		    $newrecord{$reckey} = 'correct_by_override';
 2782: 		}
 2783: 	    }	    
 2784: 	    if ($submitter && 
 2785: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2786: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2787: 	    }
 2788: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2789: 		"$env{'user.name'}:$env{'user.domain'}";
 2790: 	}
 2791: 	# unless problem has been graded, set flag to version the submitted files
 2792: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2793: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2794: 	        $dropMenu eq 'reset status')
 2795: 	   {
 2796: 	    push(@version_parts,$new_part);
 2797: 	}
 2798:     }
 2799:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2800:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2801: 
 2802:     if (%newrecord) {
 2803:         if (@version_parts) {
 2804:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2805:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2806: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2807: 	    foreach my $new_part (@version_parts) {
 2808: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2809: 				$new_part,\%newrecord);
 2810: 	    }
 2811:         }
 2812: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2813: 				$env{'request.course.id'},$domain,$stuname);
 2814: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2815: 				     $cdom,$cnum,$domain,$stuname);
 2816:     }
 2817:     if ($aggregateflag) {
 2818:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2819: 			      $cdom,$cnum);
 2820:     }
 2821:     return ('',$pts,$wgt);
 2822: }
 2823: 
 2824: sub check_and_remove_from_queue {
 2825:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2826:     my @ungraded_parts;
 2827:     foreach my $part (@{$parts}) {
 2828: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2829: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2830: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2831: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2832: 		) {
 2833: 	    push(@ungraded_parts, $part);
 2834: 	}
 2835:     }
 2836:     if ( !@ungraded_parts ) {
 2837: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2838: 					       $cnum,$domain,$stuname);
 2839:     }
 2840: }
 2841: 
 2842: sub handback_files {
 2843:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2844:     my $portfolio_root = '/userfiles/portfolio';
 2845:     my $res_error;
 2846:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2847:     if ($res_error) {
 2848:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2849:         return;
 2850:     }
 2851:     my @part_response_id = &flatten_responseType($responseType);
 2852:     foreach my $part_response_id (@part_response_id) {
 2853:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2854: 	my $part_resp = join('_',@{ $part_response_id });
 2855:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2856:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2857:                 my $file_counter = 1;
 2858: 		my $file_msg;
 2859:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2860:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2861:                     my ($directory,$answer_file) = 
 2862:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2863:                     my ($answer_name,$answer_ver,$answer_ext) =
 2864: 		        &file_name_version_ext($answer_file);
 2865: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2866:                     my $getpropath = 1;
 2867: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2868: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2869:                     # fix file name
 2870:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2871:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2872:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2873:             	                                $save_file_name);
 2874:                     if ($result !~ m|^/uploaded/|) {
 2875:                         $request->print('<br /><span class="LC_error">'.
 2876:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2877:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2878:                                         '</span>');
 2879:                     } else {
 2880:                         # mark the file as read only
 2881:                         my @files = ($save_file_name);
 2882:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2883:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2884: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2885: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2886: 			}
 2887:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2888: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2889: 
 2890:                     }
 2891:                     $request->print("<br />".$fname." will be the uploaded file name");
 2892:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2893:                     $file_counter++;
 2894:                 }
 2895: 		my $subject = "File Handed Back by Instructor ";
 2896: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2897: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2898: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2899: 		$message .= " and can be found in your portfolio space.";
 2900: 		my ($feedurl,$showsymb) = 
 2901: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2902:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2903: 		my $msgstatus = 
 2904:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2905: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2906:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2907:             }
 2908:         }
 2909:     return;
 2910: }
 2911: 
 2912: sub get_feedurl_and_symb {
 2913:     my ($symb,$uname,$udom) = @_;
 2914:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2915:     $url = &Apache::lonnet::clutter($url);
 2916:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2917: 					$symb,$udom,$uname);
 2918:     if ($encrypturl =~ /^yes$/i) {
 2919: 	&Apache::lonenc::encrypted(\$url,1);
 2920: 	&Apache::lonenc::encrypted(\$symb,1);
 2921:     }
 2922:     return ($url,$symb);
 2923: }
 2924: 
 2925: sub get_submitted_files {
 2926:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2927:     my @files;
 2928:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2929:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2930:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2931:     	    push(@files,$file_url.$file);
 2932:         }
 2933:     }
 2934:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2935:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2936:     }
 2937:     return (\@files);
 2938: }
 2939: 
 2940: # ----------- Provides number of tries since last reset.
 2941: sub get_num_tries {
 2942:     my ($record,$last_reset,$part) = @_;
 2943:     my $timestamp = '';
 2944:     my $num_tries = 0;
 2945:     if ($$record{'version'}) {
 2946:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2947:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2948:                 $timestamp = $$record{$version.':timestamp'};
 2949:                 if ($timestamp > $last_reset) {
 2950:                     $num_tries ++;
 2951:                 } else {
 2952:                     last;
 2953:                 }
 2954:             }
 2955:         }
 2956:     }
 2957:     return $num_tries;
 2958: }
 2959: 
 2960: # ----------- Determine decrements required in aggregate totals 
 2961: sub decrement_aggs {
 2962:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2963:     my %decrement = (
 2964:                         attempts => 0,
 2965:                         users => 0,
 2966:                         correct => 0
 2967:                     );
 2968:     $decrement{'attempts'} = $aggtries;
 2969:     if ($solvedstatus =~ /^correct/) {
 2970:         $decrement{'correct'} = 1;
 2971:     }
 2972:     if ($aggtries == $totaltries) {
 2973:         $decrement{'users'} = 1;
 2974:     }
 2975:     foreach my $type (keys(%decrement)) {
 2976:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2977:     }
 2978:     return;
 2979: }
 2980: 
 2981: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2982: sub get_last_resets {
 2983:     my ($symb,$courseid,$partids) =@_;
 2984:     my %last_resets;
 2985:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2986:     my $cname = $env{'course.'.$courseid.'.num'};
 2987:     my @keys;
 2988:     foreach my $part (@{$partids}) {
 2989: 	push(@keys,"$symb\0$part\0resettime");
 2990:     }
 2991:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2992: 				     $cdom,$cname);
 2993:     foreach my $part (@{$partids}) {
 2994: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2995:     }
 2996:     return %last_resets;
 2997: }
 2998: 
 2999: # ----------- Handles creating versions for portfolio files as answers
 3000: sub version_portfiles {
 3001:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3002:     my $version_parts = join('|',@$v_flag);
 3003:     my @returned_keys;
 3004:     my $parts = join('|', @$parts_graded);
 3005:     my $portfolio_root = '/userfiles/portfolio';
 3006:     foreach my $key (keys(%$record)) {
 3007:         my $new_portfiles;
 3008:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3009:             my @versioned_portfiles;
 3010:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3011:             foreach my $file (@portfiles) {
 3012:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3013:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3014: 		my ($answer_name,$answer_ver,$answer_ext) =
 3015: 		    &file_name_version_ext($answer_file);
 3016:                 my $getpropath = 1;    
 3017:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3018:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3019:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3020:                 if ($new_answer ne 'problem getting file') {
 3021:                     push(@versioned_portfiles, $directory.$new_answer);
 3022:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3023:                         [$directory.$new_answer],
 3024:                         [$symb,$env{'request.course.id'},'graded']);
 3025:                 }
 3026:             }
 3027:             $$record{$key} = join(',',@versioned_portfiles);
 3028:             push(@returned_keys,$key);
 3029:         }
 3030:     } 
 3031:     return (@returned_keys);   
 3032: }
 3033: 
 3034: sub get_next_version {
 3035:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3036:     my $version;
 3037:     foreach my $row (@$dir_list) {
 3038:         my ($file) = split(/\&/,$row,2);
 3039:         my ($file_name,$file_version,$file_ext) =
 3040: 	    &file_name_version_ext($file);
 3041:         if (($file_name eq $answer_name) && 
 3042: 	    ($file_ext eq $answer_ext)) {
 3043:                 # gets here if filename and extension match, regardless of version
 3044:                 if ($file_version ne '') {
 3045:                 # a versioned file is found  so save it for later
 3046:                 if ($file_version > $version) {
 3047: 		    $version = $file_version;
 3048: 	        }
 3049:             }
 3050:         }
 3051:     } 
 3052:     $version ++;
 3053:     return($version);
 3054: }
 3055: 
 3056: sub version_selected_portfile {
 3057:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3058:     my ($answer_name,$answer_ver,$answer_ext) =
 3059:         &file_name_version_ext($file_name);
 3060:     my $new_answer;
 3061:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3062:     if($env{'form.copy'} eq '-1') {
 3063:         $new_answer = 'problem getting file';
 3064:     } else {
 3065:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3066:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3067:                             $stu_name,$domain,'copy',
 3068: 		        '/portfolio'.$directory.$new_answer);
 3069:     }    
 3070:     return ($new_answer);
 3071: }
 3072: 
 3073: sub file_name_version_ext {
 3074:     my ($file)=@_;
 3075:     my @file_parts = split(/\./, $file);
 3076:     my ($name,$version,$ext);
 3077:     if (@file_parts > 1) {
 3078: 	$ext=pop(@file_parts);
 3079: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3080: 	    $version=pop(@file_parts);
 3081: 	}
 3082: 	$name=join('.',@file_parts);
 3083:     } else {
 3084: 	$name=join('.',@file_parts);
 3085:     }
 3086:     return($name,$version,$ext);
 3087: }
 3088: 
 3089: #--------------------------------------------------------------------------------------
 3090: #
 3091: #-------------------------- Next few routines handles grading by section or whole class
 3092: #
 3093: #--- Javascript to handle grading by section or whole class
 3094: sub viewgrades_js {
 3095:     my ($request) = shift;
 3096: 
 3097:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3098:     $request->print(<<VIEWJAVASCRIPT);
 3099: <script type="text/javascript" language="javascript">
 3100:    function writePoint(partid,weight,point) {
 3101: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3102: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3103: 	if (point == "textval") {
 3104: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3105: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3106: 		alert("$alertmsg"+parseFloat(point));
 3107: 		var resetbox = false;
 3108: 		for (var i=0; i<radioButton.length; i++) {
 3109: 		    if (radioButton[i].checked) {
 3110: 			textbox.value = i;
 3111: 			resetbox = true;
 3112: 		    }
 3113: 		}
 3114: 		if (!resetbox) {
 3115: 		    textbox.value = "";
 3116: 		}
 3117: 		return;
 3118: 	    }
 3119: 	    if (parseFloat(point) > parseFloat(weight)) {
 3120: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3121: 				   ") greater than the weight for the part. Accept?");
 3122: 		if (resp == false) {
 3123: 		    textbox.value = "";
 3124: 		    return;
 3125: 		}
 3126: 	    }
 3127: 	    for (var i=0; i<radioButton.length; i++) {
 3128: 		radioButton[i].checked=false;
 3129: 		if (parseFloat(point) == i) {
 3130: 		    radioButton[i].checked=true;
 3131: 		}
 3132: 	    }
 3133: 
 3134: 	} else {
 3135: 	    textbox.value = parseFloat(point);
 3136: 	}
 3137: 	for (i=0;i<document.classgrade.total.value;i++) {
 3138: 	    var user = document.classgrade["ctr"+i].value;
 3139: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3140: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3141: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3142: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3143: 	    if (saveval != "correct") {
 3144: 		scorename.value = point;
 3145: 		if (selname[0].selected != true) {
 3146: 		    selname[0].selected = true;
 3147: 		}
 3148: 	    }
 3149: 	}
 3150: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3151:     }
 3152: 
 3153:     function writeRadText(partid,weight) {
 3154: 	var selval   = document.classgrade["SELVAL_"+partid];
 3155: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3156:         var override = document.classgrade["FORCE_"+partid].checked;
 3157: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3158: 	if (selval[1].selected || selval[2].selected) {
 3159: 	    for (var i=0; i<radioButton.length; i++) {
 3160: 		radioButton[i].checked=false;
 3161: 
 3162: 	    }
 3163: 	    textbox.value = "";
 3164: 
 3165: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3166: 		var user = document.classgrade["ctr"+i].value;
 3167: 		user = user.replace(new RegExp(':', 'g'),"_");
 3168: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3169: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3170: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3171: 		if ((saveval != "correct") || override) {
 3172: 		    scorename.value = "";
 3173: 		    if (selval[1].selected) {
 3174: 			selname[1].selected = true;
 3175: 		    } else {
 3176: 			selname[2].selected = true;
 3177: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3178: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3179: 		    }
 3180: 		}
 3181: 	    }
 3182: 	} else {
 3183: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3184: 		var user = document.classgrade["ctr"+i].value;
 3185: 		user = user.replace(new RegExp(':', 'g'),"_");
 3186: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3187: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3188: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3189: 		if ((saveval != "correct") || override) {
 3190: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3191: 		    selname[0].selected = true;
 3192: 		}
 3193: 	    }
 3194: 	}	    
 3195:     }
 3196: 
 3197:     function changeSelect(partid,user) {
 3198: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3199: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3200: 	var point  = textbox.value;
 3201: 	var weight = document.classgrade["weight_"+partid].value;
 3202: 
 3203: 	if (isNaN(point) || parseFloat(point) < 0) {
 3204: 	    alert("$alertmsg"+parseFloat(point));
 3205: 	    textbox.value = "";
 3206: 	    return;
 3207: 	}
 3208: 	if (parseFloat(point) > parseFloat(weight)) {
 3209: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3210: 			       ") greater than the weight of the part. Accept?");
 3211: 	    if (resp == false) {
 3212: 		textbox.value = "";
 3213: 		return;
 3214: 	    }
 3215: 	}
 3216: 	selval[0].selected = true;
 3217:     }
 3218: 
 3219:     function changeOneScore(partid,user) {
 3220: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3221: 	if (selval[1].selected || selval[2].selected) {
 3222: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3223: 	    if (selval[2].selected) {
 3224: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3225: 	    }
 3226:         }
 3227:     }
 3228: 
 3229:     function resetEntry(numpart) {
 3230: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3231: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3232: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3233: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3234: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3235: 	    for (var i=0; i<radioButton.length; i++) {
 3236: 		radioButton[i].checked=false;
 3237: 
 3238: 	    }
 3239: 	    textbox.value = "";
 3240: 	    selval[0].selected = true;
 3241: 
 3242: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3243: 		var user = document.classgrade["ctr"+i].value;
 3244: 		user = user.replace(new RegExp(':', 'g'),"_");
 3245: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3246: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3247: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3248: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3249: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3250: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3251: 		if (saveselval == "excused") {
 3252: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3253: 		} else {
 3254: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3255: 		}
 3256: 	    }
 3257: 	}
 3258:     }
 3259: 
 3260: </script>
 3261: VIEWJAVASCRIPT
 3262: }
 3263: 
 3264: #--- show scores for a section or whole class w/ option to change/update a score
 3265: sub viewgrades {
 3266:     my ($request) = shift;
 3267:     &viewgrades_js($request);
 3268: 
 3269:     my ($symb) = &get_symb($request);
 3270:     #need to make sure we have the correct data for later EXT calls, 
 3271:     #thus invalidate the cache
 3272:     &Apache::lonnet::devalidatecourseresdata(
 3273:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3274:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3275:     &Apache::lonnet::clear_EXT_cache_status();
 3276: 
 3277:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3278:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3279: 
 3280:     #view individual student submission form - called using Javascript viewOneStudent
 3281:     $result.=&jscriptNform($symb);
 3282: 
 3283:     #beginning of class grading form
 3284:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3285:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3286: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3287: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3288: 	&build_section_inputs().
 3289: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3290: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3291: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3292: 
 3293:     my ($common_header,$specific_header);
 3294:     if ($env{'form.section'} eq 'all') {
 3295: 	$common_header = &mt('Assign Common Grade to Class');
 3296:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3297:     } elsif ($env{'form.section'} eq 'none') {
 3298:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3299: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3300:     } else {
 3301:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3302:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3303: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3304:     }
 3305:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3306:     #radio buttons/text box for assigning points for a section or class.
 3307:     #handles different parts of a problem
 3308:     my $res_error;
 3309:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3310:     if ($res_error) {
 3311:         return &navmap_errormsg();
 3312:     }
 3313:     my %weight = ();
 3314:     my $ctsparts = 0;
 3315:     my %seen = ();
 3316:     my @part_response_id = &flatten_responseType($responseType);
 3317:     foreach my $part_response_id (@part_response_id) {
 3318:     	my ($partid,$respid) = @{ $part_response_id };
 3319: 	my $part_resp = join('_',@{ $part_response_id });
 3320: 	next if $seen{$partid};
 3321: 	$seen{$partid}++;
 3322: 	my $handgrade=$$handgrade{$part_resp};
 3323: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3324: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3325: 
 3326: 	my $display_part=&get_display_part($partid,$symb);
 3327: 	my $radio.='<table border="0"><tr>';  
 3328: 	my $ctr = 0;
 3329: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3330: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3331: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3332: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3333: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3334: 	    $ctr++;
 3335: 	}
 3336: 	$radio.='</tr></table>';
 3337: 	my $line = '<input type="text" name="TEXTVAL_'.
 3338: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3339: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3340: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3341: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3342: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3343: 		$weight{$partid}.')"> '.
 3344: 	    '<option selected="selected"> </option>'.
 3345: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3346: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3347: 	    '</select></td>'.
 3348:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3349: 	$line.='<input type="hidden" name="partid_'.
 3350: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3351: 	$line.='<input type="hidden" name="weight_'.
 3352: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3353: 
 3354: 	$result.=
 3355: 	    &Apache::loncommon::start_data_table_row()."\n".
 3356: 	    '<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>'.
 3357: 	    &Apache::loncommon::end_data_table_row()."\n";
 3358: 	$ctsparts++;
 3359:     }
 3360:     $result.=&Apache::loncommon::end_data_table()."\n".
 3361: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3362:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3363: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3364: 
 3365:     #table listing all the students in a section/class
 3366:     #header of table
 3367:     $result.= '<h3>'.$specific_header.'</h3>'.
 3368:               &Apache::loncommon::start_data_table().
 3369: 	      &Apache::loncommon::start_data_table_header_row().
 3370: 	      '<th>'.&mt('No.').'</th>'.
 3371: 	      '<th>'.&nameUserString('header')."</th>\n";
 3372:     my $partserror;
 3373:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3374:     if ($partserror) {
 3375:         return &navmap_errormsg();
 3376:     }
 3377:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3378:     my @partids = ();
 3379:     foreach my $part (@parts) {
 3380: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3381:         my $narrowtext = &mt('Tries');
 3382: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3383: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3384: 	my ($partid) = &split_part_type($part);
 3385:         push(@partids,$partid);
 3386: 	my $display_part=&get_display_part($partid,$symb);
 3387: 	if ($display =~ /^Partial Credit Factor/) {
 3388: 	    $result.='<th>'.
 3389: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3390: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3391: 	    next;
 3392: 	    
 3393: 	} else {
 3394: 	    if ($display =~ /Problem Status/) {
 3395: 		my $grade_status_mt = &mt('Grade Status');
 3396: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3397: 	    }
 3398: 	    my $part_mt = &mt('Part:');
 3399: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3400: 	}
 3401: 
 3402: 	$result.='<th>'.$display.'</th>'."\n";
 3403:     }
 3404:     $result.=&Apache::loncommon::end_data_table_header_row();
 3405: 
 3406:     my %last_resets = 
 3407: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3408: 
 3409:     #get info for each student
 3410:     #list all the students - with points and grade status
 3411:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3412:     my $ctr = 0;
 3413:     foreach (sort 
 3414: 	     {
 3415: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3416: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3417: 		 }
 3418: 		 return $a cmp $b;
 3419: 	     } (keys(%$fullname))) {
 3420: 	$ctr++;
 3421: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3422: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3423:     }
 3424:     $result.=&Apache::loncommon::end_data_table();
 3425:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3426:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3427: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3428:     if (scalar(%$fullname) eq 0) {
 3429: 	my $colspan=3+scalar(@parts);
 3430: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3431:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3432: 	$result='<span class="LC_warning">'.
 3433: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3434: 	        $section_display, $stu_status).
 3435: 	    '</span>';
 3436:     }
 3437:     $result.=&show_grading_menu_form($symb);
 3438:     return $result;
 3439: }
 3440: 
 3441: #--- call by previous routine to display each student
 3442: sub viewstudentgrade {
 3443:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3444:     my ($uname,$udom) = split(/:/,$student);
 3445:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3446:     my %aggregates = (); 
 3447:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3448: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3449: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3450: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3451: 	'\');" target="_self">'.$fullname.'</a> '.
 3452: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3453:     $student=~s/:/_/; # colon doen't work in javascript for names
 3454:     foreach my $apart (@$parts) {
 3455: 	my ($part,$type) = &split_part_type($apart);
 3456: 	my $score=$record{"resource.$part.$type"};
 3457:         $result.='<td align="center">';
 3458:         my ($aggtries,$totaltries);
 3459:         unless (exists($aggregates{$part})) {
 3460: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3461: 
 3462: 	    $aggtries = $totaltries;
 3463:             if ($$last_resets{$part}) {  
 3464:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3465: 					   $part);
 3466:             }
 3467:             $result.='<input type="hidden" name="'.
 3468:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3469:             $result.='<input type="hidden" name="'.
 3470:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3471:             $aggregates{$part} = 1;
 3472:         }
 3473: 	if ($type eq 'awarded') {
 3474: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3475: 	    $result.='<input type="hidden" name="'.
 3476: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3477: 	    $result.='<input type="text" name="'.
 3478: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3479: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3480: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3481: 	} elsif ($type eq 'solved') {
 3482: 	    my ($status,$foo)=split(/_/,$score,2);
 3483: 	    $status = 'nothing' if ($status eq '');
 3484: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3485: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3486: 	    $result.='&nbsp;<select name="'.
 3487: 		'GD_'.$student.'_'.$part.'_solved" '.
 3488: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3489: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3490: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3491: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3492: 	    $result.="</select>&nbsp;</td>\n";
 3493: 	} else {
 3494: 	    $result.='<input type="hidden" name="'.
 3495: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3496: 		    "\n";
 3497: 	    $result.='<input type="text" name="'.
 3498: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3499: 		'value="'.$score.'" size="4" /></td>'."\n";
 3500: 	}
 3501:     }
 3502:     $result.=&Apache::loncommon::end_data_table_row();
 3503:     return $result;
 3504: }
 3505: 
 3506: #--- change scores for all the students in a section/class
 3507: #    record does not get update if unchanged
 3508: sub editgrades {
 3509:     my ($request) = @_;
 3510: 
 3511:     my $symb=&get_symb($request);
 3512:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3513:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3514:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3515:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3516: 
 3517:     my $result= &Apache::loncommon::start_data_table().
 3518: 	&Apache::loncommon::start_data_table_header_row().
 3519: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3520: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3521:     my %scoreptr = (
 3522: 		    'correct'  =>'correct_by_override',
 3523: 		    'incorrect'=>'incorrect_by_override',
 3524: 		    'excused'  =>'excused',
 3525: 		    'ungraded' =>'ungraded_attempted',
 3526: 		    'nothing'  => '',
 3527: 		    );
 3528:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3529: 
 3530:     my (@partid);
 3531:     my %weight = ();
 3532:     my %columns = ();
 3533:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3534: 
 3535:     my $partserror;
 3536:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3537:     if ($partserror) {
 3538:         return &navmap_errormsg();
 3539:     }
 3540:     my $header;
 3541:     while ($ctr < $env{'form.totalparts'}) {
 3542: 	my $partid = $env{'form.partid_'.$ctr};
 3543: 	push(@partid,$partid);
 3544: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3545: 	$ctr++;
 3546:     }
 3547:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3548:     foreach my $partid (@partid) {
 3549: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3550: 	    '<th align="center">'.&mt('New Score').'</th>';
 3551: 	$columns{$partid}=2;
 3552: 	foreach my $stores (@parts) {
 3553: 	    my ($part,$type) = &split_part_type($stores);
 3554: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3555: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3556: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3557: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3558:             my $narrowtext = &mt('Tries');
 3559: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3560: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3561: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3562: 	    $columns{$partid}+=2;
 3563: 	}
 3564:     }
 3565:     foreach my $partid (@partid) {
 3566: 	my $display_part=&get_display_part($partid,$symb);
 3567: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3568: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3569: 	    '</th>';
 3570: 
 3571:     }
 3572:     $result .= &Apache::loncommon::end_data_table_header_row().
 3573: 	&Apache::loncommon::start_data_table_header_row().
 3574: 	$header.
 3575: 	&Apache::loncommon::end_data_table_header_row();
 3576:     my @noupdate;
 3577:     my ($updateCtr,$noupdateCtr) = (1,1);
 3578:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3579: 	my $line;
 3580: 	my $user = $env{'form.ctr'.$i};
 3581: 	my ($uname,$udom)=split(/:/,$user);
 3582: 	my %newrecord;
 3583: 	my $updateflag = 0;
 3584: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3585: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3586: 	if (!&canmodify($usec)) {
 3587: 	    my $numcols=scalar(@partid)*4+2;
 3588: 	    push(@noupdate,
 3589: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3590: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3591: 	    next;
 3592: 	}
 3593:         my %aggregate = ();
 3594:         my $aggregateflag = 0;
 3595: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3596: 	foreach (@partid) {
 3597: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3598: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3599: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3600: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3601: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3602: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3603: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3604: 	    my $score;
 3605: 	    if ($partial eq '') {
 3606: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3607: 	    } elsif ($partial > 0) {
 3608: 		$score = 'correct_by_override';
 3609: 	    } elsif ($partial == 0) {
 3610: 		$score = 'incorrect_by_override';
 3611: 	    }
 3612: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3613: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3614: 
 3615: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3616: 		"$env{'user.name'}:$env{'user.domain'}";
 3617: 	    if ($dropMenu eq 'reset status' &&
 3618: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3619: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3620: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3621: 		$newrecord{'resource.'.$_.'.award'} = '';
 3622: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3623: 		$updateflag = 1;
 3624:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3625:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3626:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3627:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3628:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3629:                     $aggregateflag = 1;
 3630:                 }
 3631: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3632: 		$updateflag = 1;
 3633: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3634: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3635: 		$rec_update++;
 3636: 	    }
 3637: 
 3638: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3639: 		'<td align="center">'.$awarded.
 3640: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3641: 
 3642: 
 3643: 	    my $partid=$_;
 3644: 	    foreach my $stores (@parts) {
 3645: 		my ($part,$type) = &split_part_type($stores);
 3646: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3647: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3648: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3649: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3650: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3651: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3652: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3653: 		    $updateflag=1;
 3654: 		}
 3655: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3656: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3657: 	    }
 3658: 	}
 3659: 	$line.="\n";
 3660: 
 3661: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3662: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3663: 
 3664: 	if ($updateflag) {
 3665: 	    $count++;
 3666: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3667: 				    $udom,$uname);
 3668: 
 3669: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3670: 					      $cnum,$udom,$uname)) {
 3671: 		# need to figure out if should be in queue.
 3672: 		my %record =  
 3673: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3674: 					     $udom,$uname);
 3675: 		my $all_graded = 1;
 3676: 		my $none_graded = 1;
 3677: 		foreach my $part (@parts) {
 3678: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3679: 			$all_graded = 0;
 3680: 		    } else {
 3681: 			$none_graded = 0;
 3682: 		    }
 3683: 		}
 3684: 
 3685: 		if ($all_graded || $none_graded) {
 3686: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3687: 							   $symb,$cdom,$cnum,
 3688: 							   $udom,$uname);
 3689: 		}
 3690: 	    }
 3691: 
 3692: 	    $result.=&Apache::loncommon::start_data_table_row().
 3693: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3694: 		&Apache::loncommon::end_data_table_row();
 3695: 	    $updateCtr++;
 3696: 	} else {
 3697: 	    push(@noupdate,
 3698: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3699: 	    $noupdateCtr++;
 3700: 	}
 3701:         if ($aggregateflag) {
 3702:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3703: 				  $cdom,$cnum);
 3704:         }
 3705:     }
 3706:     if (@noupdate) {
 3707: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3708: 	my $numcols=scalar(@partid)*4+2;
 3709: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3710: 	    '<td align="center" colspan="'.$numcols.'">'.
 3711: 	    &mt('No Changes Occurred For the Students Below').
 3712: 	    '</td>'.
 3713: 	    &Apache::loncommon::end_data_table_row();
 3714: 	foreach my $line (@noupdate) {
 3715: 	    $result.=
 3716: 		&Apache::loncommon::start_data_table_row().
 3717: 		$line.
 3718: 		&Apache::loncommon::end_data_table_row();
 3719: 	}
 3720:     }
 3721:     $result .= &Apache::loncommon::end_data_table().
 3722: 	&show_grading_menu_form($symb);
 3723:     my $msg = '<p><b>'.
 3724: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3725: 	    $rec_update,$count).'</b><br />'.
 3726: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3727: 	'</b></p>';
 3728:     return $title.$msg.$result;
 3729: }
 3730: 
 3731: sub split_part_type {
 3732:     my ($partstr) = @_;
 3733:     my ($temp,@allparts)=split(/_/,$partstr);
 3734:     my $type=pop(@allparts);
 3735:     my $part=join('_',@allparts);
 3736:     return ($part,$type);
 3737: }
 3738: 
 3739: #------------- end of section for handling grading by section/class ---------
 3740: #
 3741: #----------------------------------------------------------------------------
 3742: 
 3743: 
 3744: #----------------------------------------------------------------------------
 3745: #
 3746: #-------------------------- Next few routines handles grading by csv upload
 3747: #
 3748: #--- Javascript to handle csv upload
 3749: sub csvupload_javascript_reverse_associate {
 3750:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3751:     my $error2=&mt('You need to specify at least one grading field');
 3752:   return(<<ENDPICK);
 3753:   function verify(vf) {
 3754:     var foundsomething=0;
 3755:     var founduname=0;
 3756:     var foundID=0;
 3757:     for (i=0;i<=vf.nfields.value;i++) {
 3758:       tw=eval('vf.f'+i+'.selectedIndex');
 3759:       if (i==0 && tw!=0) { foundID=1; }
 3760:       if (i==1 && tw!=0) { founduname=1; }
 3761:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3762:     }
 3763:     if (founduname==0 && foundID==0) {
 3764: 	alert('$error1');
 3765: 	return;
 3766:     }
 3767:     if (foundsomething==0) {
 3768: 	alert('$error2');
 3769: 	return;
 3770:     }
 3771:     vf.submit();
 3772:   }
 3773:   function flip(vf,tf) {
 3774:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3775:     var i;
 3776:     for (i=0;i<=vf.nfields.value;i++) {
 3777:       //can not pick the same destination field for both name and domain
 3778:       if (((i ==0)||(i ==1)) && 
 3779:           ((tf==0)||(tf==1)) && 
 3780:           (i!=tf) &&
 3781:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3782:         eval('vf.f'+i+'.selectedIndex=0;')
 3783:       }
 3784:     }
 3785:   }
 3786: ENDPICK
 3787: }
 3788: 
 3789: sub csvupload_javascript_forward_associate {
 3790:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3791:     my $error2=&mt('You need to specify at least one grading field');
 3792:   return(<<ENDPICK);
 3793:   function verify(vf) {
 3794:     var foundsomething=0;
 3795:     var founduname=0;
 3796:     var foundID=0;
 3797:     for (i=0;i<=vf.nfields.value;i++) {
 3798:       tw=eval('vf.f'+i+'.selectedIndex');
 3799:       if (tw==1) { foundID=1; }
 3800:       if (tw==2) { founduname=1; }
 3801:       if (tw>3) { foundsomething=1; }
 3802:     }
 3803:     if (founduname==0 && foundID==0) {
 3804: 	alert('$error1');
 3805: 	return;
 3806:     }
 3807:     if (foundsomething==0) {
 3808: 	alert('$error2');
 3809: 	return;
 3810:     }
 3811:     vf.submit();
 3812:   }
 3813:   function flip(vf,tf) {
 3814:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3815:     var i;
 3816:     //can not pick the same destination field twice
 3817:     for (i=0;i<=vf.nfields.value;i++) {
 3818:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3819:         eval('vf.f'+i+'.selectedIndex=0;')
 3820:       }
 3821:     }
 3822:   }
 3823: ENDPICK
 3824: }
 3825: 
 3826: sub csvuploadmap_header {
 3827:     my ($request,$symb,$datatoken,$distotal)= @_;
 3828:     my $javascript;
 3829:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3830: 	$javascript=&csvupload_javascript_reverse_associate();
 3831:     } else {
 3832: 	$javascript=&csvupload_javascript_forward_associate();
 3833:     }
 3834: 
 3835:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3836:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3837:     my $ignore=&mt('Ignore First Line');
 3838:     $symb = &Apache::lonenc::check_encrypt($symb);
 3839:     $request->print(<<ENDPICK);
 3840: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3841: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3842: $result
 3843: <hr />
 3844: <h3>Identify fields</h3>
 3845: Total number of records found in file: $distotal <hr />
 3846: Enter as many fields as you can. The system will inform you and bring you back
 3847: to this page if the data selected is insufficient to run your class.<hr />
 3848: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3849: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3850: <input type="hidden" name="associate"  value="" />
 3851: <input type="hidden" name="phase"      value="three" />
 3852: <input type="hidden" name="datatoken"  value="$datatoken" />
 3853: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3854: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3855: <input type="hidden" name="upfile_associate" 
 3856:                                        value="$env{'form.upfile_associate'}" />
 3857: <input type="hidden" name="symb"       value="$symb" />
 3858: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3859: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3860: <input type="hidden" name="command"    value="csvuploadoptions" />
 3861: <hr />
 3862: <script type="text/javascript" language="Javascript">
 3863: $javascript
 3864: </script>
 3865: ENDPICK
 3866:     return '';
 3867: 
 3868: }
 3869: 
 3870: sub csvupload_fields {
 3871:     my ($symb,$errorref) = @_;
 3872:     my (@parts) = &getpartlist($symb,$errorref);
 3873:     if (ref($errorref)) {
 3874:         if ($$errorref) {
 3875:             return;
 3876:         }
 3877:     }
 3878: 
 3879:     my @fields=(['ID','Student/Employee ID'],
 3880: 		['username','Student Username'],
 3881: 		['domain','Student Domain']);
 3882:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3883:     foreach my $part (sort(@parts)) {
 3884: 	my @datum;
 3885: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3886: 	my $name=$part;
 3887: 	if  (!$display) { $display = $name; }
 3888: 	@datum=($name,$display);
 3889: 	if ($name=~/^stores_(.*)_awarded/) {
 3890: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3891: 	}
 3892: 	push(@fields,\@datum);
 3893:     }
 3894:     return (@fields);
 3895: }
 3896: 
 3897: sub csvuploadmap_footer {
 3898:     my ($request,$i,$keyfields) =@_;
 3899:     $request->print(<<ENDPICK);
 3900: </table>
 3901: <input type="hidden" name="nfields" value="$i" />
 3902: <input type="hidden" name="keyfields" value="$keyfields" />
 3903: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3904: </form>
 3905: ENDPICK
 3906: }
 3907: 
 3908: sub checkforfile_js {
 3909:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3910:     my $result =<<CSVFORMJS;
 3911: <script type="text/javascript" language="javascript">
 3912:     function checkUpload(formname) {
 3913: 	if (formname.upfile.value == "") {
 3914: 	    alert("$alertmsg");
 3915: 	    return false;
 3916: 	}
 3917: 	formname.submit();
 3918:     }
 3919:     </script>
 3920: CSVFORMJS
 3921:     return $result;
 3922: }
 3923: 
 3924: sub upcsvScores_form {
 3925:     my ($request) = shift;
 3926:     my ($symb)=&get_symb($request);
 3927:     if (!$symb) {return '';}
 3928:     my $result=&checkforfile_js();
 3929:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3930:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3931:     $result.=$table;
 3932:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3933:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3934:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3935: 	'</b></td></tr>'."\n";
 3936:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3937:     my $upload=&mt("Upload Scores");
 3938:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3939:     my $ignore=&mt('Ignore First Line');
 3940:     $symb = &Apache::lonenc::check_encrypt($symb);
 3941:     $result.=<<ENDUPFORM;
 3942: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3943: <input type="hidden" name="symb" value="$symb" />
 3944: <input type="hidden" name="command" value="csvuploadmap" />
 3945: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3946: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3947: $upfile_select
 3948: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3949: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3950: </form>
 3951: ENDUPFORM
 3952:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3953:                            &mt("How do I create a CSV file from a spreadsheet"))
 3954:     .'</td></tr></table>'."\n";
 3955:     $result.='</td></tr></table><br /><br />'."\n";
 3956:     $result.=&show_grading_menu_form($symb);
 3957:     return $result;
 3958: }
 3959: 
 3960: 
 3961: sub csvuploadmap {
 3962:     my ($request)= @_;
 3963:     my ($symb)=&get_symb($request);
 3964:     if (!$symb) {return '';}
 3965: 
 3966:     my $datatoken;
 3967:     if (!$env{'form.datatoken'}) {
 3968: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3969:     } else {
 3970: 	$datatoken=$env{'form.datatoken'};
 3971: 	&Apache::loncommon::load_tmp_file($request);
 3972:     }
 3973:     my @records=&Apache::loncommon::upfile_record_sep();
 3974:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3975:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3976:     my ($i,$keyfields);
 3977:     if (@records) {
 3978:         my $fieldserror;
 3979: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3980:         if ($fieldserror) {
 3981:             $request->print(&navmap_errormsg());
 3982:             return;
 3983:         }
 3984: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3985: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3986: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3987: 							  \@fields);
 3988: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3989: 	    chop($keyfields);
 3990: 	} else {
 3991: 	    unshift(@fields,['none','']);
 3992: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3993: 							    \@fields);
 3994:             foreach my $rec (@records) {
 3995:                 my %temp = &Apache::loncommon::record_sep($rec);
 3996:                 if (%temp) {
 3997:                     $keyfields=join(',',sort(keys(%temp)));
 3998:                     last;
 3999:                 }
 4000:             }
 4001: 	}
 4002:     }
 4003:     &csvuploadmap_footer($request,$i,$keyfields);
 4004:     $request->print(&show_grading_menu_form($symb));
 4005: 
 4006:     return '';
 4007: }
 4008: 
 4009: sub csvuploadoptions {
 4010:     my ($request)= @_;
 4011:     my ($symb)=&get_symb($request);
 4012:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4013:     my $ignore=&mt('Ignore First Line');
 4014:     $request->print(<<ENDPICK);
 4015: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4016: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4017: <input type="hidden" name="command"    value="csvuploadassign" />
 4018: <!--
 4019: <p>
 4020: <label>
 4021:    <input type="checkbox" name="show_full_results" />
 4022:    Show a table of all changes
 4023: </label>
 4024: </p>
 4025: -->
 4026: <p>
 4027: <label>
 4028:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4029:    Overwrite any existing score
 4030: </label>
 4031: </p>
 4032: ENDPICK
 4033:     my %fields=&get_fields();
 4034:     if (!defined($fields{'domain'})) {
 4035: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4036: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4037:     }
 4038:     foreach my $key (sort(keys(%env))) {
 4039: 	if ($key !~ /^form\.(.*)$/) { next; }
 4040: 	my $cleankey=$1;
 4041: 	if ($cleankey eq 'command') { next; }
 4042: 	$request->print('<input type="hidden" name="'.$cleankey.
 4043: 			'"  value="'.$env{$key}.'" />'."\n");
 4044:     }
 4045:     # FIXME do a check for any duplicated user ids...
 4046:     # FIXME do a check for any invalid user ids?...
 4047:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4048: <hr /></form>'."\n");
 4049:     $request->print(&show_grading_menu_form($symb));
 4050:     return '';
 4051: }
 4052: 
 4053: sub get_fields {
 4054:     my %fields;
 4055:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4056:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4057: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4058: 	    if ($env{'form.f'.$i} ne 'none') {
 4059: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4060: 	    }
 4061: 	} else {
 4062: 	    if ($env{'form.f'.$i} ne 'none') {
 4063: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4064: 	    }
 4065: 	}
 4066:     }
 4067:     return %fields;
 4068: }
 4069: 
 4070: sub csvuploadassign {
 4071:     my ($request)= @_;
 4072:     my ($symb)=&get_symb($request);
 4073:     if (!$symb) {return '';}
 4074:     my $error_msg = '';
 4075:     &Apache::loncommon::load_tmp_file($request);
 4076:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4077:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4078:     my %fields=&get_fields();
 4079:     $request->print('<h3>Assigning Grades</h3>');
 4080:     my $courseid=$env{'request.course.id'};
 4081:     my ($classlist) = &getclasslist('all',0);
 4082:     my @notallowed;
 4083:     my @skipped;
 4084:     my $countdone=0;
 4085:     foreach my $grade (@gradedata) {
 4086: 	my %entries=&Apache::loncommon::record_sep($grade);
 4087: 	my $domain;
 4088: 	if ($entries{$fields{'domain'}}) {
 4089: 	    $domain=$entries{$fields{'domain'}};
 4090: 	} else {
 4091: 	    $domain=$env{'form.default_domain'};
 4092: 	}
 4093: 	$domain=~s/\s//g;
 4094: 	my $username=$entries{$fields{'username'}};
 4095: 	$username=~s/\s//g;
 4096: 	if (!$username) {
 4097: 	    my $id=$entries{$fields{'ID'}};
 4098: 	    $id=~s/\s//g;
 4099: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4100: 	    $username=$ids{$id};
 4101: 	}
 4102: 	if (!exists($$classlist{"$username:$domain"})) {
 4103: 	    my $id=$entries{$fields{'ID'}};
 4104: 	    $id=~s/\s//g;
 4105: 	    if ($id) {
 4106: 		push(@skipped,"$id:$domain");
 4107: 	    } else {
 4108: 		push(@skipped,"$username:$domain");
 4109: 	    }
 4110: 	    next;
 4111: 	}
 4112: 	my $usec=$classlist->{"$username:$domain"}[5];
 4113: 	if (!&canmodify($usec)) {
 4114: 	    push(@notallowed,"$username:$domain");
 4115: 	    next;
 4116: 	}
 4117: 	my %points;
 4118: 	my %grades;
 4119: 	foreach my $dest (keys(%fields)) {
 4120: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4121: 		$dest eq 'domain') { next; }
 4122: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4123: 	    if ($dest=~/stores_(.*)_points/) {
 4124: 		my $part=$1;
 4125: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4126: 					      $symb,$domain,$username);
 4127:                 if ($wgt) {
 4128:                     $entries{$fields{$dest}}=~s/\s//g;
 4129:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4130:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4131:                                           : 'correct_by_override';
 4132:                     $grades{"resource.$part.awarded"}=$pcr;
 4133:                     $grades{"resource.$part.solved"}=$award;
 4134:                     $points{$part}=1;
 4135:                 } else {
 4136:                     $error_msg = "<br />" .
 4137:                         &mt("Some point values were assigned"
 4138:                             ." for problems with a weight "
 4139:                             ."of zero. These values were "
 4140:                             ."ignored.");
 4141:                 }
 4142: 	    } else {
 4143: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4144: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4145: 		my $store_key=$dest;
 4146: 		$store_key=~s/^stores/resource/;
 4147: 		$store_key=~s/_/\./g;
 4148: 		$grades{$store_key}=$entries{$fields{$dest}};
 4149: 	    }
 4150: 	}
 4151: 	if (! %grades) { 
 4152:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4153:         } else {
 4154: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4155: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4156: 					   $env{'request.course.id'},
 4157: 					   $domain,$username);
 4158: 	   if ($result eq 'ok') {
 4159: 	      $request->print('.');
 4160: 	   } else {
 4161: 	      $request->print("<p><span class=\"LC_error\">".
 4162:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4163:                                   "$username:$domain",$result)."</span></p>");
 4164: 	   }
 4165: 	   $request->rflush();
 4166: 	   $countdone++;
 4167:         }
 4168:     }
 4169:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4170:     if (@skipped) {
 4171: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4172:         $request->print(join(', ',@skipped));
 4173:     }
 4174:     if (@notallowed) {
 4175: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4176: 	$request->print(join(', ',@notallowed));
 4177:     }
 4178:     $request->print("<br />\n");
 4179:     $request->print(&show_grading_menu_form($symb));
 4180:     return $error_msg;
 4181: }
 4182: #------------- end of section for handling csv file upload ---------
 4183: #
 4184: #-------------------------------------------------------------------
 4185: #
 4186: #-------------- Next few routines handle grading by page/sequence
 4187: #
 4188: #--- Select a page/sequence and a student to grade
 4189: sub pickStudentPage {
 4190:     my ($request) = shift;
 4191: 
 4192:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4193:     $request->print(<<LISTJAVASCRIPT);
 4194: <script type="text/javascript" language="javascript">
 4195: 
 4196: function checkPickOne(formname) {
 4197:     if (radioSelection(formname.student) == null) {
 4198: 	alert("$alertmsg");
 4199: 	return;
 4200:     }
 4201:     ptr = pullDownSelection(formname.selectpage);
 4202:     formname.page.value = formname["page"+ptr].value;
 4203:     formname.title.value = formname["title"+ptr].value;
 4204:     formname.submit();
 4205: }
 4206: 
 4207: </script>
 4208: LISTJAVASCRIPT
 4209:     &commonJSfunctions($request);
 4210:     my ($symb) = &get_symb($request);
 4211:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4212:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4213:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4214: 
 4215:     my $result='<h3><span class="LC_info">&nbsp;'.
 4216: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4217: 
 4218:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4219:     my $map_error;
 4220:     my ($titles,$symbx) = &getSymbMap($map_error);
 4221:     if ($map_error) {
 4222:         $request->print(&navmap_errormsg());
 4223:         return; 
 4224:     }
 4225:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4226: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4227: #    my $type=($curpage =~ /\.(page|sequence)/);
 4228:     my $select = '<select name="selectpage">'."\n";
 4229:     my $ctr=0;
 4230:     foreach (@$titles) {
 4231: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4232: 	$select.='<option value="'.$ctr.'" '.
 4233: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4234: 	    '>'.$showtitle.'</option>'."\n";
 4235: 	$ctr++;
 4236:     }
 4237:     $select.= '</select>';
 4238:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4239: 
 4240:     $ctr=0;
 4241:     foreach (@$titles) {
 4242: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4243: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4244: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4245: 	$ctr++;
 4246:     }
 4247:     $result.='<input type="hidden" name="page" />'."\n".
 4248: 	'<input type="hidden" name="title" />'."\n";
 4249: 
 4250:     my $options =
 4251: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4252: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4253:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4254: 
 4255:     $options =
 4256: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4257: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4258: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4259:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4260:     
 4261:     $result.=&build_section_inputs();
 4262:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4263:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4264: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4265: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4266: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4267: 
 4268:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4269: 
 4270:     $result.='&nbsp;<input type="button" '.
 4271: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4272: 
 4273:     $request->print($result);
 4274: 
 4275:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4276: 	&Apache::loncommon::start_data_table().
 4277: 	&Apache::loncommon::start_data_table_header_row().
 4278: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4279: 	'<th>'.&nameUserString('header').'</th>'.
 4280: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4281: 	'<th>'.&nameUserString('header').'</th>'.
 4282: 	&Apache::loncommon::end_data_table_header_row();
 4283:  
 4284:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4285:     my $ptr = 1;
 4286:     foreach my $student (sort 
 4287: 			 {
 4288: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4289: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4290: 			     }
 4291: 			     return $a cmp $b;
 4292: 			 } (keys(%$fullname))) {
 4293: 	my ($uname,$udom) = split(/:/,$student);
 4294: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4295:                                   : '</td>');
 4296: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4297: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4298: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4299: 	$studentTable.=
 4300: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4301:                          : '');
 4302: 	$ptr++;
 4303:     }
 4304:     if ($ptr%2 == 0) {
 4305: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4306: 	    &Apache::loncommon::end_data_table_row();
 4307:     }
 4308:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4309:     $studentTable.='<input type="button" '.
 4310: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4311: 
 4312:     $studentTable.=&show_grading_menu_form($symb);
 4313:     $request->print($studentTable);
 4314: 
 4315:     return '';
 4316: }
 4317: 
 4318: sub getSymbMap {
 4319:     my ($map_error) = @_;
 4320:     my $navmap = Apache::lonnavmaps::navmap->new();
 4321:     unless (ref($navmap)) {
 4322:         if (ref($map_error)) {
 4323:             $$map_error = 'navmap';
 4324:         }
 4325:         return;
 4326:     }
 4327:     my %symbx = ();
 4328:     my @titles = ();
 4329:     my $minder = 0;
 4330: 
 4331:     # Gather every sequence that has problems.
 4332:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4333: 					       1,0,1);
 4334:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4335: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4336: 	    my $title = $minder.'.'.
 4337: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4338: 	    push(@titles, $title); # minder in case two titles are identical
 4339: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4340: 	    $minder++;
 4341: 	}
 4342:     }
 4343:     return \@titles,\%symbx;
 4344: }
 4345: 
 4346: #
 4347: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4348: sub displayPage {
 4349:     my ($request) = shift;
 4350: 
 4351:     my ($symb) = &get_symb($request);
 4352:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4353:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4354:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4355:     my $pageTitle = $env{'form.page'};
 4356:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4357:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4358:     my $usec=$classlist->{$env{'form.student'}}[5];
 4359: 
 4360:     #need to make sure we have the correct data for later EXT calls, 
 4361:     #thus invalidate the cache
 4362:     &Apache::lonnet::devalidatecourseresdata(
 4363:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4364:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4365:     &Apache::lonnet::clear_EXT_cache_status();
 4366: 
 4367:     if (!&canview($usec)) {
 4368: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4369: 	$request->print(&show_grading_menu_form($symb));
 4370: 	return;
 4371:     }
 4372:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4373:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4374: 	'</h3>'."\n";
 4375:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4376:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4377: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4378:     } else {
 4379: 	delete($env{'form.CODE'});
 4380:     }
 4381:     &sub_page_js($request);
 4382:     $request->print($result);
 4383: 
 4384:     my $navmap = Apache::lonnavmaps::navmap->new();
 4385:     unless (ref($navmap)) {
 4386:         $request->print(&navmap_errormsg());
 4387:         $request->print(&show_grading_menu_form($symb));
 4388:         return;
 4389:     }
 4390:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4391:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4392:     if (!$map) {
 4393: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4394: 	$request->print(&show_grading_menu_form($symb));
 4395: 	return; 
 4396:     }
 4397:     my $iterator = $navmap->getIterator($map->map_start(),
 4398: 					$map->map_finish());
 4399: 
 4400:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4401: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4402: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4403: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4404: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4405: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4406: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4407: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4408: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4409: 
 4410:     if (defined($env{'form.CODE'})) {
 4411: 	$studentTable.=
 4412: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4413:     }
 4414:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4415: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4416: 
 4417:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4418: 	&Apache::loncommon::start_data_table().
 4419: 	&Apache::loncommon::start_data_table_header_row().
 4420: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4421: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4422: 	&Apache::loncommon::end_data_table_header_row();
 4423: 
 4424:     &Apache::lonxml::clear_problem_counter();
 4425:     my ($depth,$question,$prob) = (1,1,1);
 4426:     $iterator->next(); # skip the first BEGIN_MAP
 4427:     my $curRes = $iterator->next(); # for "current resource"
 4428:     while ($depth > 0) {
 4429:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4430:         if($curRes == $iterator->END_MAP) { $depth--; }
 4431: 
 4432:         if (ref($curRes) && $curRes->is_problem()) {
 4433: 	    my $parts = $curRes->parts();
 4434:             my $title = $curRes->compTitle();
 4435: 	    my $symbx = $curRes->symb();
 4436: 	    $studentTable.=
 4437: 		&Apache::loncommon::start_data_table_row().
 4438: 		'<td align="center" valign="top" >'.$prob.
 4439: 		(scalar(@{$parts}) == 1 ? '' 
 4440: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4441: 							scalar(@{$parts}))
 4442: 		 ).
 4443: 		 '</td>';
 4444: 	    $studentTable.='<td valign="top">';
 4445: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4446: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4447: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4448: 					     undef,'both',\%form);
 4449: 	    } else {
 4450: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4451: 		$companswer =~ s|<form(.*?)>||g;
 4452: 		$companswer =~ s|</form>||g;
 4453: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4454: #		    $companswer =~ s/$1/ /ms;
 4455: #		    $request->print('match='.$1."<br />\n");
 4456: #		}
 4457: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4458: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4459: 	    }
 4460: 
 4461: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4462: 
 4463: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4464: 		if ($record{'version'} eq '') {
 4465: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4466: 		} else {
 4467: 		    my %responseType = ();
 4468: 		    foreach my $partid (@{$parts}) {
 4469: 			my @responseIds =$curRes->responseIds($partid);
 4470: 			my @responseType =$curRes->responseType($partid);
 4471: 			my %responseIds;
 4472: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4473: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4474: 			}
 4475: 			$responseType{$partid} = \%responseIds;
 4476: 		    }
 4477: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4478: 
 4479: 		}
 4480: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4481: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4482: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4483: 									$env{'request.course.id'},
 4484: 									'','.submission');
 4485:  
 4486: 	    }
 4487: 	    if (&canmodify($usec)) {
 4488: 		foreach my $partid (@{$parts}) {
 4489: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4490: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4491: 		    $question++;
 4492: 		}
 4493: 		$prob++;
 4494: 	    }
 4495: 	    $studentTable.='</td></tr>';
 4496: 
 4497: 	}
 4498:         $curRes = $iterator->next();
 4499:     }
 4500: 
 4501:     $studentTable.='</table>'."\n".
 4502: 	'<input type="button" value="'.&mt('Save').'" '.
 4503: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4504: 	'</form>'."\n";
 4505:     $studentTable.=&show_grading_menu_form($symb);
 4506:     $request->print($studentTable);
 4507: 
 4508:     return '';
 4509: }
 4510: 
 4511: sub displaySubByDates {
 4512:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4513:     my $isCODE=0;
 4514:     my $isTask = ($symb =~/\.task$/);
 4515:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4516:     my $studentTable=&Apache::loncommon::start_data_table().
 4517: 	&Apache::loncommon::start_data_table_header_row().
 4518: 	'<th>'.&mt('Date/Time').'</th>'.
 4519: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4520: 	'<th>'.&mt('Submission').'</th>'.
 4521: 	'<th>'.&mt('Status').'</th>'.
 4522: 	&Apache::loncommon::end_data_table_header_row();
 4523:     my ($version);
 4524:     my %mark;
 4525:     my %orders;
 4526:     $mark{'correct_by_student'} = $checkIcon;
 4527:     if (!exists($$record{'1:timestamp'})) {
 4528: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4529:     }
 4530: 
 4531:     my $interaction;
 4532:     my $no_increment = 1;
 4533:     for ($version=1;$version<=$$record{'version'};$version++) {
 4534: 	my $timestamp = 
 4535: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4536: 	if (exists($$record{$version.':resource.0.version'})) {
 4537: 	    $interaction = $$record{$version.':resource.0.version'};
 4538: 	}
 4539: 
 4540: 	my $where = ($isTask ? "$version:resource.$interaction"
 4541: 		             : "$version:resource");
 4542: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4543: 	    '<td>'.$timestamp.'</td>';
 4544: 	if ($isCODE) {
 4545: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4546: 	}
 4547: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4548: 	my @displaySub = ();
 4549: 	foreach my $partid (@{$parts}) {
 4550: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4551: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4552: 	    
 4553: 
 4554: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4555: 	    my $display_part=&get_display_part($partid,$symb);
 4556: 	    foreach my $matchKey (@matchKey) {
 4557: 		if (exists($$record{$version.':'.$matchKey}) &&
 4558: 		    $$record{$version.':'.$matchKey} ne '') {
 4559: 
 4560: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4561: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4562:                     $displaySub[0].='<span class="LC_nobreak"';
 4563:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4564:                                    .' <span class="LC_internal_info">'
 4565:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4566:                                    .'</span>'
 4567:                                    .' <b>';
 4568: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4569: 			$displaySub[0].=&mt('Trial not counted');
 4570: 		    } else {
 4571: 			$displaySub[0].=&mt('Trial: [_1]',
 4572: 					    $$record{"$where.$partid.tries"});
 4573: 		    }
 4574: 		    my $responseType=($isTask ? 'Task'
 4575:                                               : $responseType->{$partid}->{$responseId});
 4576: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4577: 		    if (!exists($orders{$partid}->{$responseId})) {
 4578: 			$orders{$partid}->{$responseId}=
 4579: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4580:                                        $no_increment);
 4581: 		    }
 4582: 		    $displaySub[0].='</b></span>'; # /nobreak
 4583: 		    $displaySub[0].='&nbsp; '.
 4584: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4585: 		}
 4586: 	    }
 4587: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4588: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4589: 				    $$record{"$where.$partid.checkedin"},
 4590: 				    $$record{"$where.$partid.checkedin.slot"}).
 4591: 					'<br />';
 4592: 	    }
 4593: 	    if (exists $$record{"$where.$partid.award"}) {
 4594: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4595: 		    lc($$record{"$where.$partid.award"}).' '.
 4596: 		    $mark{$$record{"$where.$partid.solved"}}.
 4597: 		    '<br />';
 4598: 	    }
 4599: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4600: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4601: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4602: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4603: 		$displaySub[2].=
 4604: 		    $$record{"$version:resource.$partid.regrader"}.
 4605: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4606: 	    }
 4607: 	}
 4608: 	# needed because old essay regrader has not parts info
 4609: 	if (exists $$record{"$version:resource.regrader"}) {
 4610: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4611: 	}
 4612: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4613: 	if ($displaySub[2]) {
 4614: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4615: 	}
 4616: 	$studentTable.='&nbsp;</td>'.
 4617: 	    &Apache::loncommon::end_data_table_row();
 4618:     }
 4619:     $studentTable.=&Apache::loncommon::end_data_table();
 4620:     return $studentTable;
 4621: }
 4622: 
 4623: sub updateGradeByPage {
 4624:     my ($request) = shift;
 4625: 
 4626:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4627:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4628:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4629:     my $pageTitle = $env{'form.page'};
 4630:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4631:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4632:     my $usec=$classlist->{$env{'form.student'}}[5];
 4633:     if (!&canmodify($usec)) {
 4634: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4635: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4636: 	return;
 4637:     }
 4638:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4639:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4640: 	'</h3>'."\n";
 4641: 
 4642:     $request->print($result);
 4643: 
 4644: 
 4645:     my $navmap = Apache::lonnavmaps::navmap->new();
 4646:     unless (ref($navmap)) {
 4647:         $request->print(&navmap_errormsg());
 4648:         return;
 4649:     }
 4650:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4651:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4652:     if (!$map) {
 4653: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4654: 	my ($symb)=&get_symb($request);
 4655: 	$request->print(&show_grading_menu_form($symb));
 4656: 	return; 
 4657:     }
 4658:     my $iterator = $navmap->getIterator($map->map_start(),
 4659: 					$map->map_finish());
 4660: 
 4661:     my $studentTable=
 4662: 	&Apache::loncommon::start_data_table().
 4663: 	&Apache::loncommon::start_data_table_header_row().
 4664: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4665: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4666: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4667: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4668: 	&Apache::loncommon::end_data_table_header_row();
 4669: 
 4670:     $iterator->next(); # skip the first BEGIN_MAP
 4671:     my $curRes = $iterator->next(); # for "current resource"
 4672:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4673:     while ($depth > 0) {
 4674:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4675:         if($curRes == $iterator->END_MAP) { $depth--; }
 4676: 
 4677:         if (ref($curRes) && $curRes->is_problem()) {
 4678: 	    my $parts = $curRes->parts();
 4679:             my $title = $curRes->compTitle();
 4680: 	    my $symbx = $curRes->symb();
 4681: 	    $studentTable.=
 4682: 		&Apache::loncommon::start_data_table_row().
 4683: 		'<td align="center" valign="top" >'.$prob.
 4684: 		(scalar(@{$parts}) == 1 ? '' 
 4685:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4686: 		.')').'</td>';
 4687: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4688: 
 4689: 	    my %newrecord=();
 4690: 	    my @displayPts=();
 4691:             my %aggregate = ();
 4692:             my $aggregateflag = 0;
 4693: 	    foreach my $partid (@{$parts}) {
 4694: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4695: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4696: 
 4697: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4698: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4699: 		my $partial = $newpts/$wgt;
 4700: 		my $score;
 4701: 		if ($partial > 0) {
 4702: 		    $score = 'correct_by_override';
 4703: 		} elsif ($newpts ne '') { #empty is taken as 0
 4704: 		    $score = 'incorrect_by_override';
 4705: 		}
 4706: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4707: 		if ($dropMenu eq 'excused') {
 4708: 		    $partial = '';
 4709: 		    $score = 'excused';
 4710: 		} elsif ($dropMenu eq 'reset status'
 4711: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4712: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4713: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4714: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4715: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4716: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4717: 		    $changeflag++;
 4718: 		    $newpts = '';
 4719:                     
 4720:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4721:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4722:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4723:                     if ($aggtries > 0) {
 4724:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4725:                         $aggregateflag = 1;
 4726:                     }
 4727: 		}
 4728: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4729: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4730: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4731: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4732: 		    '&nbsp;<br />';
 4733: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4734: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4735: 		    '&nbsp;<br />';
 4736: 		$question++;
 4737: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4738: 
 4739: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4740: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4741: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4742: 		    if (scalar(keys(%newrecord)) > 0);
 4743: 
 4744: 		$changeflag++;
 4745: 	    }
 4746: 	    if (scalar(keys(%newrecord)) > 0) {
 4747: 		my %record = 
 4748: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4749: 					     $udom,$uname);
 4750: 
 4751: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4752: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4753: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4754: 		    $newrecord{'resource.CODE'} = '';
 4755: 		}
 4756: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4757: 					$udom,$uname);
 4758: 		%record = &Apache::lonnet::restore($symbx,
 4759: 						   $env{'request.course.id'},
 4760: 						   $udom,$uname);
 4761: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4762: 					     $cdom,$cnum,$udom,$uname);
 4763: 	    }
 4764: 	    
 4765:             if ($aggregateflag) {
 4766:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4767:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4768:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4769:             }
 4770: 
 4771: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4772: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4773: 		&Apache::loncommon::end_data_table_row();
 4774: 
 4775: 	    $prob++;
 4776: 	}
 4777:         $curRes = $iterator->next();
 4778:     }
 4779: 
 4780:     $studentTable.=&Apache::loncommon::end_data_table();
 4781:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4782:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4783: 		  &mt('The scores were changed for [quant,_1,problem].',
 4784: 		  $changeflag));
 4785:     $request->print($grademsg.$studentTable);
 4786: 
 4787:     return '';
 4788: }
 4789: 
 4790: #-------- end of section for handling grading by page/sequence ---------
 4791: #
 4792: #-------------------------------------------------------------------
 4793: 
 4794: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4795: #
 4796: #------ start of section for handling grading by page/sequence ---------
 4797: 
 4798: =pod
 4799: 
 4800: =head1 Bubble sheet grading routines
 4801: 
 4802:   For this documentation:
 4803: 
 4804:    'scanline' refers to the full line of characters
 4805:    from the file that we are parsing that represents one entire sheet
 4806: 
 4807:    'bubble line' refers to the data
 4808:    representing the line of bubbles that are on the physical bubble sheet
 4809: 
 4810: 
 4811: The overall process is that a scanned in bubble sheet data is uploaded
 4812: into a course. When a user wants to grade, they select a
 4813: sequence/folder of resources, a file of bubble sheet info, and pick
 4814: one of the predefined configurations for what each scanline looks
 4815: like.
 4816: 
 4817: Next each scanline is checked for any errors of either 'missing
 4818: bubbles' (it's an error because it may have been mis-scanned
 4819: because too light bubbling), 'double bubble' (each bubble line should
 4820: have no more that one letter picked), invalid or duplicated CODE,
 4821: invalid student/employee ID
 4822: 
 4823: If the CODE option is used that determines the randomization of the
 4824: homework problems, either way the student/employee ID is looked up into a
 4825: username:domain.
 4826: 
 4827: During the validation phase the instructor can choose to skip scanlines. 
 4828: 
 4829: After the validation phase, there are now 3 bubble sheet files
 4830: 
 4831:   scantron_original_filename (unmodified original file)
 4832:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4833:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4834: 
 4835: Also there is a separate hash nohist_scantrondata that contains extra
 4836: correction information that isn't representable in the bubble sheet
 4837: file (see &scantron_getfile() for more information)
 4838: 
 4839: After all scanlines are either valid, marked as valid or skipped, then
 4840: foreach line foreach problem in the picked sequence, an ssi request is
 4841: made that simulates a user submitting their selected letter(s) against
 4842: the homework problem.
 4843: 
 4844: =over 4
 4845: 
 4846: 
 4847: 
 4848: =item defaultFormData
 4849: 
 4850:   Returns html hidden inputs used to hold context/default values.
 4851: 
 4852:  Arguments:
 4853:   $symb - $symb of the current resource 
 4854: 
 4855: =cut
 4856: 
 4857: sub defaultFormData {
 4858:     my ($symb)=@_;
 4859:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4860:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4861:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4862: }
 4863: 
 4864: 
 4865: =pod 
 4866: 
 4867: =item getSequenceDropDown
 4868: 
 4869:    Return html dropdown of possible sequences to grade
 4870:  
 4871:  Arguments:
 4872:    $symb - $symb of the current resource
 4873:    $map_error - ref to scalar which will container error if
 4874:                 $navmap object is unavailable in &getSymbMap().
 4875: 
 4876: =cut
 4877: 
 4878: sub getSequenceDropDown {
 4879:     my ($symb,$map_error)=@_;
 4880:     my $result='<select name="selectpage">'."\n";
 4881:     my ($titles,$symbx) = &getSymbMap($map_error);
 4882:     if (ref($map_error)) {
 4883:         return if ($$map_error);
 4884:     }
 4885:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4886:     my $ctr=0;
 4887:     foreach (@$titles) {
 4888: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4889: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4890: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4891: 	    '>'.$showtitle.'</option>'."\n";
 4892: 	$ctr++;
 4893:     }
 4894:     $result.= '</select>';
 4895:     return $result;
 4896: }
 4897: 
 4898: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4899:                                    # key is zero-based index - 0, 1, 2 ...
 4900: 
 4901: my %first_bubble_line;             # First bubble line no. for each bubble.
 4902: 
 4903: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4904:                                    # matchresponse or rankresponse, where 
 4905:                                    # an individual response can have multiple 
 4906:                                    # lines
 4907: 
 4908: my %responsetype_per_response;     # responsetype for each response
 4909: 
 4910: # Save and restore the bubble lines array to the form env.
 4911: 
 4912: 
 4913: sub save_bubble_lines {
 4914:     foreach my $line (keys(%bubble_lines_per_response)) {
 4915: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4916: 	$env{"form.scantron.first_bubble_line.$line"} =
 4917: 	    $first_bubble_line{$line};
 4918:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4919:             $subdivided_bubble_lines{$line};
 4920:         $env{"form.scantron.responsetype.$line"} =
 4921:             $responsetype_per_response{$line};
 4922:     }
 4923: }
 4924: 
 4925: 
 4926: sub restore_bubble_lines {
 4927:     my $line = 0;
 4928:     %bubble_lines_per_response = ();
 4929:     while ($env{"form.scantron.bubblelines.$line"}) {
 4930: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4931: 	$bubble_lines_per_response{$line} = $value;
 4932: 	$first_bubble_line{$line}  =
 4933: 	    $env{"form.scantron.first_bubble_line.$line"};
 4934:         $subdivided_bubble_lines{$line} =
 4935:             $env{"form.scantron.sub_bubblelines.$line"};
 4936:         $responsetype_per_response{$line} =
 4937:             $env{"form.scantron.responsetype.$line"};
 4938: 	$line++;
 4939:     }
 4940: }
 4941: 
 4942: #  Given the parsed scanline, get the response for 
 4943: #  'answer' number n:
 4944: 
 4945: sub get_response_bubbles {
 4946:     my ($parsed_line, $response)  = @_;
 4947: 
 4948:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4949:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4950:     
 4951:     my $selected = "";
 4952: 
 4953:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4954: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4955: 	$bubble_line++;
 4956:     }
 4957:     return $selected;
 4958: }
 4959: 
 4960: =pod 
 4961: 
 4962: =item scantron_filenames
 4963: 
 4964:    Returns a list of the scantron files in the current course 
 4965: 
 4966: =cut
 4967: 
 4968: sub scantron_filenames {
 4969:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4970:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4971:     my $getpropath = 1;
 4972:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4973:                                        $getpropath);
 4974:     my @possiblenames;
 4975:     foreach my $filename (sort(@files)) {
 4976: 	($filename)=split(/&/,$filename);
 4977: 	if ($filename!~/^scantron_orig_/) { next ; }
 4978: 	$filename=~s/^scantron_orig_//;
 4979: 	push(@possiblenames,$filename);
 4980:     }
 4981:     return @possiblenames;
 4982: }
 4983: 
 4984: =pod 
 4985: 
 4986: =item scantron_uploads
 4987: 
 4988:    Returns  html drop-down list of scantron files in current course.
 4989: 
 4990:  Arguments:
 4991:    $file2grade - filename to set as selected in the dropdown
 4992: 
 4993: =cut
 4994: 
 4995: sub scantron_uploads {
 4996:     my ($file2grade) = @_;
 4997:     my $result=	'<select name="scantron_selectfile">';
 4998:     $result.="<option></option>";
 4999:     foreach my $filename (sort(&scantron_filenames())) {
 5000: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5001:     }
 5002:     $result.="</select>";
 5003:     return $result;
 5004: }
 5005: 
 5006: =pod 
 5007: 
 5008: =item scantron_scantab
 5009: 
 5010:   Returns html drop down of the scantron formats in the scantronformat.tab
 5011:   file.
 5012: 
 5013: =cut
 5014: 
 5015: sub scantron_scantab {
 5016:     my $result='<select name="scantron_format">'."\n";
 5017:     $result.='<option></option>'."\n";
 5018:     my @lines = &get_scantronformat_file();
 5019:     if (@lines > 0) {
 5020:         foreach my $line (@lines) {
 5021:             next if (($line =~ /^\#/) || ($line eq ''));
 5022: 	    my ($name,$descrip)=split(/:/,$line);
 5023: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5024:         }
 5025:     }
 5026:     $result.='</select>'."\n";
 5027:     return $result;
 5028: }
 5029: 
 5030: =pod
 5031: 
 5032: =item get_scantronformat_file
 5033: 
 5034:   Returns an array containing lines from the scantron format file for
 5035:   the domain of the course.
 5036: 
 5037:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5038:   lines are from this file.
 5039: 
 5040:   Otherwise, if a default.tab has been published in RES space by the 
 5041:   domainconfig user, lines are from this file.
 5042: 
 5043:   Otherwise, fall back to getting lines from the legacy file on the
 5044:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5045: 
 5046: =cut
 5047: 
 5048: sub get_scantronformat_file {
 5049:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5050:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5051:     my $gottab = 0;
 5052:     my @lines;
 5053:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5054:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5055:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5056:             if ($formatfile ne '-1') {
 5057:                 @lines = split("\n",$formatfile,-1);
 5058:                 $gottab = 1;
 5059:             }
 5060:         }
 5061:     }
 5062:     if (!$gottab) {
 5063:         my $confname = $cdom.'-domainconfig';
 5064:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5065:         my $formatfile =  &Apache::lonnet::getfile($default);
 5066:         if ($formatfile ne '-1') {
 5067:             @lines = split("\n",$formatfile,-1);
 5068:             $gottab = 1;
 5069:         }
 5070:     }
 5071:     if (!$gottab) {
 5072:         my @domains = &Apache::lonnet::current_machine_domains();
 5073:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5074:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5075:             @lines = <$fh>;
 5076:             close($fh);
 5077:         } else {
 5078:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5079:             @lines = <$fh>;
 5080:             close($fh);
 5081:         }
 5082:     }
 5083:     return @lines;
 5084: }
 5085: 
 5086: =pod 
 5087: 
 5088: =item scantron_CODElist
 5089: 
 5090:   Returns html drop down of the saved CODE lists from current course,
 5091:   generated from earlier printings.
 5092: 
 5093: =cut
 5094: 
 5095: sub scantron_CODElist {
 5096:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5097:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5098:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5099:     my $namechoice='<option></option>';
 5100:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5101: 	if ($name =~ /^error: 2 /) { next; }
 5102: 	if ($name =~ /^type\0/) { next; }
 5103: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5104:     }
 5105:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5106:     return $namechoice;
 5107: }
 5108: 
 5109: =pod 
 5110: 
 5111: =item scantron_CODEunique
 5112: 
 5113:   Returns the html for "Each CODE to be used once" radio.
 5114: 
 5115: =cut
 5116: 
 5117: sub scantron_CODEunique {
 5118:     my $result='<span class="LC_nobreak">
 5119:                  <label><input type="radio" name="scantron_CODEunique"
 5120:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5121:                 </span>
 5122:                 <span class="LC_nobreak">
 5123:                  <label><input type="radio" name="scantron_CODEunique"
 5124:                         value="no" />'.&mt('No').' </label>
 5125:                 </span>';
 5126:     return $result;
 5127: }
 5128: 
 5129: =pod 
 5130: 
 5131: =item scantron_selectphase
 5132: 
 5133:   Generates the initial screen to start the bubble sheet process.
 5134:   Allows for - starting a grading run.
 5135:              - downloading existing scan data (original, corrected
 5136:                                                 or skipped info)
 5137: 
 5138:              - uploading new scan data
 5139: 
 5140:  Arguments:
 5141:   $r          - The Apache request object
 5142:   $file2grade - name of the file that contain the scanned data to score
 5143: 
 5144: =cut
 5145: 
 5146: sub scantron_selectphase {
 5147:     my ($r,$file2grade) = @_;
 5148:     my ($symb)=&get_symb($r);
 5149:     if (!$symb) {return '';}
 5150:     my $map_error;
 5151:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5152:     if ($map_error) {
 5153:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5154:         return;
 5155:     }
 5156:     my $default_form_data=&defaultFormData($symb);
 5157:     my $grading_menu_button=&show_grading_menu_form($symb);
 5158:     my $file_selector=&scantron_uploads($file2grade);
 5159:     my $format_selector=&scantron_scantab();
 5160:     my $CODE_selector=&scantron_CODElist();
 5161:     my $CODE_unique=&scantron_CODEunique();
 5162:     my $result;
 5163: 
 5164:     $ssi_error = 0;
 5165: 
 5166:     # Chunk of form to prompt for a file to grade and how:
 5167: 
 5168:     $result.= '
 5169:     <br />
 5170:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5171:     <input type="hidden" name="command" value="scantron_warning" />
 5172:     '.$default_form_data.'
 5173:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5174:        '.&Apache::loncommon::start_data_table_header_row().'
 5175:             <th colspan="2">
 5176:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5177:             </th>
 5178:        '.&Apache::loncommon::end_data_table_header_row().'
 5179:        '.&Apache::loncommon::start_data_table_row().'
 5180:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5181:        '.&Apache::loncommon::end_data_table_row().'
 5182:        '.&Apache::loncommon::start_data_table_row().'
 5183:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5184:        '.&Apache::loncommon::end_data_table_row().'
 5185:        '.&Apache::loncommon::start_data_table_row().'
 5186:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5187:        '.&Apache::loncommon::end_data_table_row().'
 5188:        '.&Apache::loncommon::start_data_table_row().'
 5189:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5190:        '.&Apache::loncommon::end_data_table_row().'
 5191:        '.&Apache::loncommon::start_data_table_row().'
 5192:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5193:        '.&Apache::loncommon::end_data_table_row().'
 5194:        '.&Apache::loncommon::start_data_table_row().'
 5195: 	    <td> '.&mt('Options:').' </td>
 5196:             <td>
 5197: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5198:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5199:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5200: 	    </td>
 5201:        '.&Apache::loncommon::end_data_table_row().'
 5202:        '.&Apache::loncommon::start_data_table_row().'
 5203:             <td colspan="2">
 5204:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5205:             </td>
 5206:        '.&Apache::loncommon::end_data_table_row().'
 5207:     '.&Apache::loncommon::end_data_table().'
 5208:     </form>
 5209: ';
 5210:    
 5211:     $r->print($result);
 5212: 
 5213:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5214:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5215: 
 5216: 	# Chunk of form to prompt for a scantron file upload.
 5217: 
 5218:         $r->print('
 5219:     <br />
 5220:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5221:        '.&Apache::loncommon::start_data_table_header_row().'
 5222:             <th>
 5223:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5224:             </th>
 5225:        '.&Apache::loncommon::end_data_table_header_row().'
 5226:        '.&Apache::loncommon::start_data_table_row().'
 5227:             <td>
 5228: ');
 5229:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5230:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5231:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5232:     $r->print('
 5233:               <script type="text/javascript" language="javascript">
 5234:     function checkUpload(formname) {
 5235: 	if (formname.upfile.value == "") {
 5236: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5237: 	    return false;
 5238: 	}
 5239: 	formname.submit();
 5240:     }
 5241:               </script>
 5242: 
 5243:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5244:                 '.$default_form_data.'
 5245:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5246:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5247:                 <input name="command" value="scantronupload_save" type="hidden" />
 5248:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5249:                 <br />
 5250:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5251:               </form>
 5252: ');
 5253: 
 5254:         $r->print('
 5255:             </td>
 5256:        '.&Apache::loncommon::end_data_table_row().'
 5257:        '.&Apache::loncommon::end_data_table().'
 5258: ');
 5259:     }
 5260: 
 5261:     # Chunk of the form that prompts to view a scoring office file,
 5262:     # corrected file, skipped records in a file.
 5263: 
 5264:     $r->print('
 5265:    <br />
 5266:    <form action="/adm/grades" name="scantron_download">
 5267:      '.$default_form_data.'
 5268:      <input type="hidden" name="command" value="scantron_download" />
 5269:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5270:        '.&Apache::loncommon::start_data_table_header_row().'
 5271:               <th>
 5272:                 &nbsp;'.&mt('Download a scoring office file').'
 5273:               </th>
 5274:        '.&Apache::loncommon::end_data_table_header_row().'
 5275:        '.&Apache::loncommon::start_data_table_row().'
 5276:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5277:                 <br />
 5278:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5279:        '.&Apache::loncommon::end_data_table_row().'
 5280:      '.&Apache::loncommon::end_data_table().'
 5281:    </form>
 5282:    <br />
 5283: ');
 5284: 
 5285:     &Apache::lonpickcode::code_list($r,2);
 5286: 
 5287:     $r->print('<br /><form method="post" name="checkscantron">'.
 5288:              $default_form_data."\n".
 5289:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5290:              &Apache::loncommon::start_data_table_header_row()."\n".
 5291:              '<th colspan="2">
 5292:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5293:              '</th>'."\n".
 5294:               &Apache::loncommon::end_data_table_header_row()."\n".
 5295:               &Apache::loncommon::start_data_table_row()."\n".
 5296:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5297:               '<td> '.$sequence_selector.' </td>'.
 5298:               &Apache::loncommon::end_data_table_row()."\n".
 5299:               &Apache::loncommon::start_data_table_row()."\n".
 5300:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5301:               '<td> '.$file_selector.' </td>'."\n".
 5302:               &Apache::loncommon::end_data_table_row()."\n".
 5303:               &Apache::loncommon::start_data_table_row()."\n".
 5304:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5305:               '<td> '.$format_selector.' </td>'."\n".
 5306:               &Apache::loncommon::end_data_table_row()."\n".
 5307:               &Apache::loncommon::start_data_table_row()."\n".
 5308:               '<td> '.&mt('Options').' </td>'."\n".
 5309:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5310:               &Apache::loncommon::end_data_table_row()."\n".
 5311:               &Apache::loncommon::start_data_table_row()."\n".
 5312:               '<td colspan="2">'."\n".
 5313:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5314:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5315:               '</td>'."\n".
 5316:               &Apache::loncommon::end_data_table_row()."\n".
 5317:               &Apache::loncommon::end_data_table()."\n".
 5318:               '</form><br />');
 5319:     $r->print($grading_menu_button);
 5320:     return;
 5321: }
 5322: 
 5323: =pod
 5324: 
 5325: =item get_scantron_config
 5326: 
 5327:    Parse and return the scantron configuration line selected as a
 5328:    hash of configuration file fields.
 5329: 
 5330:  Arguments:
 5331:     which - the name of the configuration to parse from the file.
 5332: 
 5333: 
 5334:  Returns:
 5335:             If the named configuration is not in the file, an empty
 5336:             hash is returned.
 5337:     a hash with the fields
 5338:       name         - internal name for the this configuration setup
 5339:       description  - text to display to operator that describes this config
 5340:       CODElocation - if 0 or the string 'none'
 5341:                           - no CODE exists for this config
 5342:                      if -1 || the string 'letter'
 5343:                           - a CODE exists for this config and is
 5344:                             a string of letters
 5345:                      Unsupported value (but planned for future support)
 5346:                           if a positive integer
 5347:                                - The CODE exists as the first n items from
 5348:                                  the question section of the form
 5349:                           if the string 'number'
 5350:                                - The CODE exists for this config and is
 5351:                                  a string of numbers
 5352:       CODEstart   - (only matter if a CODE exists) column in the line where
 5353:                      the CODE starts
 5354:       CODElength  - length of the CODE
 5355:       IDstart     - column where the student/employee ID starts
 5356:       IDlength    - length of the student/employee ID info
 5357:       Qstart      - column where the information from the bubbled
 5358:                     'questions' start
 5359:       Qlength     - number of columns comprising a single bubble line from
 5360:                     the sheet. (usually either 1 or 10)
 5361:       Qon         - either a single character representing the character used
 5362:                     to signal a bubble was chosen in the positional setup, or
 5363:                     the string 'letter' if the letter of the chosen bubble is
 5364:                     in the final, or 'number' if a number representing the
 5365:                     chosen bubble is in the file (1->A 0->J)
 5366:       Qoff        - the character used to represent that a bubble was
 5367:                     left blank
 5368:       PaperID     - if the scanning process generates a unique number for each
 5369:                     sheet scanned the column that this ID number starts in
 5370:       PaperIDlength - number of columns that comprise the unique ID number
 5371:                       for the sheet of paper
 5372:       FirstName   - column that the first name starts in
 5373:       FirstNameLength - number of columns that the first name spans
 5374:  
 5375:       LastName    - column that the last name starts in
 5376:       LastNameLength - number of columns that the last name spans
 5377: 
 5378: =cut
 5379: 
 5380: sub get_scantron_config {
 5381:     my ($which) = @_;
 5382:     my @lines = &get_scantronformat_file();
 5383:     my %config;
 5384:     #FIXME probably should move to XML it has already gotten a bit much now
 5385:     foreach my $line (@lines) {
 5386: 	my ($name,$descrip)=split(/:/,$line);
 5387: 	if ($name ne $which ) { next; }
 5388: 	chomp($line);
 5389: 	my @config=split(/:/,$line);
 5390: 	$config{'name'}=$config[0];
 5391: 	$config{'description'}=$config[1];
 5392: 	$config{'CODElocation'}=$config[2];
 5393: 	$config{'CODEstart'}=$config[3];
 5394: 	$config{'CODElength'}=$config[4];
 5395: 	$config{'IDstart'}=$config[5];
 5396: 	$config{'IDlength'}=$config[6];
 5397: 	$config{'Qstart'}=$config[7];
 5398:  	$config{'Qlength'}=$config[8];
 5399: 	$config{'Qoff'}=$config[9];
 5400: 	$config{'Qon'}=$config[10];
 5401: 	$config{'PaperID'}=$config[11];
 5402: 	$config{'PaperIDlength'}=$config[12];
 5403: 	$config{'FirstName'}=$config[13];
 5404: 	$config{'FirstNamelength'}=$config[14];
 5405: 	$config{'LastName'}=$config[15];
 5406: 	$config{'LastNamelength'}=$config[16];
 5407: 	last;
 5408:     }
 5409:     return %config;
 5410: }
 5411: 
 5412: =pod 
 5413: 
 5414: =item username_to_idmap
 5415: 
 5416:     creates a hash keyed by student/employee ID with values of the corresponding
 5417:     student username:domain.
 5418: 
 5419:   Arguments:
 5420: 
 5421:     $classlist - reference to the class list hash. This is a hash
 5422:                  keyed by student name:domain  whose elements are references
 5423:                  to arrays containing various chunks of information
 5424:                  about the student. (See loncoursedata for more info).
 5425: 
 5426:   Returns
 5427:     %idmap - the constructed hash
 5428: 
 5429: =cut
 5430: 
 5431: sub username_to_idmap {
 5432:     my ($classlist)= @_;
 5433:     my %idmap;
 5434:     foreach my $student (keys(%$classlist)) {
 5435: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5436: 	    $student;
 5437:     }
 5438:     return %idmap;
 5439: }
 5440: 
 5441: =pod
 5442: 
 5443: =item scantron_fixup_scanline
 5444: 
 5445:    Process a requested correction to a scanline.
 5446: 
 5447:   Arguments:
 5448:     $scantron_config   - hash from &get_scantron_config()
 5449:     $scan_data         - hash of correction information 
 5450:                           (see &scantron_getfile())
 5451:     $line              - existing scanline
 5452:     $whichline         - line number of the passed in scanline
 5453:     $field             - type of change to process 
 5454:                          (either 
 5455:                           'ID'     -> correct the student/employee ID
 5456:                           'CODE'   -> correct the CODE
 5457:                           'answer' -> fixup the submitted answers)
 5458:     
 5459:    $args               - hash of additional info,
 5460:                           - 'ID' 
 5461:                                'newid' -> studentID to use in replacement
 5462:                                           of existing one
 5463:                           - 'CODE' 
 5464:                                'CODE_ignore_dup' - set to true if duplicates
 5465:                                                    should be ignored.
 5466: 	                       'CODE' - is new code or 'use_unfound'
 5467:                                         if the existing unfound code should
 5468:                                         be used as is
 5469:                           - 'answer'
 5470:                                'response' - new answer or 'none' if blank
 5471:                                'question' - the bubble line to change
 5472:                                'questionnum' - the question identifier,
 5473:                                                may include subquestion. 
 5474: 
 5475:   Returns:
 5476:     $line - the modified scanline
 5477: 
 5478:   Side effects: 
 5479:     $scan_data - may be updated
 5480: 
 5481: =cut
 5482: 
 5483: 
 5484: sub scantron_fixup_scanline {
 5485:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5486:     if ($field eq 'ID') {
 5487: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5488: 	    return ($line,1,'New value too large');
 5489: 	}
 5490: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5491: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5492: 				     $args->{'newid'});
 5493: 	}
 5494: 	substr($line,$$scantron_config{'IDstart'}-1,
 5495: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5496: 	if ($args->{'newid'}=~/^\s*$/) {
 5497: 	    &scan_data($scan_data,"$whichline.user",
 5498: 		       $args->{'username'}.':'.$args->{'domain'});
 5499: 	}
 5500:     } elsif ($field eq 'CODE') {
 5501: 	if ($args->{'CODE_ignore_dup'}) {
 5502: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5503: 	}
 5504: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5505: 	if ($args->{'CODE'} ne 'use_unfound') {
 5506: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5507: 		return ($line,1,'New CODE value too large');
 5508: 	    }
 5509: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5510: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5511: 	    }
 5512: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5513: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5514: 	}
 5515:     } elsif ($field eq 'answer') {
 5516: 	my $length=$scantron_config->{'Qlength'};
 5517: 	my $off=$scantron_config->{'Qoff'};
 5518: 	my $on=$scantron_config->{'Qon'};
 5519: 	my $answer=${off}x$length;
 5520: 	if ($args->{'response'} eq 'none') {
 5521: 	    &scan_data($scan_data,
 5522: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5523: 	} else {
 5524: 	    if ($on eq 'letter') {
 5525: 		my @alphabet=('A'..'Z');
 5526: 		$answer=$alphabet[$args->{'response'}];
 5527: 	    } elsif ($on eq 'number') {
 5528: 		$answer=$args->{'response'}+1;
 5529: 		if ($answer == 10) { $answer = '0'; }
 5530: 	    } else {
 5531: 		substr($answer,$args->{'response'},1)=$on;
 5532: 	    }
 5533: 	    &scan_data($scan_data,
 5534: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5535: 	}
 5536: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5537: 	substr($line,$where-1,$length)=$answer;
 5538:     }
 5539:     return $line;
 5540: }
 5541: 
 5542: =pod
 5543: 
 5544: =item scan_data
 5545: 
 5546:     Edit or look up  an item in the scan_data hash.
 5547: 
 5548:   Arguments:
 5549:     $scan_data  - The hash (see scantron_getfile)
 5550:     $key        - shorthand of the key to edit (actual key is
 5551:                   scantronfilename_key).
 5552:     $data        - New value of the hash entry.
 5553:     $delete      - If true, the entry is removed from the hash.
 5554: 
 5555:   Returns:
 5556:     The new value of the hash table field (undefined if deleted).
 5557: 
 5558: =cut
 5559: 
 5560: 
 5561: sub scan_data {
 5562:     my ($scan_data,$key,$value,$delete)=@_;
 5563:     my $filename=$env{'form.scantron_selectfile'};
 5564:     if (defined($value)) {
 5565: 	$scan_data->{$filename.'_'.$key} = $value;
 5566:     }
 5567:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5568:     return $scan_data->{$filename.'_'.$key};
 5569: }
 5570: 
 5571: # ----- These first few routines are general use routines.----
 5572: 
 5573: # Return the number of occurences of a pattern in a string.
 5574: 
 5575: sub occurence_count {
 5576:     my ($string, $pattern) = @_;
 5577: 
 5578:     my @matches = ($string =~ /$pattern/g);
 5579: 
 5580:     return scalar(@matches);
 5581: }
 5582: 
 5583: 
 5584: # Take a string known to have digits and convert all the
 5585: # digits into letters in the range J,A..I.
 5586: 
 5587: sub digits_to_letters {
 5588:     my ($input) = @_;
 5589: 
 5590:     my @alphabet = ('J', 'A'..'I');
 5591: 
 5592:     my @input    = split(//, $input);
 5593:     my $output ='';
 5594:     for (my $i = 0; $i < scalar(@input); $i++) {
 5595: 	if ($input[$i] =~ /\d/) {
 5596: 	    $output .= $alphabet[$input[$i]];
 5597: 	} else {
 5598: 	    $output .= $input[$i];
 5599: 	}
 5600:     }
 5601:     return $output;
 5602: }
 5603: 
 5604: =pod 
 5605: 
 5606: =item scantron_parse_scanline
 5607: 
 5608:   Decodes a scanline from the selected scantron file
 5609: 
 5610:  Arguments:
 5611:     line             - The text of the scantron file line to process
 5612:     whichline        - Line number
 5613:     scantron_config  - Hash describing the format of the scantron lines.
 5614:     scan_data        - Hash of extra information about the scanline
 5615:                        (see scantron_getfile for more information)
 5616:     just_header      - True if should not process question answers but only
 5617:                        the stuff to the left of the answers.
 5618:  Returns:
 5619:    Hash containing the result of parsing the scanline
 5620: 
 5621:    Keys are all proceeded by the string 'scantron.'
 5622: 
 5623:        CODE    - the CODE in use for this scanline
 5624:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5625:                  by the operator
 5626:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5627:                             CODEs were selected, but the usage has been
 5628:                             forced by the operator
 5629:        ID  - student/employee ID
 5630:        PaperID - if used, the ID number printed on the sheet when the 
 5631:                  paper was scanned
 5632:        FirstName - first name from the sheet
 5633:        LastName  - last name from the sheet
 5634: 
 5635:      if just_header was not true these key may also exist
 5636: 
 5637:        missingerror - a list of bubble ranges that are considered to be answers
 5638:                       to a single question that don't have any bubbles filled in.
 5639:                       Of the form questionnumber:firstbubblenumber:count.
 5640:        doubleerror  - a list of bubble ranges that are considered to be answers
 5641:                       to a single question that have more than one bubble filled in.
 5642:                       Of the form questionnumber::firstbubblenumber:count
 5643:    
 5644:                 In the above, count is the number of bubble responses in the
 5645:                 input line needed to represent the possible answers to the question.
 5646:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5647:                 per line would have count = 2.
 5648: 
 5649:        maxquest     - the number of the last bubble line that was parsed
 5650: 
 5651:        (<number> starts at 1)
 5652:        <number>.answer - zero or more letters representing the selected
 5653:                          letters from the scanline for the bubble line 
 5654:                          <number>.
 5655:                          if blank there was either no bubble or there where
 5656:                          multiple bubbles, (consult the keys missingerror and
 5657:                          doubleerror if this is an error condition)
 5658: 
 5659: =cut
 5660: 
 5661: sub scantron_parse_scanline {
 5662:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5663: 
 5664:     my %record;
 5665:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5666:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5667:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5668:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5669: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5670: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5671: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5672: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5673: 	    $record{'scantron.CODE'}=substr($data,
 5674: 					    $$scantron_config{'CODEstart'}-1,
 5675: 					    $$scantron_config{'CODElength'});
 5676: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5677: 		$record{'scantron.useCODE'}=1;
 5678: 	    }
 5679: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5680: 		$record{'scantron.CODE_ignore_dup'}=1;
 5681: 	    }
 5682: 	} else {
 5683: 	    #FIXME interpret first N questions
 5684: 	}
 5685:     }
 5686:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5687: 				  $$scantron_config{'IDlength'});
 5688:     $record{'scantron.PaperID'}=
 5689: 	substr($data,$$scantron_config{'PaperID'}-1,
 5690: 	       $$scantron_config{'PaperIDlength'});
 5691:     $record{'scantron.FirstName'}=
 5692: 	substr($data,$$scantron_config{'FirstName'}-1,
 5693: 	       $$scantron_config{'FirstNamelength'});
 5694:     $record{'scantron.LastName'}=
 5695: 	substr($data,$$scantron_config{'LastName'}-1,
 5696: 	       $$scantron_config{'LastNamelength'});
 5697:     if ($just_header) { return \%record; }
 5698: 
 5699:     my @alphabet=('A'..'Z');
 5700:     my $questnum=0;
 5701:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5702: 
 5703:     chomp($questions);		# Get rid of any trailing \n.
 5704:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5705:     while (length($questions)) {
 5706: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5707:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5708:                              || 1;
 5709:         $questnum++;
 5710:         my $quest_id = $questnum;
 5711:         my $currentquest = substr($questions,0,$answer_length);
 5712:         $questions       = substr($questions,$answer_length);
 5713:         if (length($currentquest) < $answer_length) { next; }
 5714: 
 5715:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5716:             my $subquestnum = 1;
 5717:             my $subquestions = $currentquest;
 5718:             my @subanswers_needed = 
 5719:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5720:             foreach my $subans (@subanswers_needed) {
 5721:                 my $subans_length =
 5722:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5723:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5724:                 $subquestions   = substr($subquestions,$subans_length);
 5725:                 $quest_id = "$questnum.$subquestnum";
 5726:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5727:                     ($$scantron_config{'Qon'} eq 'number')) {
 5728:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5729:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5730:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5731:                 } else {
 5732:                     $ansnum = &scantron_validator_positional($ansnum,
 5733:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5734:                 }
 5735:                 $subquestnum ++;
 5736:             }
 5737:         } else {
 5738:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5739:                 ($$scantron_config{'Qon'} eq 'number')) {
 5740:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5741:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5742:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5743:             } else {
 5744:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5745:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5746:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5747:             }
 5748:         }
 5749:     }
 5750:     $record{'scantron.maxquest'}=$questnum;
 5751:     return \%record;
 5752: }
 5753: 
 5754: sub scantron_validator_lettnum {
 5755:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5756:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5757: 
 5758:     # Qon 'letter' implies for each slot in currquest we have:
 5759:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5760:     #    about anything else (esp. a value of Qoff) for missing
 5761:     #    bubbles.
 5762:     #
 5763:     # Qon 'number' implies each slot gives a digit that indexes the
 5764:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5765:     #    and * or ? for double bubbles on a single line.
 5766:     #
 5767: 
 5768:     my $matchon;
 5769:     if ($$scantron_config{'Qon'} eq 'letter') {
 5770:         $matchon = '[A-Z]';
 5771:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5772:         $matchon = '\d';
 5773:     }
 5774:     my $occurrences = 0;
 5775:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5776:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5777:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5778:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5779:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5780:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5781:         my @singlelines = split('',$currquest);
 5782:         foreach my $entry (@singlelines) {
 5783:             $occurrences = &occurence_count($entry,$matchon);
 5784:             if ($occurrences > 1) {
 5785:                 last;
 5786:             }
 5787:         } 
 5788:     } else {
 5789:         $occurrences = &occurence_count($currquest,$matchon); 
 5790:     }
 5791:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5792:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5793:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5794:             my $bubble = substr($currquest,$ans,1);
 5795:             if ($bubble =~ /$matchon/ ) {
 5796:                 if ($$scantron_config{'Qon'} eq 'number') {
 5797:                     if ($bubble == 0) {
 5798:                         $bubble = 10; 
 5799:                     }
 5800:                     $record->{"scantron.$ansnum.answer"} = 
 5801:                         $alphabet->[$bubble-1];
 5802:                 } else {
 5803:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5804:                 }
 5805:             } else {
 5806:                 $record->{"scantron.$ansnum.answer"}='';
 5807:             }
 5808:             $ansnum++;
 5809:         }
 5810:     } elsif (!defined($currquest)
 5811:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5812:             || (&occurence_count($currquest,$matchon) == 0)) {
 5813:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5814:             $record->{"scantron.$ansnum.answer"}='';
 5815:             $ansnum++;
 5816:         }
 5817:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5818:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5819:         }
 5820:     } else {
 5821:         if ($$scantron_config{'Qon'} eq 'number') {
 5822:             $currquest = &digits_to_letters($currquest);            
 5823:         }
 5824:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5825:             my $bubble = substr($currquest,$ans,1);
 5826:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5827:             $ansnum++;
 5828:         }
 5829:     }
 5830:     return $ansnum;
 5831: }
 5832: 
 5833: sub scantron_validator_positional {
 5834:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5835:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5836: 
 5837:     # Otherwise there's a positional notation;
 5838:     # each bubble line requires Qlength items, and there are filled in
 5839:     # bubbles for each case where there 'Qon' characters.
 5840:     #
 5841: 
 5842:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5843: 
 5844:     # If the split only gives us one element.. the full length of the
 5845:     # answer string, no bubbles are filled in:
 5846: 
 5847:     if ($answers_needed eq '') {
 5848:         return;
 5849:     }
 5850: 
 5851:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5852:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5853:             $record->{"scantron.$ansnum.answer"}='';
 5854:             $ansnum++;
 5855:         }
 5856:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5857:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5858:         }
 5859:     } elsif (scalar(@array) == 2) {
 5860:         my $location = length($array[0]);
 5861:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5862:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5863:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5864:             if ($ans eq $line_num) {
 5865:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5866:             } else {
 5867:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5868:             }
 5869:             $ansnum++;
 5870:          }
 5871:     } else {
 5872:         #  If there's more than one instance of a bubble character
 5873:         #  That's a double bubble; with positional notation we can
 5874:         #  record all the bubbles filled in as well as the
 5875:         #  fact this response consists of multiple bubbles.
 5876:         #
 5877:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5878:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5879:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5880:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5881:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5882:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5883:             my $doubleerror = 0;
 5884:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5885:                    (!$doubleerror)) {
 5886:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5887:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5888:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5889:                if (length(@currarray) > 2) {
 5890:                    $doubleerror = 1;
 5891:                } 
 5892:             }
 5893:             if ($doubleerror) {
 5894:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5895:             }
 5896:         } else {
 5897:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5898:         }
 5899:         my $item = $ansnum;
 5900:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5901:             $record->{"scantron.$item.answer"} = '';
 5902:             $item ++;
 5903:         }
 5904: 
 5905:         my @ans=@array;
 5906:         my $i=0;
 5907:         my $increment = 0;
 5908:         while ($#ans) {
 5909:             $i+=length($ans[0]) + $increment;
 5910:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5911:             my $bubble = $i%$$scantron_config{'Qlength'};
 5912:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5913:             shift(@ans);
 5914:             $increment = 1;
 5915:         }
 5916:         $ansnum += $answers_needed;
 5917:     }
 5918:     return $ansnum;
 5919: }
 5920: 
 5921: =pod
 5922: 
 5923: =item scantron_add_delay
 5924: 
 5925:    Adds an error message that occurred during the grading phase to a
 5926:    queue of messages to be shown after grading pass is complete
 5927: 
 5928:  Arguments:
 5929:    $delayqueue  - arrary ref of hash ref of error messages
 5930:    $scanline    - the scanline that caused the error
 5931:    $errormesage - the error message
 5932:    $errorcode   - a numeric code for the error
 5933: 
 5934:  Side Effects:
 5935:    updates the $delayqueue to have a new hash ref of the error
 5936: 
 5937: =cut
 5938: 
 5939: sub scantron_add_delay {
 5940:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5941:     push(@$delayqueue,
 5942: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5943: 	  'ecode' => $errorcode }
 5944: 	 );
 5945: }
 5946: 
 5947: =pod
 5948: 
 5949: =item scantron_find_student
 5950: 
 5951:    Finds the username for the current scanline
 5952: 
 5953:   Arguments:
 5954:    $scantron_record - hash result from scantron_parse_scanline
 5955:    $scan_data       - hash of correction information 
 5956:                       (see &scantron_getfile() form more information)
 5957:    $idmap           - hash from &username_to_idmap()
 5958:    $line            - number of current scanline
 5959:  
 5960:   Returns:
 5961:    Either 'username:domain' or undef if unknown
 5962: 
 5963: =cut
 5964: 
 5965: sub scantron_find_student {
 5966:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5967:     my $scanID=$$scantron_record{'scantron.ID'};
 5968:     if ($scanID =~ /^\s*$/) {
 5969:  	return &scan_data($scan_data,"$line.user");
 5970:     }
 5971:     foreach my $id (keys(%$idmap)) {
 5972:  	if (lc($id) eq lc($scanID)) {
 5973:  	    return $$idmap{$id};
 5974:  	}
 5975:     }
 5976:     return undef;
 5977: }
 5978: 
 5979: =pod
 5980: 
 5981: =item scantron_filter
 5982: 
 5983:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5984:    hidden resources was selected
 5985: 
 5986: =cut
 5987: 
 5988: sub scantron_filter {
 5989:     my ($curres)=@_;
 5990: 
 5991:     if (ref($curres) && $curres->is_problem()) {
 5992: 	# if the user has asked to not have either hidden
 5993: 	# or 'randomout' controlled resources to be graded
 5994: 	# don't include them
 5995: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5996: 	    && $curres->randomout) {
 5997: 	    return 0;
 5998: 	}
 5999: 	return 1;
 6000:     }
 6001:     return 0;
 6002: }
 6003: 
 6004: =pod
 6005: 
 6006: =item scantron_process_corrections
 6007: 
 6008:    Gets correction information out of submitted form data and corrects
 6009:    the scanline
 6010: 
 6011: =cut
 6012: 
 6013: sub scantron_process_corrections {
 6014:     my ($r) = @_;
 6015:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6016:     my ($scanlines,$scan_data)=&scantron_getfile();
 6017:     my $classlist=&Apache::loncoursedata::get_classlist();
 6018:     my $which=$env{'form.scantron_line'};
 6019:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6020:     my ($skip,$err,$errmsg);
 6021:     if ($env{'form.scantron_skip_record'}) {
 6022: 	$skip=1;
 6023:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6024: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6025: 	    $env{'form.scantron_domain'};
 6026: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6027: 	($line,$err,$errmsg)=
 6028: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6029: 				     'ID',{'newid'=>$newid,
 6030: 				    'username'=>$env{'form.scantron_username'},
 6031: 				    'domain'=>$env{'form.scantron_domain'}});
 6032:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6033: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6034: 	my $newCODE;
 6035: 	my %args;
 6036: 	if      ($resolution eq 'use_unfound') {
 6037: 	    $newCODE='use_unfound';
 6038: 	} elsif ($resolution eq 'use_found') {
 6039: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6040: 	} elsif ($resolution eq 'use_typed') {
 6041: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6042: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6043: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6044: 	}
 6045: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6046: 	    $args{'CODE_ignore_dup'}=1;
 6047: 	}
 6048: 	$args{'CODE'}=$newCODE;
 6049: 	($line,$err,$errmsg)=
 6050: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6051: 				     'CODE',\%args);
 6052:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6053: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6054: 	    ($line,$err,$errmsg)=
 6055: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6056: 					 $which,'answer',
 6057: 					 { 'question'=>$question,
 6058: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6059:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6060: 	    if ($err) { last; }
 6061: 	}
 6062:     }
 6063:     if ($err) {
 6064: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6065:     } else {
 6066: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6067: 	&scantron_putfile($scanlines,$scan_data);
 6068:     }
 6069: }
 6070: 
 6071: =pod
 6072: 
 6073: =item reset_skipping_status
 6074: 
 6075:    Forgets the current set of remember skipped scanlines (and thus
 6076:    reverts back to considering all lines in the
 6077:    scantron_skipped_<filename> file)
 6078: 
 6079: =cut
 6080: 
 6081: sub reset_skipping_status {
 6082:     my ($scanlines,$scan_data)=&scantron_getfile();
 6083:     &scan_data($scan_data,'remember_skipping',undef,1);
 6084:     &scantron_putfile(undef,$scan_data);
 6085: }
 6086: 
 6087: =pod
 6088: 
 6089: =item start_skipping
 6090: 
 6091:    Marks a scanline to be skipped. 
 6092: 
 6093: =cut
 6094: 
 6095: sub start_skipping {
 6096:     my ($scan_data,$i)=@_;
 6097:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6098:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6099: 	$remembered{$i}=2;
 6100:     } else {
 6101: 	$remembered{$i}=1;
 6102:     }
 6103:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6104: }
 6105: 
 6106: =pod
 6107: 
 6108: =item should_be_skipped
 6109: 
 6110:    Checks whether a scanline should be skipped.
 6111: 
 6112: =cut
 6113: 
 6114: sub should_be_skipped {
 6115:     my ($scanlines,$scan_data,$i)=@_;
 6116:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6117: 	# not redoing old skips
 6118: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6119: 	return 0;
 6120:     }
 6121:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6122: 
 6123:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6124: 	return 0;
 6125:     }
 6126:     return 1;
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item remember_current_skipped
 6132: 
 6133:    Discovers what scanlines are in the scantron_skipped_<filename>
 6134:    file and remembers them into scan_data for later use.
 6135: 
 6136: =cut
 6137: 
 6138: sub remember_current_skipped {
 6139:     my ($scanlines,$scan_data)=&scantron_getfile();
 6140:     my %to_remember;
 6141:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6142: 	if ($scanlines->{'skipped'}[$i]) {
 6143: 	    $to_remember{$i}=1;
 6144: 	}
 6145:     }
 6146: 
 6147:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6148:     &scantron_putfile(undef,$scan_data);
 6149: }
 6150: 
 6151: =pod
 6152: 
 6153: =item check_for_error
 6154: 
 6155:     Checks if there was an error when attempting to remove a specific
 6156:     scantron_.. bubble sheet data file. Prints out an error if
 6157:     something went wrong.
 6158: 
 6159: =cut
 6160: 
 6161: sub check_for_error {
 6162:     my ($r,$result)=@_;
 6163:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6164: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6165:     }
 6166: }
 6167: 
 6168: =pod
 6169: 
 6170: =item scantron_warning_screen
 6171: 
 6172:    Interstitial screen to make sure the operator has selected the
 6173:    correct options before we start the validation phase.
 6174: 
 6175: =cut
 6176: 
 6177: sub scantron_warning_screen {
 6178:     my ($button_text)=@_;
 6179:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6180:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6181:     my $CODElist;
 6182:     if ($scantron_config{'CODElocation'} &&
 6183: 	$scantron_config{'CODEstart'} &&
 6184: 	$scantron_config{'CODElength'}) {
 6185: 	$CODElist=$env{'form.scantron_CODElist'};
 6186: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6187: 	$CODElist=
 6188: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6189: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6190:     }
 6191:     return ('
 6192: <p>
 6193: <span class="LC_warning">
 6194: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6195: </p>
 6196: <table>
 6197: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6198: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6199: '.$CODElist.'
 6200: </table>
 6201: <br />
 6202: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6203: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6204: 
 6205: <br />
 6206: ');
 6207: }
 6208: 
 6209: =pod
 6210: 
 6211: =item scantron_do_warning
 6212: 
 6213:    Check if the operator has picked something for all required
 6214:    fields. Error out if something is missing.
 6215: 
 6216: =cut
 6217: 
 6218: sub scantron_do_warning {
 6219:     my ($r)=@_;
 6220:     my ($symb)=&get_symb($r);
 6221:     if (!$symb) {return '';}
 6222:     my $default_form_data=&defaultFormData($symb);
 6223:     $r->print(&scantron_form_start().$default_form_data);
 6224:     if ( $env{'form.selectpage'} eq '' ||
 6225: 	 $env{'form.scantron_selectfile'} eq '' ||
 6226: 	 $env{'form.scantron_format'} eq '' ) {
 6227: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6228: 	if ( $env{'form.selectpage'} eq '') {
 6229: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6230: 	} 
 6231: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6232: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6233: 	} 
 6234: 	if ( $env{'form.scantron_format'} eq '') {
 6235: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6236: 	} 
 6237:     } else {
 6238: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6239: 	$r->print('
 6240: '.$warning.'
 6241: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6242: <input type="hidden" name="command" value="scantron_validate" />
 6243: ');
 6244:     }
 6245:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6246:     return '';
 6247: }
 6248: 
 6249: =pod
 6250: 
 6251: =item scantron_form_start
 6252: 
 6253:     html hidden input for remembering all selected grading options
 6254: 
 6255: =cut
 6256: 
 6257: sub scantron_form_start {
 6258:     my ($max_bubble)=@_;
 6259:     my $result= <<SCANTRONFORM;
 6260: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6261:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6262:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6263:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6264:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6265:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6266:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6267:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6268:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6269:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6270: SCANTRONFORM
 6271: 
 6272:   my $line = 0;
 6273:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6274:        my $chunk =
 6275: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6276:        $chunk .=
 6277: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6278:        $chunk .= 
 6279:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6280:        $chunk .=
 6281:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6282:        $result .= $chunk;
 6283:        $line++;
 6284:    }
 6285:     return $result;
 6286: }
 6287: 
 6288: =pod
 6289: 
 6290: =item scantron_validate_file
 6291: 
 6292:     Dispatch routine for doing validation of a bubble sheet data file.
 6293: 
 6294:     Also processes any necessary information resets that need to
 6295:     occur before validation begins (ignore previous corrections,
 6296:     restarting the skipped records processing)
 6297: 
 6298: =cut
 6299: 
 6300: sub scantron_validate_file {
 6301:     my ($r) = @_;
 6302:     my ($symb)=&get_symb($r);
 6303:     if (!$symb) {return '';}
 6304:     my $default_form_data=&defaultFormData($symb);
 6305:     
 6306:     # do the detection of only doing skipped records first befroe we delete
 6307:     # them when doing the corrections reset
 6308:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6309: 	&reset_skipping_status();
 6310:     }
 6311:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6312: 	&remember_current_skipped();
 6313: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6314:     }
 6315: 
 6316:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6317: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6318: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6319: 	&check_for_error($r,&scantron_remove_scan_data());
 6320: 	$env{'form.scantron_options_ignore'}='done';
 6321:     }
 6322: 
 6323:     if ($env{'form.scantron_corrections'}) {
 6324: 	&scantron_process_corrections($r);
 6325:     }
 6326:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6327:     #get the student pick code ready
 6328:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6329:     my $nav_error;
 6330:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6331:     if ($nav_error) {
 6332:         $r->print(&navmap_errormsg());
 6333:         return '';
 6334:     }
 6335:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6336:     $r->print($result);
 6337:     
 6338:     my @validate_phases=( 'sequence',
 6339: 			  'ID',
 6340: 			  'CODE',
 6341: 			  'doublebubble',
 6342: 			  'missingbubbles');
 6343:     if (!$env{'form.validatepass'}) {
 6344: 	$env{'form.validatepass'} = 0;
 6345:     }
 6346:     my $currentphase=$env{'form.validatepass'};
 6347: 
 6348: 
 6349:     my $stop=0;
 6350:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6351: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6352: 	$r->rflush();
 6353: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6354: 	{
 6355: 	    no strict 'refs';
 6356: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6357: 	}
 6358:     }
 6359:     if (!$stop) {
 6360: 	my $warning=&scantron_warning_screen('Start Grading');
 6361: 	$r->print(&mt('Validation process complete.').'<br />'.
 6362:                   $warning.
 6363:                   &mt('Perform verification for each student after storage of submissions?').
 6364:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6365:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6366:                   ('&nbsp;'x3).'<label>'.
 6367:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6368:                   '</label></span><br />'.
 6369:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6370:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6371:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6372:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6373:     } else {
 6374: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6375: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6376:     }
 6377:     if ($stop) {
 6378: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6379: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6380: 	    $r->print(' '.&mt('this error').' <br />');
 6381: 
 6382: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6383: 	} else {
 6384:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6385: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6386:             } else {
 6387:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6388:             }
 6389: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6390: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6391: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6392: 	}
 6393:     }
 6394:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6395:     return '';
 6396: }
 6397: 
 6398: 
 6399: =pod
 6400: 
 6401: =item scantron_remove_file
 6402: 
 6403:    Removes the requested bubble sheet data file, makes sure that
 6404:    scantron_original_<filename> is never removed
 6405: 
 6406: 
 6407: =cut
 6408: 
 6409: sub scantron_remove_file {
 6410:     my ($which)=@_;
 6411:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6412:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6413:     my $file='scantron_';
 6414:     if ($which eq 'corrected' || $which eq 'skipped') {
 6415: 	$file.=$which.'_';
 6416:     } else {
 6417: 	return 'refused';
 6418:     }
 6419:     $file.=$env{'form.scantron_selectfile'};
 6420:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6421: }
 6422: 
 6423: 
 6424: =pod
 6425: 
 6426: =item scantron_remove_scan_data
 6427: 
 6428:    Removes all scan_data correction for the requested bubble sheet
 6429:    data file.  (In the case that both the are doing skipped records we need
 6430:    to remember the old skipped lines for the time being so that element
 6431:    persists for a while.)
 6432: 
 6433: =cut
 6434: 
 6435: sub scantron_remove_scan_data {
 6436:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6438:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6439:     my @todelete;
 6440:     my $filename=$env{'form.scantron_selectfile'};
 6441:     foreach my $key (@keys) {
 6442: 	if ($key=~/^\Q$filename\E_/) {
 6443: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6444: 		$key=~/remember_skipping/) {
 6445: 		next;
 6446: 	    }
 6447: 	    push(@todelete,$key);
 6448: 	}
 6449:     }
 6450:     my $result;
 6451:     if (@todelete) {
 6452: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6453: 				       \@todelete,$cdom,$cname);
 6454:     } else {
 6455: 	$result = 'ok';
 6456:     }
 6457:     return $result;
 6458: }
 6459: 
 6460: 
 6461: =pod
 6462: 
 6463: =item scantron_getfile
 6464: 
 6465:     Fetches the requested bubble sheet data file (all 3 versions), and
 6466:     the scan_data hash
 6467:   
 6468:   Arguments:
 6469:     None
 6470: 
 6471:   Returns:
 6472:     2 hash references
 6473: 
 6474:      - first one has 
 6475:          orig      -
 6476:          corrected -
 6477:          skipped   -  each of which points to an array ref of the specified
 6478:                       file broken up into individual lines
 6479:          count     - number of scanlines
 6480:  
 6481:      - second is the scan_data hash possible keys are
 6482:        ($number refers to scanline numbered $number and thus the key affects
 6483:         only that scanline
 6484:         $bubline refers to the specific bubble line element and the aspects
 6485:         refers to that specific bubble line element)
 6486: 
 6487:        $number.user - username:domain to use
 6488:        $number.CODE_ignore_dup 
 6489:                     - ignore the duplicate CODE error 
 6490:        $number.useCODE
 6491:                     - use the CODE in the scanline as is
 6492:        $number.no_bubble.$bubline
 6493:                     - it is valid that there is no bubbled in bubble
 6494:                       at $number $bubline
 6495:        remember_skipping
 6496:                     - a frozen hash containing keys of $number and values
 6497:                       of either 
 6498:                         1 - we are on a 'do skipped records pass' and plan
 6499:                             on processing this line
 6500:                         2 - we are on a 'do skipped records pass' and this
 6501:                             scanline has been marked to skip yet again
 6502: 
 6503: =cut
 6504: 
 6505: sub scantron_getfile {
 6506:     #FIXME really would prefer a scantron directory
 6507:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6508:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6509:     my $lines;
 6510:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6511: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6512:     my %scanlines;
 6513:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6514:     my $temp=$scanlines{'orig'};
 6515:     $scanlines{'count'}=$#$temp;
 6516: 
 6517:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6518: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6519:     if ($lines eq '-1') {
 6520: 	$scanlines{'corrected'}=[];
 6521:     } else {
 6522: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6523:     }
 6524:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6525: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6526:     if ($lines eq '-1') {
 6527: 	$scanlines{'skipped'}=[];
 6528:     } else {
 6529: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6530:     }
 6531:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6532:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6533:     my %scan_data = @tmp;
 6534:     return (\%scanlines,\%scan_data);
 6535: }
 6536: 
 6537: =pod
 6538: 
 6539: =item lonnet_putfile
 6540: 
 6541:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6542: 
 6543:  Arguments:
 6544:    $contents - data to store
 6545:    $filename - filename to store $contents into
 6546: 
 6547:  Returns:
 6548:    result value from &Apache::lonnet::finishuserfileupload
 6549: 
 6550: =cut
 6551: 
 6552: sub lonnet_putfile {
 6553:     my ($contents,$filename)=@_;
 6554:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6555:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6556:     $env{'form.sillywaytopassafilearound'}=$contents;
 6557:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6558: 
 6559: }
 6560: 
 6561: =pod
 6562: 
 6563: =item scantron_putfile
 6564: 
 6565:     Stores the current version of the bubble sheet data files, and the
 6566:     scan_data hash. (Does not modify the original version only the
 6567:     corrected and skipped versions.
 6568: 
 6569:  Arguments:
 6570:     $scanlines - hash ref that looks like the first return value from
 6571:                  &scantron_getfile()
 6572:     $scan_data - hash ref that looks like the second return value from
 6573:                  &scantron_getfile()
 6574: 
 6575: =cut
 6576: 
 6577: sub scantron_putfile {
 6578:     my ($scanlines,$scan_data) = @_;
 6579:     #FIXME really would prefer a scantron directory
 6580:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6581:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6582:     if ($scanlines) {
 6583: 	my $prefix='scantron_';
 6584: # no need to update orig, shouldn't change
 6585: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6586: #		    $env{'form.scantron_selectfile'});
 6587: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6588: 			$prefix.'corrected_'.
 6589: 			$env{'form.scantron_selectfile'});
 6590: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6591: 			$prefix.'skipped_'.
 6592: 			$env{'form.scantron_selectfile'});
 6593:     }
 6594:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6595: }
 6596: 
 6597: =pod
 6598: 
 6599: =item scantron_get_line
 6600: 
 6601:    Returns the correct version of the scanline
 6602: 
 6603:  Arguments:
 6604:     $scanlines - hash ref that looks like the first return value from
 6605:                  &scantron_getfile()
 6606:     $scan_data - hash ref that looks like the second return value from
 6607:                  &scantron_getfile()
 6608:     $i         - number of the requested line (starts at 0)
 6609: 
 6610:  Returns:
 6611:    A scanline, (either the original or the corrected one if it
 6612:    exists), or undef if the requested scanline should be
 6613:    skipped. (Either because it's an skipped scanline, or it's an
 6614:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6615:    pass.
 6616: 
 6617: =cut
 6618: 
 6619: sub scantron_get_line {
 6620:     my ($scanlines,$scan_data,$i)=@_;
 6621:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6622:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6623:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6624:     return $scanlines->{'orig'}[$i]; 
 6625: }
 6626: 
 6627: =pod
 6628: 
 6629: =item scantron_todo_count
 6630: 
 6631:     Counts the number of scanlines that need processing.
 6632: 
 6633:  Arguments:
 6634:     $scanlines - hash ref that looks like the first return value from
 6635:                  &scantron_getfile()
 6636:     $scan_data - hash ref that looks like the second return value from
 6637:                  &scantron_getfile()
 6638: 
 6639:  Returns:
 6640:     $count - number of scanlines to process
 6641: 
 6642: =cut
 6643: 
 6644: sub get_todo_count {
 6645:     my ($scanlines,$scan_data)=@_;
 6646:     my $count=0;
 6647:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6648: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6649: 	if ($line=~/^[\s\cz]*$/) { next; }
 6650: 	$count++;
 6651:     }
 6652:     return $count;
 6653: }
 6654: 
 6655: =pod
 6656: 
 6657: =item scantron_put_line
 6658: 
 6659:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6660:     data file.
 6661: 
 6662:  Arguments:
 6663:     $scanlines - hash ref that looks like the first return value from
 6664:                  &scantron_getfile()
 6665:     $scan_data - hash ref that looks like the second return value from
 6666:                  &scantron_getfile()
 6667:     $i         - line number to update
 6668:     $newline   - contents of the updated scanline
 6669:     $skip      - if true make the line for skipping and update the
 6670:                  'skipped' file
 6671: 
 6672: =cut
 6673: 
 6674: sub scantron_put_line {
 6675:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6676:     if ($skip) {
 6677: 	$scanlines->{'skipped'}[$i]=$newline;
 6678: 	&start_skipping($scan_data,$i);
 6679: 	return;
 6680:     }
 6681:     $scanlines->{'corrected'}[$i]=$newline;
 6682: }
 6683: 
 6684: =pod
 6685: 
 6686: =item scantron_clear_skip
 6687: 
 6688:    Remove a line from the 'skipped' file
 6689: 
 6690:  Arguments:
 6691:     $scanlines - hash ref that looks like the first return value from
 6692:                  &scantron_getfile()
 6693:     $scan_data - hash ref that looks like the second return value from
 6694:                  &scantron_getfile()
 6695:     $i         - line number to update
 6696: 
 6697: =cut
 6698: 
 6699: sub scantron_clear_skip {
 6700:     my ($scanlines,$scan_data,$i)=@_;
 6701:     if (exists($scanlines->{'skipped'}[$i])) {
 6702: 	undef($scanlines->{'skipped'}[$i]);
 6703: 	return 1;
 6704:     }
 6705:     return 0;
 6706: }
 6707: 
 6708: =pod
 6709: 
 6710: =item scantron_filter_not_exam
 6711: 
 6712:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6713:    filter out resources that are not marked as 'exam' mode
 6714: 
 6715: =cut
 6716: 
 6717: sub scantron_filter_not_exam {
 6718:     my ($curres)=@_;
 6719:     
 6720:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6721: 	# if the user has asked to not have either hidden
 6722: 	# or 'randomout' controlled resources to be graded
 6723: 	# don't include them
 6724: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6725: 	    && $curres->randomout) {
 6726: 	    return 0;
 6727: 	}
 6728: 	return 1;
 6729:     }
 6730:     return 0;
 6731: }
 6732: 
 6733: =pod
 6734: 
 6735: =item scantron_validate_sequence
 6736: 
 6737:     Validates the selected sequence, checking for resource that are
 6738:     not set to exam mode.
 6739: 
 6740: =cut
 6741: 
 6742: sub scantron_validate_sequence {
 6743:     my ($r,$currentphase) = @_;
 6744: 
 6745:     my $navmap=Apache::lonnavmaps::navmap->new();
 6746:     unless (ref($navmap)) {
 6747:         $r->print(&navmap_errormsg());
 6748:         return (1,$currentphase);
 6749:     }
 6750:     my (undef,undef,$sequence)=
 6751: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6752: 
 6753:     my $map=$navmap->getResourceByUrl($sequence);
 6754: 
 6755:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6756:                                     value="ignore" />');
 6757:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6758: 	my @resources=
 6759: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6760: 	if (@resources) {
 6761: 	    $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>");
 6762: 	    return (1,$currentphase);
 6763: 	}
 6764:     }
 6765: 
 6766:     return (0,$currentphase+1);
 6767: }
 6768: 
 6769: 
 6770: 
 6771: sub scantron_validate_ID {
 6772:     my ($r,$currentphase) = @_;
 6773:     
 6774:     #get student info
 6775:     my $classlist=&Apache::loncoursedata::get_classlist();
 6776:     my %idmap=&username_to_idmap($classlist);
 6777: 
 6778:     #get scantron line setup
 6779:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6780:     my ($scanlines,$scan_data)=&scantron_getfile();
 6781: 
 6782:     my $nav_error;
 6783:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6784:     if ($nav_error) {
 6785:         $r->print(&navmap_errormsg());
 6786:         return(1,$currentphase);
 6787:     }
 6788: 
 6789:     my %found=('ids'=>{},'usernames'=>{});
 6790:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6791: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6792: 	if ($line=~/^[\s\cz]*$/) { next; }
 6793: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6794: 						 $scan_data);
 6795: 	my $id=$$scan_record{'scantron.ID'};
 6796: 	my $found;
 6797: 	foreach my $checkid (keys(%idmap)) {
 6798: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6799: 	}
 6800: 	if ($found) {
 6801: 	    my $username=$idmap{$found};
 6802: 	    if ($found{'ids'}{$found}) {
 6803: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6804: 					 $line,'duplicateID',$found);
 6805: 		return(1,$currentphase);
 6806: 	    } elsif ($found{'usernames'}{$username}) {
 6807: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6808: 					 $line,'duplicateID',$username);
 6809: 		return(1,$currentphase);
 6810: 	    }
 6811: 	    #FIXME store away line we previously saw the ID on to use above
 6812: 	    $found{'ids'}{$found}++;
 6813: 	    $found{'usernames'}{$username}++;
 6814: 	} else {
 6815: 	    if ($id =~ /^\s*$/) {
 6816: 		my $username=&scan_data($scan_data,"$i.user");
 6817: 		if (defined($username) && $found{'usernames'}{$username}) {
 6818: 		    &scantron_get_correction($r,$i,$scan_record,
 6819: 					     \%scantron_config,
 6820: 					     $line,'duplicateID',$username);
 6821: 		    return(1,$currentphase);
 6822: 		} elsif (!defined($username)) {
 6823: 		    &scantron_get_correction($r,$i,$scan_record,
 6824: 					     \%scantron_config,
 6825: 					     $line,'incorrectID');
 6826: 		    return(1,$currentphase);
 6827: 		}
 6828: 		$found{'usernames'}{$username}++;
 6829: 	    } else {
 6830: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6831: 					 $line,'incorrectID');
 6832: 		return(1,$currentphase);
 6833: 	    }
 6834: 	}
 6835:     }
 6836: 
 6837:     return (0,$currentphase+1);
 6838: }
 6839: 
 6840: 
 6841: sub scantron_get_correction {
 6842:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6843: #FIXME in the case of a duplicated ID the previous line, probably need
 6844: #to show both the current line and the previous one and allow skipping
 6845: #the previous one or the current one
 6846: 
 6847:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6848: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6849: 			    " for PaperID <tt>[_1]</tt>",
 6850: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6851:     } else {
 6852: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6853: 			    " in scanline [_1] <pre>[_2]</pre>",
 6854: 			    $i,$line)."</p> \n");
 6855:     }
 6856:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6857: 			  "The name on the paper is [_2],[_3]",
 6858: 			  $$scan_record{'scantron.ID'},
 6859: 			  $$scan_record{'scantron.LastName'},
 6860: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6861: 
 6862:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6863:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6864:                            # Array populated for doublebubble or
 6865:     my @lines_to_correct;  # missingbubble errors to build javascript
 6866:                            # to validate radio button checking   
 6867: 
 6868:     if ($error =~ /ID$/) {
 6869: 	if ($error eq 'incorrectID') {
 6870: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6871: 		      "</p>\n");
 6872: 	} elsif ($error eq 'duplicateID') {
 6873: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6874: 	}
 6875: 	$r->print($message);
 6876: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6877: 	$r->print("\n<ul><li> ");
 6878: 	#FIXME it would be nice if this sent back the user ID and
 6879: 	#could do partial userID matches
 6880: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6881: 				       'scantron_username','scantron_domain'));
 6882: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6883: 	$r->print("\n@".
 6884: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6885: 
 6886: 	$r->print('</li>');
 6887:     } elsif ($error =~ /CODE$/) {
 6888: 	if ($error eq 'incorrectCODE') {
 6889: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6890: 	} elsif ($error eq 'duplicateCODE') {
 6891: 	    $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");
 6892: 	}
 6893: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6894: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6895: 	$r->print($message);
 6896: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6897: 	$r->print("\n<br /> ");
 6898: 	my $i=0;
 6899: 	if ($error eq 'incorrectCODE' 
 6900: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6901: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6902: 	    if ($closest > 0) {
 6903: 		foreach my $testcode (@{$closest}) {
 6904: 		    my $checked='';
 6905: 		    if (!$i) { $checked=' checked="checked"'; }
 6906: 		    $r->print("
 6907:    <label>
 6908:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6909:        ".&mt("Use the similar CODE [_1] instead.",
 6910: 	    "<b><tt>".$testcode."</tt></b>")."
 6911:     </label>
 6912:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6913: 		    $r->print("\n<br />");
 6914: 		    $i++;
 6915: 		}
 6916: 	    }
 6917: 	}
 6918: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6919: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6920: 	    $r->print("
 6921:     <label>
 6922:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6923:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6924: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6925:     </label>");
 6926: 	    $r->print("\n<br />");
 6927: 	}
 6928: 
 6929: 	$r->print(<<ENDSCRIPT);
 6930: <script type="text/javascript">
 6931: function change_radio(field) {
 6932:     var slct=document.scantronupload.scantron_CODE_resolution;
 6933:     var i;
 6934:     for (i=0;i<slct.length;i++) {
 6935:         if (slct[i].value==field) { slct[i].checked=true; }
 6936:     }
 6937: }
 6938: </script>
 6939: ENDSCRIPT
 6940: 	my $href="/adm/pickcode?".
 6941: 	   "form=".&escape("scantronupload").
 6942: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6943: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6944: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6945: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6946: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6947: 	    $r->print("
 6948:     <label>
 6949:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6950:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6951: 	     "<a target='_blank' href='$href'>","</a>")."
 6952:     </label> 
 6953:     ".&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\')" />'));
 6954: 	    $r->print("\n<br />");
 6955: 	}
 6956: 	$r->print("
 6957:     <label>
 6958:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6959:        ".&mt("Use [_1] as the CODE.",
 6960: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6961: 	$r->print("\n<br /><br />");
 6962:     } elsif ($error eq 'doublebubble') {
 6963: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6964: 
 6965: 	# The form field scantron_questions is acutally a list of line numbers.
 6966: 	# represented by this form so:
 6967: 
 6968: 	my $line_list = &questions_to_line_list($arg);
 6969: 
 6970: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6971: 		  $line_list.'" />');
 6972: 	$r->print($message);
 6973: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6974: 	foreach my $question (@{$arg}) {
 6975: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6976:                                                    $scan_record, $error);
 6977:             push(@lines_to_correct,@linenums);
 6978: 	}
 6979:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6980:     } elsif ($error eq 'missingbubble') {
 6981: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6982: 	$r->print($message);
 6983: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6984: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6985: 
 6986: 	# The form field scantron_questions is actually a list of line numbers not
 6987: 	# a list of question numbers. Therefore:
 6988: 	#
 6989: 	
 6990: 	my $line_list = &questions_to_line_list($arg);
 6991: 
 6992: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6993: 		  $line_list.'" />');
 6994: 	foreach my $question (@{$arg}) {
 6995: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6996:                                                    $scan_record, $error);
 6997:             push(@lines_to_correct,@linenums);
 6998: 	}
 6999:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 7000:     } else {
 7001: 	$r->print("\n<ul>");
 7002:     }
 7003:     $r->print("\n</li></ul>");
 7004: }
 7005: 
 7006: sub verify_bubbles_checked {
 7007:     my (@ansnums) = @_;
 7008:     my $ansnumstr = join('","',@ansnums);
 7009:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7010:     my $output = (<<ENDSCRIPT);
 7011: <script type="text/javascript">
 7012: function verify_bubble_radio(form) {
 7013:     var ansnumArray = new Array ("$ansnumstr");
 7014:     var need_bubble_count = 0;
 7015:     for (var i=0; i<ansnumArray.length; i++) {
 7016:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7017:             var bubble_picked = 0; 
 7018:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7019:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7020:                     bubble_picked = 1;
 7021:                 }
 7022:             }
 7023:             if (bubble_picked == 0) {
 7024:                 need_bubble_count ++;
 7025:             }
 7026:         }
 7027:     }
 7028:     if (need_bubble_count) {
 7029:         alert("$warning");
 7030:         return;
 7031:     }
 7032:     form.submit(); 
 7033: }
 7034: </script>
 7035: ENDSCRIPT
 7036:     return $output;
 7037: }
 7038: 
 7039: =pod
 7040: 
 7041: =item  questions_to_line_list
 7042: 
 7043: Converts a list of questions into a string of comma separated
 7044: line numbers in the answer sheet used by the questions.  This is
 7045: used to fill in the scantron_questions form field.
 7046: 
 7047:   Arguments:
 7048:      questions    - Reference to an array of questions.
 7049: 
 7050: =cut
 7051: 
 7052: 
 7053: sub questions_to_line_list {
 7054:     my ($questions) = @_;
 7055:     my @lines;
 7056: 
 7057:     foreach my $item (@{$questions}) {
 7058:         my $question = $item;
 7059:         my ($first,$count,$last);
 7060:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7061:             $question = $1;
 7062:             my $subquestion = $2;
 7063:             $first = $first_bubble_line{$question-1} + 1;
 7064:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7065:             my $subcount = 1;
 7066:             while ($subcount<$subquestion) {
 7067:                 $first += $subans[$subcount-1];
 7068:                 $subcount ++;
 7069:             }
 7070:             $count = $subans[$subquestion-1];
 7071:         } else {
 7072: 	    $first   = $first_bubble_line{$question-1} + 1;
 7073: 	    $count   = $bubble_lines_per_response{$question-1};
 7074:         }
 7075:         $last = $first+$count-1;
 7076:         push(@lines, ($first..$last));
 7077:     }
 7078:     return join(',', @lines);
 7079: }
 7080: 
 7081: =pod 
 7082: 
 7083: =item prompt_for_corrections
 7084: 
 7085: Prompts for a potentially multiline correction to the
 7086: user's bubbling (factors out common code from scantron_get_correction
 7087: for multi and missing bubble cases).
 7088: 
 7089:  Arguments:
 7090:    $r           - Apache request object.
 7091:    $question    - The question number to prompt for.
 7092:    $scan_config - The scantron file configuration hash.
 7093:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7094:    $error       - Type of error
 7095: 
 7096:  Implicit inputs:
 7097:    %bubble_lines_per_response   - Starting line numbers for each question.
 7098:                                   Numbered from 0 (but question numbers are from
 7099:                                   1.
 7100:    %first_bubble_line           - Starting bubble line for each question.
 7101:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7102:                                   type problems render as separate sub-questions, 
 7103:                                   in exam mode. This hash contains a 
 7104:                                   comma-separated list of the lines per 
 7105:                                   sub-question.
 7106:    %responsetype_per_response   - essayresponse, formularesponse,
 7107:                                   stringresponse, imageresponse, reactionresponse,
 7108:                                   and organicresponse type problem parts can have
 7109:                                   multiple lines per response if the weight
 7110:                                   assigned exceeds 10.  In this case, only
 7111:                                   one bubble per line is permitted, but more 
 7112:                                   than one line might contain bubbles, e.g.
 7113:                                   bubbling of: line 1 - J, line 2 - J, 
 7114:                                   line 3 - B would assign 22 points.  
 7115: 
 7116: =cut
 7117: 
 7118: sub prompt_for_corrections {
 7119:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7120:     my ($current_line,$lines);
 7121:     my @linenums;
 7122:     my $questionnum = $question;
 7123:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7124:         $question = $1;
 7125:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7126:         my $subquestion = $2;
 7127:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7128:         my $subcount = 1;
 7129:         while ($subcount<$subquestion) {
 7130:             $current_line += $subans[$subcount-1];
 7131:             $subcount ++;
 7132:         }
 7133:         $lines = $subans[$subquestion-1];
 7134:     } else {
 7135:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7136:         $lines        = $bubble_lines_per_response{$question-1};
 7137:     }
 7138:     if ($lines > 1) {
 7139:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7140:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7141:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7142:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7143:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7144:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7145:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7146:             $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 />');
 7147:         } else {
 7148:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7149:         }
 7150:     }
 7151:     for (my $i =0; $i < $lines; $i++) {
 7152:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7153: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7154: 	        		  $questionnum,$error,split('', $selected));
 7155:         push(@linenums,$current_line);
 7156: 	$current_line++;
 7157:     }
 7158:     if ($lines > 1) {
 7159: 	$r->print("<hr /><br />");
 7160:     }
 7161:     return @linenums;
 7162: }
 7163: 
 7164: =pod
 7165: 
 7166: =item scantron_bubble_selector
 7167:   
 7168:    Generates the html radiobuttons to correct a single bubble line
 7169:    possibly showing the existing the selected bubbles if known
 7170: 
 7171:  Arguments:
 7172:     $r           - Apache request object
 7173:     $scan_config - hash from &get_scantron_config()
 7174:     $line        - Number of the line being displayed.
 7175:     $questionnum - Question number (may include subquestion)
 7176:     $error       - Type of error.
 7177:     @selected    - Array of bubbles picked on this line.
 7178: 
 7179: =cut
 7180: 
 7181: sub scantron_bubble_selector {
 7182:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7183:     my $max=$$scan_config{'Qlength'};
 7184: 
 7185:     my $scmode=$$scan_config{'Qon'};
 7186:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7187: 
 7188:     my @alphabet=('A'..'Z');
 7189:     $r->print(&Apache::loncommon::start_data_table().
 7190:               &Apache::loncommon::start_data_table_row());
 7191:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7192:     for (my $i=0;$i<$max+1;$i++) {
 7193: 	$r->print("\n".'<td align="center">');
 7194: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7195: 	else { $r->print('&nbsp;'); }
 7196: 	$r->print('</td>');
 7197:     }
 7198:     $r->print(&Apache::loncommon::end_data_table_row().
 7199:               &Apache::loncommon::start_data_table_row());
 7200:     for (my $i=0;$i<$max;$i++) {
 7201: 	$r->print("\n".
 7202: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7203: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7204:     }
 7205:     my $nobub_checked = ' ';
 7206:     if ($error eq 'missingbubble') {
 7207:         $nobub_checked = ' checked = "checked" ';
 7208:     }
 7209:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7210: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7211:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7212:               $line.'" value="'.$questionnum.'" /></td>');
 7213:     $r->print(&Apache::loncommon::end_data_table_row().
 7214:               &Apache::loncommon::end_data_table());
 7215: }
 7216: 
 7217: =pod
 7218: 
 7219: =item num_matches
 7220: 
 7221:    Counts the number of characters that are the same between the two arguments.
 7222: 
 7223:  Arguments:
 7224:    $orig - CODE from the scanline
 7225:    $code - CODE to match against
 7226: 
 7227:  Returns:
 7228:    $count - integer count of the number of same characters between the
 7229:             two arguments
 7230: 
 7231: =cut
 7232: 
 7233: sub num_matches {
 7234:     my ($orig,$code) = @_;
 7235:     my @code=split(//,$code);
 7236:     my @orig=split(//,$orig);
 7237:     my $same=0;
 7238:     for (my $i=0;$i<scalar(@code);$i++) {
 7239: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7240:     }
 7241:     return $same;
 7242: }
 7243: 
 7244: =pod
 7245: 
 7246: =item scantron_get_closely_matching_CODEs
 7247: 
 7248:    Cycles through all CODEs and finds the set that has the greatest
 7249:    number of same characters as the provided CODE
 7250: 
 7251:  Arguments:
 7252:    $allcodes - hash ref returned by &get_codes()
 7253:    $CODE     - CODE from the current scanline
 7254: 
 7255:  Returns:
 7256:    2 element list
 7257:     - first elements is number of how closely matching the best fit is 
 7258:       (5 means best set has 5 matching characters)
 7259:     - second element is an arrary ref containing the set of valid CODEs
 7260:       that best fit the passed in CODE
 7261: 
 7262: =cut
 7263: 
 7264: sub scantron_get_closely_matching_CODEs {
 7265:     my ($allcodes,$CODE)=@_;
 7266:     my @CODEs;
 7267:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7268: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7269:     }
 7270: 
 7271:     return ($#CODEs,$CODEs[-1]);
 7272: }
 7273: 
 7274: =pod
 7275: 
 7276: =item get_codes
 7277: 
 7278:    Builds a hash which has keys of all of the valid CODEs from the selected
 7279:    set of remembered CODEs.
 7280: 
 7281:  Arguments:
 7282:   $old_name - name of the set of remembered CODEs
 7283:   $cdom     - domain of the course
 7284:   $cnum     - internal course name
 7285: 
 7286:  Returns:
 7287:   %allcodes - keys are the valid CODEs, values are all 1
 7288: 
 7289: =cut
 7290: 
 7291: sub get_codes {
 7292:     my ($old_name, $cdom, $cnum) = @_;
 7293:     if (!$old_name) {
 7294: 	$old_name=$env{'form.scantron_CODElist'};
 7295:     }
 7296:     if (!$cdom) {
 7297: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7298:     }
 7299:     if (!$cnum) {
 7300: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7301:     }
 7302:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7303: 				    $cdom,$cnum);
 7304:     my %allcodes;
 7305:     if ($result{"type\0$old_name"} eq 'number') {
 7306: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7307:     } else {
 7308: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7309:     }
 7310:     return %allcodes;
 7311: }
 7312: 
 7313: =pod
 7314: 
 7315: =item scantron_validate_CODE
 7316: 
 7317:    Validates all scanlines in the selected file to not have any
 7318:    invalid or underspecified CODEs and that none of the codes are
 7319:    duplicated if this was requested.
 7320: 
 7321: =cut
 7322: 
 7323: sub scantron_validate_CODE {
 7324:     my ($r,$currentphase) = @_;
 7325:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7326:     if ($scantron_config{'CODElocation'} &&
 7327: 	$scantron_config{'CODEstart'} &&
 7328: 	$scantron_config{'CODElength'}) {
 7329: 	if (!defined($env{'form.scantron_CODElist'})) {
 7330: 	    &FIXME_blow_up()
 7331: 	}
 7332:     } else {
 7333: 	return (0,$currentphase+1);
 7334:     }
 7335:     
 7336:     my %usedCODEs;
 7337: 
 7338:     my %allcodes=&get_codes();
 7339: 
 7340:     my $nav_error;
 7341:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7342:     if ($nav_error) {
 7343:         $r->print(&navmap_errormsg());
 7344:         return(1,$currentphase);
 7345:     }
 7346: 
 7347:     my ($scanlines,$scan_data)=&scantron_getfile();
 7348:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7349: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7350: 	if ($line=~/^[\s\cz]*$/) { next; }
 7351: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7352: 						 $scan_data);
 7353: 	my $CODE=$$scan_record{'scantron.CODE'};
 7354: 	my $error=0;
 7355: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7356: 	    &scantron_get_correction($r,$i,$scan_record,
 7357: 				     \%scantron_config,
 7358: 				     $line,'incorrectCODE',\%allcodes);
 7359: 	    return(1,$currentphase);
 7360: 	}
 7361: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7362: 	    && !$$scan_record{'scantron.useCODE'}) {
 7363: 	    &scantron_get_correction($r,$i,$scan_record,
 7364: 				     \%scantron_config,
 7365: 				     $line,'incorrectCODE',\%allcodes);
 7366: 	    return(1,$currentphase);
 7367: 	}
 7368: 	if (exists($usedCODEs{$CODE}) 
 7369: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7370: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7371: 	    &scantron_get_correction($r,$i,$scan_record,
 7372: 				     \%scantron_config,
 7373: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7374: 	    return(1,$currentphase);
 7375: 	}
 7376: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7377:     }
 7378:     return (0,$currentphase+1);
 7379: }
 7380: 
 7381: =pod
 7382: 
 7383: =item scantron_validate_doublebubble
 7384: 
 7385:    Validates all scanlines in the selected file to not have any
 7386:    bubble lines with multiple bubbles marked.
 7387: 
 7388: =cut
 7389: 
 7390: sub scantron_validate_doublebubble {
 7391:     my ($r,$currentphase) = @_;
 7392:     #get student info
 7393:     my $classlist=&Apache::loncoursedata::get_classlist();
 7394:     my %idmap=&username_to_idmap($classlist);
 7395: 
 7396:     #get scantron line setup
 7397:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7398:     my ($scanlines,$scan_data)=&scantron_getfile();
 7399:     my $nav_error;
 7400:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7401:     if ($nav_error) {
 7402:         $r->print(&navmap_errormsg());
 7403:         return(1,$currentphase);
 7404:     }
 7405: 
 7406:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7407: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7408: 	if ($line=~/^[\s\cz]*$/) { next; }
 7409: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7410: 						 $scan_data);
 7411: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7412: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7413: 				 'doublebubble',
 7414: 				 $$scan_record{'scantron.doubleerror'});
 7415:     	return (1,$currentphase);
 7416:     }
 7417:     return (0,$currentphase+1);
 7418: }
 7419: 
 7420: 
 7421: sub scantron_get_maxbubble {
 7422:     my ($nav_error) = @_;
 7423:     if (defined($env{'form.scantron_maxbubble'}) &&
 7424: 	$env{'form.scantron_maxbubble'}) {
 7425: 	&restore_bubble_lines();
 7426: 	return $env{'form.scantron_maxbubble'};
 7427:     }
 7428: 
 7429:     my (undef, undef, $sequence) =
 7430: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7431: 
 7432:     my $navmap=Apache::lonnavmaps::navmap->new();
 7433:     unless (ref($navmap)) {
 7434:         if (ref($nav_error)) {
 7435:             $$nav_error = 1;
 7436:         }
 7437:     }
 7438:     my $map=$navmap->getResourceByUrl($sequence);
 7439:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7440: 
 7441:     &Apache::lonxml::clear_problem_counter();
 7442: 
 7443:     my $uname       = $env{'user.name'};
 7444:     my $udom        = $env{'user.domain'};
 7445:     my $cid         = $env{'request.course.id'};
 7446:     my $total_lines = 0;
 7447:     %bubble_lines_per_response = ();
 7448:     %first_bubble_line         = ();
 7449:     %subdivided_bubble_lines   = ();
 7450:     %responsetype_per_response = ();
 7451: 
 7452:     my $response_number = 0;
 7453:     my $bubble_line     = 0;
 7454:     foreach my $resource (@resources) {
 7455:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7456:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7457: 	    foreach my $part_id (@{$parts}) {
 7458:                 my $lines;
 7459: 
 7460: 	        # TODO - make this a persistent hash not an array.
 7461: 
 7462:                 # optionresponse, matchresponse and rankresponse type items 
 7463:                 # render as separate sub-questions in exam mode.
 7464:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7465:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7466:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7467:                     my ($numbub,$numshown);
 7468:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7469:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7470:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7471:                         }
 7472:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7473:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7474:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7475:                         }
 7476:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7477:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7478:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7479:                         }
 7480:                     }
 7481:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7482:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7483:                     }
 7484:                     my $bubbles_per_line = 10;
 7485:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7486:                     if (($numbub % $bubbles_per_line) != 0) {
 7487:                         $inner_bubble_lines++;
 7488:                     }
 7489:                     for (my $i=0; $i<$numshown; $i++) {
 7490:                         $subdivided_bubble_lines{$response_number} .= 
 7491:                             $inner_bubble_lines.',';
 7492:                     }
 7493:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7494:                     $lines = $numshown * $inner_bubble_lines;
 7495:                 } else {
 7496:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7497:                 } 
 7498: 
 7499:                 $first_bubble_line{$response_number} = $bubble_line;
 7500: 	        $bubble_lines_per_response{$response_number} = $lines;
 7501:                 $responsetype_per_response{$response_number} = 
 7502:                     $analysis->{$part_id.'.type'};
 7503: 	        $response_number++;
 7504: 
 7505: 	        $bubble_line +=  $lines;
 7506: 	        $total_lines +=  $lines;
 7507: 	    }
 7508:         }
 7509:     }
 7510:     &Apache::lonnet::delenv('scantron.');
 7511: 
 7512:     &save_bubble_lines();
 7513:     $env{'form.scantron_maxbubble'} =
 7514: 	$total_lines;
 7515:     return $env{'form.scantron_maxbubble'};
 7516: }
 7517: 
 7518: sub scantron_validate_missingbubbles {
 7519:     my ($r,$currentphase) = @_;
 7520:     #get student info
 7521:     my $classlist=&Apache::loncoursedata::get_classlist();
 7522:     my %idmap=&username_to_idmap($classlist);
 7523: 
 7524:     #get scantron line setup
 7525:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7526:     my ($scanlines,$scan_data)=&scantron_getfile();
 7527:     my $nav_error;
 7528:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7529:     if ($nav_error) {
 7530:         return(1,$currentphase);
 7531:     }
 7532:     if (!$max_bubble) { $max_bubble=2**31; }
 7533:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7534: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7535: 	if ($line=~/^[\s\cz]*$/) { next; }
 7536: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7537: 						 $scan_data);
 7538: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7539: 	my @to_correct;
 7540: 	
 7541: 	# Probably here's where the error is...
 7542: 
 7543: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7544:             my $lastbubble;
 7545:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7546:                my $question = $1;
 7547:                my $subquestion = $2;
 7548:                if (!defined($first_bubble_line{$question -1})) { next; }
 7549:                my $first = $first_bubble_line{$question-1};
 7550:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7551:                my $subcount = 1;
 7552:                while ($subcount<$subquestion) {
 7553:                    $first += $subans[$subcount-1];
 7554:                    $subcount ++;
 7555:                }
 7556:                my $count = $subans[$subquestion-1];
 7557:                $lastbubble = $first + $count;
 7558:             } else {
 7559:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7560:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7561:             }
 7562:             if ($lastbubble > $max_bubble) { next; }
 7563: 	    push(@to_correct,$missing);
 7564: 	}
 7565: 	if (@to_correct) {
 7566: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7567: 				     $line,'missingbubble',\@to_correct);
 7568: 	    return (1,$currentphase);
 7569: 	}
 7570: 
 7571:     }
 7572:     return (0,$currentphase+1);
 7573: }
 7574: 
 7575: 
 7576: sub scantron_process_students {
 7577:     my ($r) = @_;
 7578: 
 7579:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7580:     my ($symb)=&get_symb($r);
 7581:     if (!$symb) {
 7582: 	return '';
 7583:     }
 7584:     my $default_form_data=&defaultFormData($symb);
 7585: 
 7586:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7587:     my ($scanlines,$scan_data)=&scantron_getfile();
 7588:     my $classlist=&Apache::loncoursedata::get_classlist();
 7589:     my %idmap=&username_to_idmap($classlist);
 7590:     my $navmap=Apache::lonnavmaps::navmap->new();
 7591:     unless (ref($navmap)) {
 7592:         $r->print(&navmap_errormsg());
 7593:         return '';
 7594:     }  
 7595:     my $map=$navmap->getResourceByUrl($sequence);
 7596:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7597:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7598:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7599:                             \%grader_randomlists_by_symb);
 7600:     foreach my $resource (@resources) {
 7601:         my $ressymb = $resource->symb();
 7602:         my ($analysis,$parts) =
 7603:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7604:                                       $env{'user.name'},$env{'user.domain'},1);
 7605:         $grader_partids_by_symb{$ressymb} = $parts;
 7606:         if (ref($analysis) eq 'HASH') {
 7607:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7608:                 $grader_randomlists_by_symb{$ressymb} = 
 7609:                     $analysis->{'parts_withrandomlist'};
 7610:             }
 7611:         }
 7612:     }
 7613: 
 7614:     my ($uname,$udom);
 7615:     my $result= <<SCANTRONFORM;
 7616: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7617:   <input type="hidden" name="command" value="scantron_configphase" />
 7618:   $default_form_data
 7619: SCANTRONFORM
 7620:     $r->print($result);
 7621: 
 7622:     my @delayqueue;
 7623:     my (%completedstudents,%scandata);
 7624:     
 7625:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7626:     my $count=&get_todo_count($scanlines,$scan_data);
 7627:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7628:  				    'Bubblesheet Progress',$count,
 7629: 				    'inline',undef,'scantronupload');
 7630:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7631: 					  'Processing first student');
 7632:     $r->print('<br />');
 7633:     my $start=&Time::HiRes::time();
 7634:     my $i=-1;
 7635:     my $started;
 7636: 
 7637:     my $nav_error;
 7638:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7639:     if ($nav_error) {
 7640:         $r->print(&navmap_errormsg());
 7641:         return '';
 7642:     }
 7643: 
 7644:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7645:     # the user and return.
 7646: 
 7647:     if ($ssi_error) {
 7648: 	$r->print("</form>");
 7649: 	&ssi_print_error($r);
 7650: 	$r->print(&show_grading_menu_form($symb));
 7651:         &Apache::lonnet::remove_lock($lock);
 7652: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7653:     }
 7654: 
 7655:     my %lettdig = &letter_to_digits();
 7656:     my $numletts = scalar(keys(%lettdig));
 7657: 
 7658:     while ($i<$scanlines->{'count'}) {
 7659:  	($uname,$udom)=('','');
 7660:  	$i++;
 7661:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7662:  	if ($line=~/^[\s\cz]*$/) { next; }
 7663: 	if ($started) {
 7664: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7665: 						     'last student');
 7666: 	}
 7667: 	$started=1;
 7668:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7669:  						 $scan_data);
 7670:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7671:  					      \%idmap,$i)) {
 7672:   	    &scantron_add_delay(\@delayqueue,$line,
 7673:  				'Unable to find a student that matches',1);
 7674:  	    next;
 7675:   	}
 7676:  	if (exists $completedstudents{$uname}) {
 7677:  	    &scantron_add_delay(\@delayqueue,$line,
 7678:  				'Student '.$uname.' has multiple sheets',2);
 7679:  	    next;
 7680:  	}
 7681:   	($uname,$udom)=split(/:/,$uname);
 7682: 
 7683:         my %partids_by_symb;
 7684:         foreach my $resource (@resources) {
 7685:             my $ressymb = $resource->symb();
 7686:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7687:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7688:                 my ($analysis,$parts) =
 7689:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7690:                 $partids_by_symb{$ressymb} = $parts;
 7691:             } else {
 7692:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7693:             }
 7694:         }
 7695: 
 7696: 	&Apache::lonxml::clear_problem_counter();
 7697:   	&Apache::lonnet::appenv($scan_record);
 7698: 
 7699: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7700: 	    &scantron_putfile($scanlines,$scan_data);
 7701: 	}
 7702: 	
 7703:         my $scancode;
 7704:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7705:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7706:             $scancode = $scan_record->{'scantron.CODE'};
 7707:         } else {
 7708:             $scancode = '';
 7709:         }
 7710: 
 7711:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7712:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7713:             $ssi_error = 0; # So end of handler error message does not trigger.
 7714:             $r->print("</form>");
 7715:             &ssi_print_error($r);
 7716:             $r->print(&show_grading_menu_form($symb));
 7717:             &Apache::lonnet::remove_lock($lock);
 7718:             return '';      # Why return ''?  Beats me.
 7719:         }
 7720: 
 7721: 	$completedstudents{$uname}={'line'=>$line};
 7722:         if ($env{'form.verifyrecord'}) {
 7723:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7724:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7725:             chomp($studentdata);
 7726:             $studentdata =~ s/\r$//;
 7727:             my $studentrecord = '';
 7728:             my $counter = -1;
 7729:             foreach my $resource (@resources) {
 7730:                 my $ressymb = $resource->symb();
 7731:                 ($counter,my $recording) =
 7732:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7733:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7734:                                              \%scantron_config,\%lettdig,$numletts);
 7735:                 $studentrecord .= $recording;
 7736:             }
 7737:             if ($studentrecord ne $studentdata) {
 7738:                 &Apache::lonxml::clear_problem_counter();
 7739:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7740:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7741:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7742:                     $r->print("</form>");
 7743:                     &ssi_print_error($r);
 7744:                     $r->print(&show_grading_menu_form($symb));
 7745:                     &Apache::lonnet::remove_lock($lock);
 7746:                     delete($completedstudents{$uname});
 7747:                     return '';
 7748:                 }
 7749:                 $counter = -1;
 7750:                 $studentrecord = '';
 7751:                 foreach my $resource (@resources) {
 7752:                     my $ressymb = $resource->symb();
 7753:                     ($counter,my $recording) =
 7754:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7755:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7756:                                                  \%scantron_config,\%lettdig,$numletts);
 7757:                     $studentrecord .= $recording;
 7758:                 }
 7759:                 if ($studentrecord ne $studentdata) {
 7760:                     $r->print('<p><span class="LC_error">');
 7761:                     if ($scancode eq '') {
 7762:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7763:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7764:                     } else {
 7765:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7766:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7767:                     }
 7768:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7769:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7770:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7771:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7772:                               &Apache::loncommon::start_data_table_row().
 7773:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7774:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7775:                               &Apache::loncommon::end_data_table_row().
 7776:                               &Apache::loncommon::start_data_table_row().
 7777:                               '<td>Stored submissions</td>'.
 7778:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7779:                               &Apache::loncommon::end_data_table_row().
 7780:                               &Apache::loncommon::end_data_table().'</p>');
 7781:                 } else {
 7782:                     $r->print('<br /><span class="LC_warning">'.
 7783:                              &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 />'.
 7784:                              &mt("As a consequence, this user's submission history records two tries.").
 7785:                                  '</span><br />');
 7786:                 }
 7787:             }
 7788:         }
 7789:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7790:     } continue {
 7791: 	&Apache::lonxml::clear_problem_counter();
 7792: 	&Apache::lonnet::delenv('scantron.');
 7793:     }
 7794:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7795:     &Apache::lonnet::remove_lock($lock);
 7796: #    my $lasttime = &Time::HiRes::time()-$start;
 7797: #    $r->print("<p>took $lasttime</p>");
 7798: 
 7799:     $r->print("</form>");
 7800:     $r->print(&show_grading_menu_form($symb));
 7801:     return '';
 7802: }
 7803: 
 7804: sub graders_resources_pass {
 7805:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7806:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7807:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7808:         foreach my $resource (@{$resources}) {
 7809:             my $ressymb = $resource->symb();
 7810:             my ($analysis,$parts) =
 7811:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7812:                                           $env{'user.name'},$env{'user.domain'},1);
 7813:             $grader_partids_by_symb->{$ressymb} = $parts;
 7814:             if (ref($analysis) eq 'HASH') {
 7815:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7816:                     $grader_randomlists_by_symb->{$ressymb} =
 7817:                         $analysis->{'parts_withrandomlist'};
 7818:                 }
 7819:             }
 7820:         }
 7821:     }
 7822:     return;
 7823: }
 7824: 
 7825: sub grade_student_bubbles {
 7826:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7827:     if (ref($resources) eq 'ARRAY') {
 7828:         my $count = 0;
 7829:         foreach my $resource (@{$resources}) {
 7830:             my $ressymb = $resource->symb();
 7831:             my %form = ('submitted'      => 'scantron',
 7832:                         'grade_target'   => 'grade',
 7833:                         'grade_username' => $uname,
 7834:                         'grade_domain'   => $udom,
 7835:                         'grade_courseid' => $env{'request.course.id'},
 7836:                         'grade_symb'     => $ressymb,
 7837:                         'CODE'           => $scancode
 7838:                        );
 7839:             if (ref($parts) eq 'HASH') {
 7840:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7841:                     foreach my $part (@{$parts->{$ressymb}}) {
 7842:                         $form{'scantron_questnum_start.'.$part} =
 7843:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7844:                         $count++;
 7845:                     }
 7846:                 }
 7847:             }
 7848:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7849:             return 'ssi_error' if ($ssi_error);
 7850:             last if (&Apache::loncommon::connection_aborted($r));
 7851:         }
 7852:     }
 7853:     return;
 7854: }
 7855: 
 7856: sub scantron_upload_scantron_data {
 7857:     my ($r)=@_;
 7858:     my $dom = $env{'request.role.domain'};
 7859:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7860:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7861:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7862: 							  'domainid',
 7863: 							  'coursename',$dom);
 7864:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7865:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7866:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7867:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7868:     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.");
 7869:     $r->print('
 7870: <script type="text/javascript" language="javascript">
 7871:     function checkUpload(formname) {
 7872: 	if (formname.upfile.value == "") {
 7873: 	    alert("'.$nofile_alert.'");
 7874: 	    return false;
 7875: 	}
 7876:         if (formname.courseid.value == "") {
 7877:             alert("'.$nocourseid_alert.'");
 7878:             return false;
 7879:         }
 7880: 	formname.submit();
 7881:     }
 7882: 
 7883:     function ToSyllabus() {
 7884:         var cdom = '."'$dom'".';
 7885:         var cnum = document.rules.courseid.value;
 7886:         if (cdom == "" || cdom == null) {
 7887:             return;
 7888:         }
 7889:         if (cnum == "" || cnum == null) {
 7890:            return;
 7891:         }
 7892:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7893:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7894:         return;
 7895:     }
 7896: 
 7897: </script>
 7898: 
 7899: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7900: 
 7901: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7902: '.$default_form_data.
 7903:   &Apache::lonhtmlcommon::start_pick_box().
 7904:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7905:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7906:   &Apache::lonhtmlcommon::row_closure().
 7907:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7908:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7909:   &Apache::lonhtmlcommon::row_closure().
 7910:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7911:   '<input name="domainid" type="hidden" />'.$domdesc.
 7912:   &Apache::lonhtmlcommon::row_closure().
 7913:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7914:   '<input type="file" name="upfile" size="50" />'.
 7915:   &Apache::lonhtmlcommon::row_closure(1).
 7916:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7917: 
 7918: <input name="command" value="scantronupload_save" type="hidden" />
 7919: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7920: </form>
 7921: ');
 7922:     return '';
 7923: }
 7924: 
 7925: 
 7926: sub scantron_upload_scantron_data_save {
 7927:     my($r)=@_;
 7928:     my ($symb)=&get_symb($r,1);
 7929:     my $doanotherupload=
 7930: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7931: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7932: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7933: 	'</form>'."\n";
 7934:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7935: 	!&Apache::lonnet::allowed('usc',
 7936: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7937: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7938: 	if ($symb) {
 7939: 	    $r->print(&show_grading_menu_form($symb));
 7940: 	} else {
 7941: 	    $r->print($doanotherupload);
 7942: 	}
 7943: 	return '';
 7944:     }
 7945:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7946:     my $uploadedfile;
 7947:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7948:     if (length($env{'form.upfile'}) < 2) {
 7949:         $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>'));
 7950:     } else {
 7951:         my $result = 
 7952:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7953:                                             $env{'form.courseid'},$env{'form.domainid'});
 7954: 	if ($result =~ m{^/uploaded/}) {
 7955: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7956:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7957: 			  '<span class="LC_filename">'.$result.'</span>'));
 7958:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7959:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7960:                                                        $env{'form.courseid'},$uploadedfile));
 7961: 	} else {
 7962: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7963:                           '<span class="LC_error">','</span>',$result,
 7964: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7965: 	}
 7966:     }
 7967:     if ($symb) {
 7968: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7969:     } else {
 7970: 	$r->print($doanotherupload);
 7971:     }
 7972:     return '';
 7973: }
 7974: 
 7975: sub validate_uploaded_scantron_file {
 7976:     my ($cdom,$cname,$fname) = @_;
 7977:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7978:     my @lines;
 7979:     if ($scanlines ne '-1') {
 7980:         @lines=split("\n",$scanlines,-1);
 7981:     }
 7982:     my $output;
 7983:     if (@lines) {
 7984:         my (%counts,$max_match_format);
 7985:         my ($max_match_count,$max_match_pct) = (0,0);
 7986:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7987:         my %idmap = &username_to_idmap($classlist);
 7988:         foreach my $key (keys(%idmap)) {
 7989:             my $lckey = lc($key);
 7990:             $idmap{$lckey} = $idmap{$key};
 7991:         }
 7992:         my %unique_formats;
 7993:         my @formatlines = &get_scantronformat_file();
 7994:         foreach my $line (@formatlines) {
 7995:             chomp($line);
 7996:             my @config = split(/:/,$line);
 7997:             my $idstart = $config[5];
 7998:             my $idlength = $config[6];
 7999:             if (($idstart ne '') && ($idlength > 0)) {
 8000:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8001:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8002:                 } else {
 8003:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8004:                 }
 8005:             }
 8006:         }
 8007:         foreach my $key (keys(%unique_formats)) {
 8008:             my ($idstart,$idlength) = split(':',$key);
 8009:             %{$counts{$key}} = (
 8010:                                'found'   => 0,
 8011:                                'total'   => 0,
 8012:                               );
 8013:             foreach my $line (@lines) {
 8014:                 next if ($line =~ /^#/);
 8015:                 next if ($line =~ /^[\s\cz]*$/);
 8016:                 my $id = substr($line,$idstart-1,$idlength);
 8017:                 $id = lc($id);
 8018:                 if (exists($idmap{$id})) {
 8019:                     $counts{$key}{'found'} ++;
 8020:                 }
 8021:                 $counts{$key}{'total'} ++;
 8022:             }
 8023:             if ($counts{$key}{'total'}) {
 8024:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8025:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8026:                     $max_match_pct = $percent_match;
 8027:                     $max_match_format = $key;
 8028:                     $max_match_count = $counts{$key}{'total'};
 8029:                 }
 8030:             }
 8031:         }
 8032:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8033:             my $format_descs;
 8034:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8035:             for (my $i=0; $i<$numwithformat; $i++) {
 8036:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8037:                 if ($i<$numwithformat-2) {
 8038:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8039:                 } elsif ($i==$numwithformat-2) {
 8040:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8041:                 } elsif ($i==$numwithformat-1) {
 8042:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8043:                 }
 8044:             }
 8045:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8046:             $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).
 8047:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8048:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8049:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8050:                                   '<i>'.$cdom.'</i>').'</li>'.
 8051:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8052:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8053:                        '</ul>';
 8054:         }
 8055:     } else {
 8056:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8057:     }
 8058:     return $output;
 8059: }
 8060: 
 8061: sub valid_file {
 8062:     my ($requested_file)=@_;
 8063:     foreach my $filename (sort(&scantron_filenames())) {
 8064: 	if ($requested_file eq $filename) { return 1; }
 8065:     }
 8066:     return 0;
 8067: }
 8068: 
 8069: sub scantron_download_scantron_data {
 8070:     my ($r)=@_;
 8071:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8072:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8073:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8074:     my $file=$env{'form.scantron_selectfile'};
 8075:     if (! &valid_file($file)) {
 8076: 	$r->print('
 8077: 	<p>
 8078: 	    '.&mt('The requested file name was invalid.').'
 8079:         </p>
 8080: ');
 8081: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8082: 	return;
 8083:     }
 8084:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8085:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8086:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8087:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8088:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8089:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8090:     $r->print('
 8091:     <p>
 8092: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8093: 	      '<a href="'.$orig.'">','</a>').'
 8094:     </p>
 8095:     <p>
 8096: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8097: 	      '<a href="'.$corrected.'">','</a>').'
 8098:     </p>
 8099:     <p>
 8100: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8101: 	      '<a href="'.$skipped.'">','</a>').'
 8102:     </p>
 8103: ');
 8104:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8105:     return '';
 8106: }
 8107: 
 8108: sub checkscantron_results {
 8109:     my ($r) = @_;
 8110:     my ($symb)=&get_symb($r);
 8111:     if (!$symb) {return '';}
 8112:     my $grading_menu_button=&show_grading_menu_form($symb);
 8113:     my $cid = $env{'request.course.id'};
 8114:     my %lettdig = &letter_to_digits();
 8115:     my $numletts = scalar(keys(%lettdig));
 8116:     my $cnum = $env{'course.'.$cid.'.num'};
 8117:     my $cdom = $env{'course.'.$cid.'.domain'};
 8118:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8119:     my %record;
 8120:     my %scantron_config =
 8121:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8122:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8123:     my $classlist=&Apache::loncoursedata::get_classlist();
 8124:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8125:     my $navmap=Apache::lonnavmaps::navmap->new();
 8126:     unless (ref($navmap)) {
 8127:         $r->print(&navmap_errormsg());
 8128:         return '';
 8129:     }
 8130:     my $map=$navmap->getResourceByUrl($sequence);
 8131:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8132:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8133:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8134: 
 8135:     my ($uname,$udom);
 8136:     my (%scandata,%lastname,%bylast);
 8137:     $r->print('
 8138: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8139: 
 8140:     my @delayqueue;
 8141:     my %completedstudents;
 8142: 
 8143:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8144:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8145:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8146:                                     'inline',undef,'checkscantron');
 8147:     my ($username,$domain,$started);
 8148:     my $nav_error;
 8149:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8150:     if ($nav_error) {
 8151:         $r->print(&navmap_errormsg());
 8152:         return '';
 8153:     }
 8154: 
 8155:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8156:                                           'Processing first student');
 8157:     my $start=&Time::HiRes::time();
 8158:     my $i=-1;
 8159: 
 8160:     while ($i<$scanlines->{'count'}) {
 8161:         ($username,$domain,$uname)=('','','');
 8162:         $i++;
 8163:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8164:         if ($line=~/^[\s\cz]*$/) { next; }
 8165:         if ($started) {
 8166:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8167:                                                      'last student');
 8168:         }
 8169:         $started=1;
 8170:         my $scan_record=
 8171:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8172:                                                      $scan_data);
 8173:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8174:                                                               \%idmap,$i)) {
 8175:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8176:                                 'Unable to find a student that matches',1);
 8177:             next;
 8178:         }
 8179:         if (exists $completedstudents{$uname}) {
 8180:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8181:                                 'Student '.$uname.' has multiple sheets',2);
 8182:             next;
 8183:         }
 8184:         my $pid = $scan_record->{'scantron.ID'};
 8185:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8186:         push(@{$bylast{$lastname{$pid}}},$pid);
 8187:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8188:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8189:         chomp($scandata{$pid});
 8190:         $scandata{$pid} =~ s/\r$//;
 8191:         ($username,$domain)=split(/:/,$uname);
 8192:         my $counter = -1;
 8193:         foreach my $resource (@resources) {
 8194:             my $parts;
 8195:             my $ressymb = $resource->symb();
 8196:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8197:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8198:                 (my $analysis,$parts) =
 8199:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8200:             } else {
 8201:                 $parts = $grader_partids_by_symb{$ressymb};
 8202:             }
 8203:             ($counter,my $recording) =
 8204:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8205:                                          $scandata{$pid},$parts,
 8206:                                          \%scantron_config,\%lettdig,$numletts);
 8207:             $record{$pid} .= $recording;
 8208:         }
 8209:     }
 8210:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8211:     $r->print('<br />');
 8212:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8213:     $passed = 0;
 8214:     $failed = 0;
 8215:     $numstudents = 0;
 8216:     foreach my $last (sort(keys(%bylast))) {
 8217:         if (ref($bylast{$last}) eq 'ARRAY') {
 8218:             foreach my $pid (sort(@{$bylast{$last}})) {
 8219:                 my $showscandata = $scandata{$pid};
 8220:                 my $showrecord = $record{$pid};
 8221:                 $showscandata =~ s/\s/&nbsp;/g;
 8222:                 $showrecord =~ s/\s/&nbsp;/g;
 8223:                 if ($scandata{$pid} eq $record{$pid}) {
 8224:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8225:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8226: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8227: '</tr>'."\n".
 8228: '<tr class="'.$css_class.'">'."\n".
 8229: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8230:                     $passed ++;
 8231:                 } else {
 8232:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8233:                     $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".
 8234: '</tr>'."\n".
 8235: '<tr class="'.$css_class.'">'."\n".
 8236: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8237: '</tr>'."\n";
 8238:                     $failed ++;
 8239:                 }
 8240:                 $numstudents ++;
 8241:             }
 8242:         }
 8243:     }
 8244:     $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>');
 8245:     $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>');
 8246:     if ($passed) {
 8247:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8248:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8249:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8250:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8251:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8252:                  $okstudents."\n".
 8253:                  &Apache::loncommon::end_data_table().'<br />');
 8254:     }
 8255:     if ($failed) {
 8256:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8257:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8258:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8259:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8260:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8261:                  $badstudents."\n".
 8262:                  &Apache::loncommon::end_data_table()).'<br />'.
 8263:                  &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.');  
 8264:     }
 8265:     $r->print('</form><br />'.$grading_menu_button);
 8266:     return;
 8267: }
 8268: 
 8269: sub verify_scantron_grading {
 8270:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8271:         $scantron_config,$lettdig,$numletts) = @_;
 8272:     my ($record,%expected,%startpos);
 8273:     return ($counter,$record) if (!ref($resource));
 8274:     return ($counter,$record) if (!$resource->is_problem());
 8275:     my $symb = $resource->symb();
 8276:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8277:     foreach my $part_id (@{$partids}) {
 8278:         $counter ++;
 8279:         $expected{$part_id} = 0;
 8280:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8281:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8282:             foreach my $item (@sub_lines) {
 8283:                 $expected{$part_id} += $item;
 8284:             }
 8285:         } else {
 8286:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8287:         }
 8288:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8289:     }
 8290:     if ($symb) {
 8291:         my %recorded;
 8292:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8293:         if ($returnhash{'version'}) {
 8294:             my %lasthash=();
 8295:             my $version;
 8296:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8297:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8298:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8299:                 }
 8300:             }
 8301:             foreach my $key (keys(%lasthash)) {
 8302:                 if ($key =~ /\.scantron$/) {
 8303:                     my $value = &unescape($lasthash{$key});
 8304:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8305:                     if ($value eq '') {
 8306:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8307:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8308:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8309:                             }
 8310:                         }
 8311:                     } else {
 8312:                         my @tocheck;
 8313:                         my @items = split(//,$value);
 8314:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8315:                             ($scantron_config->{'Qon'} eq 'number')) {
 8316:                             if (@items < $expected{$part_id}) {
 8317:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8318:                                 my @singles = split(//,$fragment);
 8319:                                 foreach my $pos (@singles) {
 8320:                                     if ($pos eq ' ') {
 8321:                                         push(@tocheck,$pos);
 8322:                                     } else {
 8323:                                         my $next = shift(@items);
 8324:                                         push(@tocheck,$next);
 8325:                                     }
 8326:                                 }
 8327:                             } else {
 8328:                                 @tocheck = @items;
 8329:                             }
 8330:                             foreach my $letter (@tocheck) {
 8331:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8332:                                     if ($letter !~ /^[A-J]$/) {
 8333:                                         $letter = $scantron_config->{'Qoff'};
 8334:                                     }
 8335:                                     $recorded{$part_id} .= $letter;
 8336:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8337:                                     my $digit;
 8338:                                     if ($letter !~ /^[A-J]$/) {
 8339:                                         $digit = $scantron_config->{'Qoff'};
 8340:                                     } else {
 8341:                                         $digit = $lettdig->{$letter};
 8342:                                     }
 8343:                                     $recorded{$part_id} .= $digit;
 8344:                                 }
 8345:                             }
 8346:                         } else {
 8347:                             @tocheck = @items;
 8348:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8349:                                 my $curr_sub = shift(@tocheck);
 8350:                                 my $digit;
 8351:                                 if ($curr_sub =~ /^[A-J]$/) {
 8352:                                     $digit = $lettdig->{$curr_sub}-1;
 8353:                                 }
 8354:                                 if ($curr_sub eq 'J') {
 8355:                                     $digit += scalar($numletts);
 8356:                                 }
 8357:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8358:                                     if ($j == $digit) {
 8359:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8360:                                     } else {
 8361:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8362:                                     }
 8363:                                 }
 8364:                             }
 8365:                         }
 8366:                     }
 8367:                 }
 8368:             }
 8369:         }
 8370:         foreach my $part_id (@{$partids}) {
 8371:             if ($recorded{$part_id} eq '') {
 8372:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8373:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8374:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8375:                     }
 8376:                 }
 8377:             }
 8378:             $record .= $recorded{$part_id};
 8379:         }
 8380:     }
 8381:     return ($counter,$record);
 8382: }
 8383: 
 8384: sub letter_to_digits { 
 8385:     my %lettdig = (
 8386:                     A => 1,
 8387:                     B => 2,
 8388:                     C => 3,
 8389:                     D => 4,
 8390:                     E => 5,
 8391:                     F => 6,
 8392:                     G => 7,
 8393:                     H => 8,
 8394:                     I => 9,
 8395:                     J => 0,
 8396:                   );
 8397:     return %lettdig;
 8398: }
 8399: 
 8400: 
 8401: #-------- end of section for handling grading scantron forms -------
 8402: #
 8403: #-------------------------------------------------------------------
 8404: 
 8405: #-------------------------- Menu interface -------------------------
 8406: #
 8407: #--- Show a Grading Menu button - Calls the next routine ---
 8408: sub show_grading_menu_form {
 8409:     my ($symb)=@_;
 8410:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8411: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8412: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8413: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8414: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8415: 	'</form>'."\n";
 8416:     return $result;
 8417: }
 8418: 
 8419: # -- Retrieve choices for grading form
 8420: sub savedState {
 8421:     my %savedState = ();
 8422:     if ($env{'form.saveState'}) {
 8423: 	foreach (split(/:/,$env{'form.saveState'})) {
 8424: 	    my ($key,$value) = split(/=/,$_,2);
 8425: 	    $savedState{$key} = $value;
 8426: 	}
 8427:     }
 8428:     return \%savedState;
 8429: }
 8430: 
 8431: sub grading_menu {
 8432:     my ($request) = @_;
 8433:     my ($symb)=&get_symb($request);
 8434:     if (!$symb) {return '';}
 8435:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8436:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8437: 
 8438:     $request->print($table);
 8439:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8440:                   'handgrade'=>$hdgrade,
 8441:                   'probTitle'=>$probTitle,
 8442:                   'command'=>'submit_options',
 8443:                   'saveState'=>"",
 8444:                   'gradingMenu'=>1,
 8445:                   'showgrading'=>"yes");
 8446:     
 8447:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8448:     
 8449:     $fields{'command'} = 'csvform';
 8450:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8451:     
 8452:     $fields{'command'} = 'processclicker';
 8453:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8454:     
 8455:     $fields{'command'} = 'scantron_selectphase';
 8456:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8457:     
 8458:     my @menu = ({	categorytitle=>'Course Grading',
 8459:             items =>[
 8460:                         {	linktext => 'Manual Grading/View Submissions',
 8461:                     		url => $url1,
 8462:                     		permission => 'F',
 8463:                     		icon => 'edit-find-replace.png',
 8464:                     		linktitle => 'Start the process of hand grading submissions.'
 8465:                         },
 8466:                 	    {	linktext => 'Upload Scores',
 8467:                     		url => $url2,
 8468:                     		permission => 'F',
 8469:                     		icon => 'uploadscores.png',
 8470:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8471:                 	    },
 8472:                 	    {	linktext => 'Process Clicker',
 8473:                     		url => $url3,
 8474:                     		permission => 'F',
 8475:                     		icon => 'addClickerInfoFile.png',
 8476:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8477:                 	    },
 8478:                 	    {	linktext => 'Grade/Manage/Review Bubblesheet Forms',
 8479:                     		url => $url4,
 8480:                     		permission => 'F',
 8481:                     		icon => 'stat.png',
 8482:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8483:                 	    }
 8484:                     ]
 8485:             });
 8486: 
 8487:     #$fields{'command'} = 'verify';
 8488:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8489:     #
 8490:     # Create the menu
 8491:     my $Str;
 8492:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8493:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8494:     $Str .= '<input type="hidden" name="command" value="" />'.
 8495:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8496: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8497: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8498: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8499: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8500: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8501: 
 8502:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8503:     #$menudata->{'jscript'}
 8504:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8505:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8506:         ' /> '.
 8507:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8508:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8509: 
 8510:     $Str .="</form>\n";
 8511:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8512:     $request->print(<<GRADINGMENUJS);
 8513: <script type="text/javascript" language="javascript">
 8514:     function checkChoice(formname,val,cmdx) {
 8515: 	if (val <= 2) {
 8516: 	    var cmd = radioSelection(formname.radioChoice);
 8517: 	    var cmdsave = cmd;
 8518: 	} else {
 8519: 	    cmd = cmdx;
 8520: 	    cmdsave = 'submission';
 8521: 	}
 8522: 	formname.command.value = cmd;
 8523: 	if (val < 5) formname.submit();
 8524: 	if (val == 5) {
 8525: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8526: 	        return false;
 8527: 	    } else {
 8528: 	        formname.submit();
 8529: 	    }
 8530: 	}
 8531:     }
 8532: 
 8533:     function checkReceiptNo(formname,nospace) {
 8534: 	var receiptNo = formname.receipt.value;
 8535: 	var checkOpt = false;
 8536: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8537: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8538: 	if (checkOpt) {
 8539: 	    alert("$receiptalert");
 8540: 	    formname.receipt.value = "";
 8541: 	    formname.receipt.focus();
 8542: 	    return false;
 8543: 	}
 8544: 	return true;
 8545:     }
 8546: </script>
 8547: GRADINGMENUJS
 8548:     &commonJSfunctions($request);
 8549:     return $Str;    
 8550: }
 8551: 
 8552: 
 8553: #--- Displays the submissions first page -------
 8554: sub submit_options {
 8555:     my ($request) = @_;
 8556:     my ($symb)=&get_symb($request);
 8557:     if (!$symb) {return '';}
 8558:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8559: 
 8560:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8561:     $request->print(<<GRADINGMENUJS);
 8562: <script type="text/javascript" language="javascript">
 8563:     function checkChoice(formname,val,cmdx) {
 8564: 	if (val <= 2) {
 8565: 	    var cmd = radioSelection(formname.radioChoice);
 8566: 	    var cmdsave = cmd;
 8567: 	} else {
 8568: 	    cmd = cmdx;
 8569: 	    cmdsave = 'submission';
 8570: 	}
 8571: 	formname.command.value = cmd;
 8572: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8573: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8574: 	if (val < 5) formname.submit();
 8575: 	if (val == 5) {
 8576: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8577: 	    formname.submit();
 8578: 	}
 8579: 	if (val < 7) formname.submit();
 8580:     }
 8581: 
 8582:     function checkReceiptNo(formname,nospace) {
 8583: 	var receiptNo = formname.receipt.value;
 8584: 	var checkOpt = false;
 8585: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8586: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8587: 	if (checkOpt) {
 8588: 	    alert("$receiptalert");
 8589: 	    formname.receipt.value = "";
 8590: 	    formname.receipt.focus();
 8591: 	    return false;
 8592: 	}
 8593: 	return true;
 8594:     }
 8595: </script>
 8596: GRADINGMENUJS
 8597:     &commonJSfunctions($request);
 8598:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8599:     my $result;
 8600:     my (undef,$sections) = &getclasslist('all','0');
 8601:     my $savedState = &savedState();
 8602:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8603:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8604:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8605:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8606: 
 8607:     # Preselect sections
 8608:     my $selsec="";
 8609:     if (ref($sections)) {
 8610:         foreach my $section (sort(@$sections)) {
 8611:             $selsec.='<option value="'.$section.'" '.
 8612:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8613:         }
 8614:     }
 8615: 
 8616:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8617: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8618: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8619: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8620: 	'<input type="hidden" name="command"     value="" />'."\n".
 8621: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8622: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8623: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8624: 
 8625:     $result.='
 8626: <h2>
 8627:   '.&mt('Grade Current Resource').'
 8628: </h2>
 8629: <div>
 8630:   '.$table.'
 8631: </div>
 8632: 
 8633: <div class="LC_columnSection">
 8634:   
 8635:     <fieldset>
 8636:       <legend>
 8637:        '.&mt('Sections').'
 8638:       </legend>
 8639:       <select name="section" multiple="multiple" size="5">'."\n";
 8640:     $result.= $selsec;
 8641:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8642:     $result.='
 8643:     </fieldset>
 8644:   
 8645:     <fieldset>
 8646:       <legend>
 8647:         '.&mt('Groups').'
 8648:       </legend>
 8649:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8650:     </fieldset>
 8651:   
 8652:     <fieldset>
 8653:       <legend>
 8654:         '.&mt('Access Status').'
 8655:       </legend>
 8656:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8657:     </fieldset>
 8658:   
 8659:     <fieldset>
 8660:       <legend>
 8661:         '.&mt('Submission Status').'
 8662:       </legend>
 8663:       <select name="submitonly" size="5">
 8664: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8665: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8666: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8667: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8668:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8669:       </select>
 8670:     </fieldset>
 8671:   
 8672: </div>
 8673: 
 8674: <br />
 8675:           <div>
 8676:             <div>
 8677:               <label>
 8678:                 <input type="radio" name="radioChoice" value="submission" '.
 8679:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8680:              &mt('Select individual students to grade and view submissions.').'
 8681: 	      </label> 
 8682:             </div>
 8683:             <div>
 8684: 	      <label>
 8685:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8686:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8687:                     &mt('Grade all selected students in a grading table.').'
 8688:               </label>
 8689:             </div>
 8690:             <div>
 8691: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8692:             </div>
 8693:           </div>
 8694: 
 8695: 
 8696:         <h2>
 8697:          '.&mt('Grade Complete Folder for One Student').'
 8698:         </h2>
 8699:         <div>
 8700:             <div>
 8701:               <label>
 8702:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8703: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8704:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8705:               </label>
 8706:             </div>
 8707:             <div>
 8708: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8709:             </div>
 8710:         </div>
 8711:   </form>';
 8712:     $result .= &show_grading_menu_form($symb);
 8713:     return $result;
 8714: }
 8715: 
 8716: sub reset_perm {
 8717:     undef(%perm);
 8718: }
 8719: 
 8720: sub init_perm {
 8721:     &reset_perm();
 8722:     foreach my $test_perm ('vgr','mgr','opa') {
 8723: 
 8724: 	my $scope = $env{'request.course.id'};
 8725: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8726: 
 8727: 	    $scope .= '/'.$env{'request.course.sec'};
 8728: 	    if ( $perm{$test_perm}=
 8729: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8730: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8731: 	    } else {
 8732: 		delete($perm{$test_perm});
 8733: 	    }
 8734: 	}
 8735:     }
 8736: }
 8737: 
 8738: sub gather_clicker_ids {
 8739:     my %clicker_ids;
 8740: 
 8741:     my $classlist = &Apache::loncoursedata::get_classlist();
 8742: 
 8743:     # Set up a couple variables.
 8744:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8745:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8746:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8747: 
 8748:     foreach my $student (keys(%$classlist)) {
 8749:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8750:         my $username = $classlist->{$student}->[$username_idx];
 8751:         my $domain   = $classlist->{$student}->[$domain_idx];
 8752:         my $clickers =
 8753: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8754:         foreach my $id (split(/\,/,$clickers)) {
 8755:             $id=~s/^[\#0]+//;
 8756:             $id=~s/[\-\:]//g;
 8757:             if (exists($clicker_ids{$id})) {
 8758: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8759:             } else {
 8760: 		$clicker_ids{$id}=$username.':'.$domain;
 8761:             }
 8762:         }
 8763:     }
 8764:     return %clicker_ids;
 8765: }
 8766: 
 8767: sub gather_adv_clicker_ids {
 8768:     my %clicker_ids;
 8769:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8770:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8771:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8772:     foreach my $element (sort(keys(%coursepersonnel))) {
 8773:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8774:             my ($puname,$pudom)=split(/\:/,$person);
 8775:             my $clickers =
 8776: 		(&Apache::lonnet::userenvironment($pudom,$puname,'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}.=','.$puname.':'.$pudom;
 8782: 		} else {
 8783: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8784: 		}
 8785:             }
 8786:         }
 8787:     }
 8788:     return %clicker_ids;
 8789: }
 8790: 
 8791: sub clicker_grading_parameters {
 8792:     return ('gradingmechanism' => 'scalar',
 8793:             'upfiletype' => 'scalar',
 8794:             'specificid' => 'scalar',
 8795:             'pcorrect' => 'scalar',
 8796:             'pincorrect' => 'scalar');
 8797: }
 8798: 
 8799: sub process_clicker {
 8800:     my ($r)=@_;
 8801:     my ($symb)=&get_symb($r);
 8802:     if (!$symb) {return '';}
 8803:     my $result=&checkforfile_js();
 8804:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8805:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8806:     $result.=$table;
 8807:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8808:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8809:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8810:         '</b></td></tr>'."\n";
 8811:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8812: # Attempt to restore parameters from last session, set defaults if not present
 8813:     my %Saveable_Parameters=&clicker_grading_parameters();
 8814:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8815:                                                  \%Saveable_Parameters);
 8816:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8817:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8818:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8819:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8820: 
 8821:     my %checked;
 8822:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8823:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8824:           $checked{$gradingmechanism}=' checked="checked"';
 8825:        }
 8826:     }
 8827: 
 8828:     my $upload=&mt("Upload File");
 8829:     my $type=&mt("Type");
 8830:     my $attendance=&mt("Award points just for participation");
 8831:     my $personnel=&mt("Correctness determined from response by course personnel");
 8832:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8833:     my $given=&mt("Correctness determined from given list of answers").' '.
 8834:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8835:     my $pcorrect=&mt("Percentage points for correct solution");
 8836:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8837:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8838: 						   ('iclicker' => 'i>clicker',
 8839:                                                     'interwrite' => 'interwrite PRS'));
 8840:     $symb = &Apache::lonenc::check_encrypt($symb);
 8841:     $result.=<<ENDUPFORM;
 8842: <script type="text/javascript">
 8843: function sanitycheck() {
 8844: // Accept only integer percentages
 8845:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8846:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8847: // Find out grading choice
 8848:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8849:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8850:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8851:       }
 8852:    }
 8853: // By default, new choice equals user selection
 8854:    newgradingchoice=gradingchoice;
 8855: // Not good to give more points for false answers than correct ones
 8856:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8857:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8858:    }
 8859: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8860:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8861:       document.forms.gradesupload.pcorrect.value=100;
 8862:       document.forms.gradesupload.pincorrect.value=100;
 8863:    }
 8864: // If the values are different, cannot be attendance only
 8865:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8866:        (gradingchoice=='attendance')) {
 8867:        newgradingchoice='personnel';
 8868:    }
 8869: // Change grading choice to new one
 8870:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8871:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8872:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8873:       } else {
 8874:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8875:       }
 8876:    }
 8877: // Remember the old state
 8878:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8879: }
 8880: </script>
 8881: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8882: <input type="hidden" name="symb" value="$symb" />
 8883: <input type="hidden" name="command" value="processclickerfile" />
 8884: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8885: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8886: <input type="file" name="upfile" size="50" />
 8887: <br /><label>$type: $selectform</label>
 8888: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8889: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8890: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8891: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8892: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8893: <br />&nbsp;&nbsp;&nbsp;
 8894: <input type="text" name="givenanswer" size="50" />
 8895: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8896: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8897: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8898: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8899: </form>
 8900: ENDUPFORM
 8901:     $result.='</td></tr></table>'."\n".
 8902:              '</td></tr></table><br /><br />'."\n";
 8903:     $result.=&show_grading_menu_form($symb);
 8904:     return $result;
 8905: }
 8906: 
 8907: sub process_clicker_file {
 8908:     my ($r)=@_;
 8909:     my ($symb)=&get_symb($r);
 8910:     if (!$symb) {return '';}
 8911: 
 8912:     my %Saveable_Parameters=&clicker_grading_parameters();
 8913:     &Apache::loncommon::store_course_settings('grades_clicker',
 8914:                                               \%Saveable_Parameters);
 8915: 
 8916:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8917:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8918: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8919: 	return $result.&show_grading_menu_form($symb);
 8920:     }
 8921:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8922:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8923:         return $result.&show_grading_menu_form($symb);
 8924:     }
 8925:     my $foundgiven=0;
 8926:     if ($env{'form.gradingmechanism'} eq 'given') {
 8927:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8928:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8929:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8930:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8931:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8932:         $foundgiven=$#answers+1;
 8933:     }
 8934:     my %clicker_ids=&gather_clicker_ids();
 8935:     my %correct_ids;
 8936:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8937: 	%correct_ids=&gather_adv_clicker_ids();
 8938:     }
 8939:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8940: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8941: 	   $correct_id=~tr/a-z/A-Z/;
 8942: 	   $correct_id=~s/\s//gs;
 8943: 	   $correct_id=~s/^[\#0]+//;
 8944:            $correct_id=~s/[\-\:]//g;
 8945:            if ($correct_id) {
 8946: 	      $correct_ids{$correct_id}='specified';
 8947:            }
 8948:         }
 8949:     }
 8950:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8951: 	$result.=&mt('Score based on attendance only');
 8952:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8953:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8954:     } else {
 8955: 	my $number=0;
 8956: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8957: 	foreach my $id (sort(keys(%correct_ids))) {
 8958: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8959: 	    if ($correct_ids{$id} eq 'specified') {
 8960: 		$result.=&mt('specified');
 8961: 	    } else {
 8962: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8963: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8964: 	    }
 8965: 	    $number++;
 8966: 	}
 8967:         $result.="</p>\n";
 8968: 	if ($number==0) {
 8969: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8970: 	    return $result.&show_grading_menu_form($symb);
 8971: 	}
 8972:     }
 8973:     if (length($env{'form.upfile'}) < 2) {
 8974:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8975: 		     '<span class="LC_error">',
 8976: 		     '</span>',
 8977: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8978:         return $result.&show_grading_menu_form($symb);
 8979:     }
 8980: 
 8981: # Were able to get all the info needed, now analyze the file
 8982: 
 8983:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8984:     $symb = &Apache::lonenc::check_encrypt($symb);
 8985:     my $heading=&mt('Scanning clicker file');
 8986:     $result.=(<<ENDHEADER);
 8987: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8988: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8989: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8990: <form method="post" action="/adm/grades" name="clickeranalysis">
 8991: <input type="hidden" name="symb" value="$symb" />
 8992: <input type="hidden" name="command" value="assignclickergrades" />
 8993: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8994: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8995: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8996: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8997: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8998: ENDHEADER
 8999:     if ($env{'form.gradingmechanism'} eq 'given') {
 9000:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9001:     } 
 9002:     my %responses;
 9003:     my @questiontitles;
 9004:     my $errormsg='';
 9005:     my $number=0;
 9006:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9007: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9008:     }
 9009:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9010:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9011:     }
 9012:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9013:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9014:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9015:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9016:              '<br />';
 9017:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9018:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9019:        return $result.&show_grading_menu_form($symb);
 9020:     } 
 9021: # Remember Question Titles
 9022: # FIXME: Possibly need delimiter other than ":"
 9023:     for (my $i=0;$i<$number;$i++) {
 9024:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9025:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9026:     }
 9027:     my $correct_count=0;
 9028:     my $student_count=0;
 9029:     my $unknown_count=0;
 9030: # Match answers with usernames
 9031: # FIXME: Possibly need delimiter other than ":"
 9032:     foreach my $id (keys(%responses)) {
 9033:        if ($correct_ids{$id}) {
 9034:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9035:           $correct_count++;
 9036:        } elsif ($clicker_ids{$id}) {
 9037:           if ($clicker_ids{$id}=~/\,/) {
 9038: # More than one user with the same clicker!
 9039:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9040:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9041:                            "<select name='multi".$id."'>";
 9042:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9043:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9044:              }
 9045:              $result.='</select>';
 9046:              $unknown_count++;
 9047:           } else {
 9048: # Good: found one and only one user with the right clicker
 9049:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9050:              $student_count++;
 9051:           }
 9052:        } else {
 9053:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9054:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9055:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9056:                    "\n".&mt("Domain").": ".
 9057:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9058:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9059:           $unknown_count++;
 9060:        }
 9061:     }
 9062:     $result.='<hr />'.
 9063:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9064:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9065:        if ($correct_count==0) {
 9066:           $errormsg.="Found no correct answers answers for grading!";
 9067:        } elsif ($correct_count>1) {
 9068:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9069:        }
 9070:     }
 9071:     if ($number<1) {
 9072:        $errormsg.="Found no questions.";
 9073:     }
 9074:     if ($errormsg) {
 9075:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9076:     } else {
 9077:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9078:     }
 9079:     $result.='</form></td></tr></table>'."\n".
 9080:              '</td></tr></table><br /><br />'."\n";
 9081:     return $result.&show_grading_menu_form($symb);
 9082: }
 9083: 
 9084: sub iclicker_eval {
 9085:     my ($questiontitles,$responses)=@_;
 9086:     my $number=0;
 9087:     my $errormsg='';
 9088:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9089:         my %components=&Apache::loncommon::record_sep($line);
 9090:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9091: 	if ($entries[0] eq 'Question') {
 9092: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9093: 		$$questiontitles[$number]=$entries[$i];
 9094: 		$number++;
 9095: 	    }
 9096: 	}
 9097: 	if ($entries[0]=~/^\#/) {
 9098: 	    my $id=$entries[0];
 9099: 	    my @idresponses;
 9100: 	    $id=~s/^[\#0]+//;
 9101: 	    for (my $i=0;$i<$number;$i++) {
 9102: 		my $idx=3+$i*6;
 9103: 		push(@idresponses,$entries[$idx]);
 9104: 	    }
 9105: 	    $$responses{$id}=join(',',@idresponses);
 9106: 	}
 9107:     }
 9108:     return ($errormsg,$number);
 9109: }
 9110: 
 9111: sub interwrite_eval {
 9112:     my ($questiontitles,$responses)=@_;
 9113:     my $number=0;
 9114:     my $errormsg='';
 9115:     my $skipline=1;
 9116:     my $questionnumber=0;
 9117:     my %idresponses=();
 9118:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9119:         my %components=&Apache::loncommon::record_sep($line);
 9120:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9121:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9122:         if ($entries[1] eq 'Response') { $skipline=1; }
 9123:         next if $skipline;
 9124:         if ($entries[0]!=$questionnumber) {
 9125:            $questionnumber=$entries[0];
 9126:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9127:            $number++;
 9128:         }
 9129:         my $id=$entries[4];
 9130:         $id=~s/^[\#0]+//;
 9131:         $id=~s/^v\d*\://i;
 9132:         $id=~s/[\-\:]//g;
 9133:         $idresponses{$id}[$number]=$entries[6];
 9134:     }
 9135:     foreach my $id (keys(%idresponses)) {
 9136:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9137:        $$responses{$id}=~s/^\s*\,//;
 9138:     }
 9139:     return ($errormsg,$number);
 9140: }
 9141: 
 9142: sub assign_clicker_grades {
 9143:     my ($r)=@_;
 9144:     my ($symb)=&get_symb($r);
 9145:     if (!$symb) {return '';}
 9146: # See which part we are saving to
 9147:     my $res_error;
 9148:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9149:     if ($res_error) {
 9150:         return &navmap_errormsg();
 9151:     }
 9152: # FIXME: This should probably look for the first handgradeable part
 9153:     my $part=$$partlist[0];
 9154: # Start screen output
 9155:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9156: 
 9157:     my $heading=&mt('Assigning grades based on clicker file');
 9158:     $result.=(<<ENDHEADER);
 9159: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9160: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9161: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9162: ENDHEADER
 9163: # Get correct result
 9164: # FIXME: Possibly need delimiter other than ":"
 9165:     my @correct=();
 9166:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9167:     my $number=$env{'form.number'};
 9168:     if ($gradingmechanism ne 'attendance') {
 9169:        foreach my $key (keys(%env)) {
 9170:           if ($key=~/^form\.correct\:/) {
 9171:              my @input=split(/\,/,$env{$key});
 9172:              for (my $i=0;$i<=$#input;$i++) {
 9173:                  if (($correct[$i]) && ($input[$i]) &&
 9174:                      ($correct[$i] ne $input[$i])) {
 9175:                     $result.='<br /><span class="LC_warning">'.
 9176:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9177:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9178:                  } elsif ($input[$i]) {
 9179:                     $correct[$i]=$input[$i];
 9180:                  }
 9181:              }
 9182:           }
 9183:        }
 9184:        for (my $i=0;$i<$number;$i++) {
 9185:           if (!$correct[$i]) {
 9186:              $result.='<br /><span class="LC_error">'.
 9187:                       &mt('No correct result given for question "[_1]"!',
 9188:                           $env{'form.question:'.$i}).'</span>';
 9189:           }
 9190:        }
 9191:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9192:     }
 9193: # Start grading
 9194:     my $pcorrect=$env{'form.pcorrect'};
 9195:     my $pincorrect=$env{'form.pincorrect'};
 9196:     my $storecount=0;
 9197:     foreach my $key (keys(%env)) {
 9198:        my $user='';
 9199:        if ($key=~/^form\.student\:(.*)$/) {
 9200:           $user=$1;
 9201:        }
 9202:        if ($key=~/^form\.unknown\:(.*)$/) {
 9203:           my $id=$1;
 9204:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9205:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9206:           } elsif ($env{'form.multi'.$id}) {
 9207:              $user=$env{'form.multi'.$id};
 9208:           }
 9209:        }
 9210:        if ($user) { 
 9211:           my @answer=split(/\,/,$env{$key});
 9212:           my $sum=0;
 9213:           my $realnumber=$number;
 9214:           for (my $i=0;$i<$number;$i++) {
 9215:              if  ($correct[$i] eq '-') {
 9216:                 $realnumber--;
 9217:              } elsif ($answer[$i]) {
 9218:                 if ($gradingmechanism eq 'attendance') {
 9219:                    $sum+=$pcorrect;
 9220:                 } elsif ($correct[$i] eq '*') {
 9221:                    $sum+=$pcorrect;
 9222:                 } else {
 9223:                    if ($answer[$i] eq $correct[$i]) {
 9224:                       $sum+=$pcorrect;
 9225:                    } else {
 9226:                       $sum+=$pincorrect;
 9227:                    }
 9228:                 }
 9229:              }
 9230:           }
 9231:           my $ave=$sum/(100*$realnumber);
 9232: # Store
 9233:           my ($username,$domain)=split(/\:/,$user);
 9234:           my %grades=();
 9235:           $grades{"resource.$part.solved"}='correct_by_override';
 9236:           $grades{"resource.$part.awarded"}=$ave;
 9237:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9238:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9239:                                                  $env{'request.course.id'},
 9240:                                                  $domain,$username);
 9241:           if ($returncode ne 'ok') {
 9242:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9243:           } else {
 9244:              $storecount++;
 9245:           }
 9246:        }
 9247:     }
 9248: # We are done
 9249:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9250:              '</td></tr></table>'."\n".
 9251:              '</td></tr></table><br /><br />'."\n";
 9252:     return $result.&show_grading_menu_form($symb);
 9253: }
 9254: 
 9255: sub navmap_errormsg {
 9256:     return '<div class="LC_error">'.
 9257:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9258:            &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>').
 9259:            '</div>';
 9260: }
 9261: 
 9262: sub handler {
 9263:     my $request=$_[0];
 9264:     &reset_caches();
 9265:     if ($env{'browser.mathml'}) {
 9266: 	&Apache::loncommon::content_type($request,'text/xml');
 9267:     } else {
 9268: 	&Apache::loncommon::content_type($request,'text/html');
 9269:     }
 9270:     $request->send_http_header;
 9271:     return '' if $request->header_only;
 9272:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9273:     my $symb=&get_symb($request,1);
 9274:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9275:     my $command=$commands[0];
 9276: 
 9277:     if ($#commands > 0) {
 9278: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9279:     }
 9280: 
 9281:     $ssi_error = 0;
 9282:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9283:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9284:                                           {'bread_crumbs' => $brcrum}));
 9285:     if ($symb eq '' && $command eq '') {
 9286: 	if ($env{'user.adv'}) {
 9287: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9288: 		($env{'form.codethree'})) {
 9289: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9290: 		    $env{'form.codethree'};
 9291: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9292: 		    &Apache::lonnet::checkin($token);
 9293: 		if ($tsymb) {
 9294: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9295: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9296: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9297: 					  ('grade_username' => $tuname,
 9298: 					   'grade_domain' => $tudom,
 9299: 					   'grade_courseid' => $tcrsid,
 9300: 					   'grade_symb' => $tsymb)));
 9301: 		    } else {
 9302: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9303: 		    }
 9304: 		} else {
 9305: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9306: 		}
 9307: 	    } else {
 9308: 		$request->print(&Apache::lonxml::tokeninputfield());
 9309: 	    }
 9310: 	}
 9311:     } else {
 9312: 	&init_perm();
 9313: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9314: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9315: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9316: 	    &pickStudentPage($request);
 9317: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9318: 	    &displayPage($request);
 9319: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9320: 	    &updateGradeByPage($request);
 9321: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9322: 	    &processGroup($request);
 9323: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9324: 	    $request->print(&grading_menu($request));
 9325: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9326: 	    $request->print(&submit_options($request));
 9327: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9328: 	    $request->print(&viewgrades($request));
 9329: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9330: 	    $request->print(&processHandGrade($request));
 9331: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9332: 	    $request->print(&editgrades($request));
 9333: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9334: 	    $request->print(&verifyreceipt($request));
 9335:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9336:             $request->print(&process_clicker($request));
 9337:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9338:             $request->print(&process_clicker_file($request));
 9339:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9340:             $request->print(&assign_clicker_grades($request));
 9341: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9342: 	    $request->print(&upcsvScores_form($request));
 9343: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9344: 	    $request->print(&csvupload($request));
 9345: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9346: 	    $request->print(&csvuploadmap($request));
 9347: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9348: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9349: 		$request->print(&csvuploadoptions($request));
 9350: 	    } else {
 9351: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9352: 		    $env{'form.upfile_associate'} = 'reverse';
 9353: 		} else {
 9354: 		    $env{'form.upfile_associate'} = 'forward';
 9355: 		}
 9356: 		$request->print(&csvuploadmap($request));
 9357: 	    }
 9358: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9359: 	    $request->print(&csvuploadassign($request));
 9360: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9361: 	    $request->print(&scantron_selectphase($request));
 9362:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9363:  	    $request->print(&scantron_do_warning($request));
 9364: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9365: 	    $request->print(&scantron_validate_file($request));
 9366: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9367: 	    $request->print(&scantron_process_students($request));
 9368:  	} elsif ($command eq 'scantronupload' && 
 9369:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9370: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9371:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9372:  	} elsif ($command eq 'scantronupload_save' &&
 9373:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9374: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9375:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9376:  	} elsif ($command eq 'scantron_download' &&
 9377: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9378:  	    $request->print(&scantron_download_scantron_data($request));
 9379:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9380:             $request->print(&checkscantron_results($request));     
 9381: 	} elsif ($command) {
 9382: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9383: 	}
 9384:     }
 9385:     if ($ssi_error) {
 9386: 	&ssi_print_error($request);
 9387:     }
 9388:     $request->print(&Apache::loncommon::end_page());
 9389:     &reset_caches();
 9390:     return '';
 9391: }
 9392: 
 9393: 1;
 9394: 
 9395: __END__;
 9396: 
 9397: 
 9398: =head1 NAME
 9399: 
 9400: Apache::grades
 9401: 
 9402: =head1 SYNOPSIS
 9403: 
 9404: Handles the viewing of grades.
 9405: 
 9406: This is part of the LearningOnline Network with CAPA project
 9407: described at http://www.lon-capa.org.
 9408: 
 9409: =head1 OVERVIEW
 9410: 
 9411: Do an ssi with retries:
 9412: While I'd love to factor out this with the vesrion in lonprintout,
 9413: 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
 9414: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9415: 
 9416: At least the logic that drives this has been pulled out into loncommon.
 9417: 
 9418: 
 9419: 
 9420: ssi_with_retries - Does the server side include of a resource.
 9421:                      if the ssi call returns an error we'll retry it up to
 9422:                      the number of times requested by the caller.
 9423:                      If we still have a proble, no text is appended to the
 9424:                      output and we set some global variables.
 9425:                      to indicate to the caller an SSI error occurred.  
 9426:                      All of this is supposed to deal with the issues described
 9427:                      in LonCAPA BZ 5631 see:
 9428:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9429:                      by informing the user that this happened.
 9430: 
 9431: Parameters:
 9432:   resource   - The resource to include.  This is passed directly, without
 9433:                interpretation to lonnet::ssi.
 9434:   form       - The form hash parameters that guide the interpretation of the resource
 9435:                
 9436:   retries    - Number of retries allowed before giving up completely.
 9437: Returns:
 9438:   On success, returns the rendered resource identified by the resource parameter.
 9439: Side Effects:
 9440:   The following global variables can be set:
 9441:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9442:                               It is up to the caller to initialize this to false
 9443:                               if desired.
 9444:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9445:                               of the resource that could not be rendered by the ssi
 9446:                               call.
 9447:    ssi_error_message   - The error string fetched from the ssi response
 9448:                               in the event of an error.
 9449: 
 9450: 
 9451: =head1 HANDLER SUBROUTINE
 9452: 
 9453: ssi_with_retries()
 9454: 
 9455: =head1 SUBROUTINES
 9456: 
 9457: =over
 9458: 
 9459: =item scantron_get_correction() : 
 9460: 
 9461:    Builds the interface screen to interact with the operator to fix a
 9462:    specific error condition in a specific scanline
 9463: 
 9464:  Arguments:
 9465:     $r           - Apache request object
 9466:     $i           - number of the current scanline
 9467:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9468:     $scan_config - hash ref as returned from &get_scantron_config()
 9469:     $line        - full contents of the current scanline
 9470:     $error       - error condition, valid values are
 9471:                    'incorrectCODE', 'duplicateCODE',
 9472:                    'doublebubble', 'missingbubble',
 9473:                    'duplicateID', 'incorrectID'
 9474:     $arg         - extra information needed
 9475:        For errors:
 9476:          - duplicateID   - paper number that this studentID was seen before on
 9477:          - duplicateCODE - array ref of the paper numbers this CODE was
 9478:                            seen on before
 9479:          - incorrectCODE - current incorrect CODE 
 9480:          - doublebubble  - array ref of the bubble lines that have double
 9481:                            bubble errors
 9482:          - missingbubble - array ref of the bubble lines that have missing
 9483:                            bubble errors
 9484: 
 9485: =item  scantron_get_maxbubble() : 
 9486: 
 9487:    Arguments:
 9488:        $nav_error  - Reference to scalar which is a flag to indicate a
 9489:                       failure to retrieve a navmap object.
 9490:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9491:        calling routine should trap the error condition and display the warning
 9492:        found in &navmap_errormsg().
 9493: 
 9494:    Returns the maximum number of bubble lines that are expected to
 9495:    occur. Does this by walking the selected sequence rendering the
 9496:    resource and then checking &Apache::lonxml::get_problem_counter()
 9497:    for what the current value of the problem counter is.
 9498: 
 9499:    Caches the results to $env{'form.scantron_maxbubble'},
 9500:    $env{'form.scantron.bubble_lines.n'}, 
 9501:    $env{'form.scantron.first_bubble_line.n'} and
 9502:    $env{"form.scantron.sub_bubblelines.n"}
 9503:    which are the total number of bubble, lines, the number of bubble
 9504:    lines for response n and number of the first bubble line for response n,
 9505:    and a comma separated list of numbers of bubble lines for sub-questions
 9506:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9507: 
 9508: 
 9509: =item  scantron_validate_missingbubbles() : 
 9510: 
 9511:    Validates all scanlines in the selected file to not have any
 9512:     answers that don't have bubbles that have not been verified
 9513:     to be bubble free.
 9514: 
 9515: =item  scantron_process_students() : 
 9516: 
 9517:    Routine that does the actual grading of the bubble sheet information.
 9518: 
 9519:    The parsed scanline hash is added to %env 
 9520: 
 9521:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9522:    foreach resource , with the form data of
 9523: 
 9524: 	'submitted'     =>'scantron' 
 9525: 	'grade_target'  =>'grade',
 9526: 	'grade_username'=> username of student
 9527: 	'grade_domain'  => domain of student
 9528: 	'grade_courseid'=> of course
 9529: 	'grade_symb'    => symb of resource to grade
 9530: 
 9531:     This triggers a grading pass. The problem grading code takes care
 9532:     of converting the bubbled letter information (now in %env) into a
 9533:     valid submission.
 9534: 
 9535: =item  scantron_upload_scantron_data() :
 9536: 
 9537:     Creates the screen for adding a new bubble sheet data file to a course.
 9538: 
 9539: =item  scantron_upload_scantron_data_save() : 
 9540: 
 9541:    Adds a provided bubble information data file to the course if user
 9542:    has the correct privileges to do so. 
 9543: 
 9544: =item  valid_file() :
 9545: 
 9546:    Validates that the requested bubble data file exists in the course.
 9547: 
 9548: =item  scantron_download_scantron_data() : 
 9549: 
 9550:    Shows a list of the three internal files (original, corrected,
 9551:    skipped) for a specific bubble sheet data file that exists in the
 9552:    course.
 9553: 
 9554: =item  scantron_validate_ID() : 
 9555: 
 9556:    Validates all scanlines in the selected file to not have any
 9557:    invalid or underspecified student/employee IDs
 9558: 
 9559: =item navmap_errormsg() :
 9560: 
 9561:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9562:    Should be called whenever the request to instantiate a navmap object fails.  
 9563: 
 9564: =back
 9565: 
 9566: =cut

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