File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.583: download - view: text, annotated - select for diffs
Wed Dec 9 19:41:10 2009 UTC (14 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Amend 1.582 changes.
- Remove surplus &scantron_get_maxbubble() call
- Adding navmap object check for one more call to &scantron_get_maxbubble().

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.583 2009/12/09 19:41:10 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: package Apache::grades;
   32: use strict;
   33: use Apache::style;
   34: use Apache::lonxml;
   35: use Apache::lonnet;
   36: use Apache::loncommon;
   37: use Apache::lonhtmlcommon;
   38: use Apache::lonnavmaps;
   39: use Apache::lonhomework;
   40: use Apache::lonpickcode;
   41: use Apache::loncoursedata;
   42: use Apache::lonmsg();
   43: use Apache::Constants qw(:common);
   44: use Apache::lonlocal;
   45: use Apache::lonenc;
   46: use String::Similarity;
   47: use LONCAPA;
   48: 
   49: use POSIX qw(floor);
   50: 
   51: 
   52: 
   53: my %perm=();
   54: 
   55: #  These variables are used to recover from ssi errors
   56: 
   57: my $ssi_retries = 5;
   58: my $ssi_error;
   59: my $ssi_error_resource;
   60: my $ssi_error_message;
   61: 
   62: 
   63: sub ssi_with_retries {
   64:     my ($resource, $retries, %form) = @_;
   65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
   66:     if ($response->is_error) {
   67: 	$ssi_error          = 1;
   68: 	$ssi_error_resource = $resource;
   69: 	$ssi_error_message  = $response->code . " " . $response->message;
   70:     }
   71: 
   72:     return $content;
   73: 
   74: }
   75: #
   76: #  Prodcuces an ssi retry failure error message to the user:
   77: #
   78: 
   79: sub ssi_print_error {
   80:     my ($r) = @_;
   81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
   82:     $r->print('
   83: <br />
   84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
   85: <p>
   86: '.&mt('Unable to retrieve a resource from a server:').'<br />
   87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
   88: '.&mt('Error:').' '.$ssi_error_message.'
   89: </p>
   90: <p>'.
   91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
   92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
   93: '</p>');
   94:     return;
   95: }
   96: 
   97: #
   98: # --- Retrieve the parts from the metadata file.---
   99: sub getpartlist {
  100:     my ($symb,$errorref) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     unless (ref($navmap)) {
  104:         if (ref($errorref)) { 
  105:             $$errorref = 'navmap';
  106:             return;
  107:         }
  108:     }
  109:     my $res      = $navmap->getBySymb($symb);
  110:     my $partlist = $res->parts();
  111:     my $url      = $res->src();
  112:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  113: 
  114:     my @stores;
  115:     foreach my $part (@{ $partlist }) {
  116: 	foreach my $key (@metakeys) {
  117: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  118: 	}
  119:     }
  120:     return @stores;
  121: }
  122: 
  123: # --- Get the symbolic name of a problem and the url
  124: sub get_symb {
  125:     my ($request,$silent) = @_;
  126:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  127:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  128:     if ($symb eq '') { 
  129: 	if (!$silent) {
  130: 	    $request->print("Unable to handle ambiguous references:$url:.");
  131: 	    return ();
  132: 	}
  133:     }
  134:     &Apache::lonenc::check_decrypt(\$symb);
  135:     return ($symb);
  136: }
  137: 
  138: #--- Format fullname, username:domain if different for display
  139: #--- Use anywhere where the student names are listed
  140: sub nameUserString {
  141:     my ($type,$fullname,$uname,$udom) = @_;
  142:     if ($type eq 'header') {
  143: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  144:     } else {
  145: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  146: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  147:     }
  148: }
  149: 
  150: #--- Get the partlist and the response type for a given problem. ---
  151: #--- Indicate if a response type is coded handgraded or not. ---
  152: sub response_type {
  153:     my ($symb,$response_error) = @_;
  154: 
  155:     my $navmap = Apache::lonnavmaps::navmap->new();
  156:     unless (ref($navmap)) {
  157:         if (ref($response_error)) {
  158:             $$response_error = 1;
  159:         }
  160:         return;
  161:     }
  162:     my $res = $navmap->getBySymb($symb);
  163:     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 $col=3;
  211:     if ($checkboxes) { $col=4; }
  212:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  213:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  214:     if (ref($res_error)) {
  215:         if ($$res_error) {
  216:             return;
  217:         }
  218:     }
  219:     $result .='<table border="0">';
  220:     my %resptype = ();
  221:     my $hdgrade='no';
  222:     my %partsseen;
  223:     foreach my $partID (sort(keys(%$responseType))) {
  224: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  225: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  226: 	    my $responsetype = $responseType->{$partID}->{$resID};
  227: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  228: 	    $result.='<tr>';
  229: 	    if ($checkboxes) {
  230: 		if (exists($partsseen{$partID})) {
  231: 		    $result.="<td>&nbsp;</td>";
  232: 		} else {
  233: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  234: 		}
  235: 		$partsseen{$partID}=1;
  236: 	    }
  237: 	    my $display_part=&get_display_part($partID,$symb);
  238:             $result.='<td><b>'.&mt('Part: [_1]',$display_part).'</b>'.
  239:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  240:                 '<td><b>'.&mt('Type: [_1]',$responsetype).'</b></td></tr>';
  241: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  242: 	}
  243:     }
  244:     $result.='</table>'."\n";
  245:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  246: }
  247: 
  248: sub reset_caches {
  249:     &reset_analyze_cache();
  250:     &reset_perm();
  251: }
  252: 
  253: {
  254:     my %analyze_cache;
  255:     my %analyze_cache_formkeys;
  256: 
  257:     sub reset_analyze_cache {
  258: 	undef(%analyze_cache);
  259:         undef(%analyze_cache_formkeys);
  260:     }
  261: 
  262:     sub get_analyze {
  263: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  264: 	my $key = "$symb\0$uname\0$udom";
  265: 	if (exists($analyze_cache{$key})) {
  266:             my $getupdate = 0;
  267:             if (ref($add_to_hash) eq 'HASH') {
  268:                 foreach my $item (keys(%{$add_to_hash})) {
  269:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  270:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  271:                             $getupdate = 1;
  272:                             last;
  273:                         }
  274:                     } else {
  275:                         $getupdate = 1;
  276:                     }
  277:                 }
  278:             }
  279:             if (!$getupdate) {
  280:                 return $analyze_cache{$key};
  281:             }
  282:         }
  283: 
  284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  285: 	$url=&Apache::lonnet::clutter($url);
  286:         my %form = ('grade_target'      => 'analyze',
  287:                     'grade_domain'      => $udom,
  288:                     'grade_symb'        => $symb,
  289:                     'grade_courseid'    =>  $env{'request.course.id'},
  290:                     'grade_username'    => $uname,
  291:                     'grade_noincrement' => $no_increment);
  292:         if (ref($add_to_hash)) {
  293:             %form = (%form,%{$add_to_hash});
  294:         } 
  295: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  296: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  297: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  298:         if (ref($add_to_hash) eq 'HASH') {
  299:             $analyze_cache_formkeys{$key} = $add_to_hash;
  300:         } else {
  301:             $analyze_cache_formkeys{$key} = {};
  302:         }
  303: 	return $analyze_cache{$key} = \%analyze;
  304:     }
  305: 
  306:     sub get_order {
  307: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  308: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  309: 	return $analyze->{"$partid.$respid.shown"};
  310:     }
  311: 
  312:     sub get_radiobutton_correct_foil {
  313: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  314: 	my $analyze = &get_analyze($symb,$uname,$udom);
  315:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  316:         if (ref($foils) eq 'ARRAY') {
  317: 	    foreach my $foil (@{$foils}) {
  318: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  319: 		    return $foil;
  320: 	        }
  321: 	    }
  322: 	}
  323:     }
  324: 
  325:     sub scantron_partids_tograde {
  326:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  327:         my (%analysis,@parts);
  328:         if (ref($resource)) {
  329:             my $symb = $resource->symb();
  330:             my $add_to_form;
  331:             if ($check_for_randomlist) {
  332:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  333:             }
  334:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  335:             if (ref($analyze) eq 'HASH') {
  336:                 %analysis = %{$analyze};
  337:             }
  338:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  339:                 foreach my $part (@{$analysis{'parts'}}) {
  340:                     my ($id,$respid) = split(/\./,$part);
  341:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  342:                         push(@parts,$part);
  343:                     }
  344:                 }
  345:             }
  346:         }
  347:         return (\%analysis,\@parts);
  348:     }
  349: 
  350: }
  351: 
  352: #--- Clean response type for display
  353: #--- Currently filters option/rank/radiobutton/match/essay/Task
  354: #        response types only.
  355: sub cleanRecord {
  356:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  357: 	$uname,$udom) = @_;
  358:     my $grayFont = '<span class="LC_internal_info">';
  359:     if ($response =~ /^(option|rank)$/) {
  360: 	my %answer=&Apache::lonnet::str2hash($answer);
  361: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  362: 	my ($toprow,$bottomrow);
  363: 	foreach my $foil (@$order) {
  364: 	    if ($grading{$foil} == 1) {
  365: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  366: 	    } else {
  367: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  368: 	    }
  369: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  370: 	}
  371: 	return '<blockquote><table border="1">'.
  372: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  373: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  374: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  375:     } elsif ($response eq 'match') {
  376: 	my %answer=&Apache::lonnet::str2hash($answer);
  377: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  378: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  379: 	my ($toprow,$middlerow,$bottomrow);
  380: 	foreach my $foil (@$order) {
  381: 	    my $item=shift(@items);
  382: 	    if ($grading{$foil} == 1) {
  383: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  384: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  385: 	    } else {
  386: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  387: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  388: 	    }
  389: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  390: 	}
  391: 	return '<blockquote><table border="1">'.
  392: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  393: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  394: 	    $middlerow.'</tr>'.
  395: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  396: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  397:     } elsif ($response eq 'radiobutton') {
  398: 	my %answer=&Apache::lonnet::str2hash($answer);
  399: 	my ($toprow,$bottomrow);
  400: 	my $correct = 
  401: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  402: 	foreach my $foil (@$order) {
  403: 	    if (exists($answer{$foil})) {
  404: 		if ($foil eq $correct) {
  405: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  406: 		} else {
  407: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  408: 		}
  409: 	    } else {
  410: 		$toprow.='<td>'.&mt('false').'</td>';
  411: 	    }
  412: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  413: 	}
  414: 	return '<blockquote><table border="1">'.
  415: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  416: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  417: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  418:     } elsif ($response eq 'essay') {
  419: 	if (! exists ($env{'form.'.$symb})) {
  420: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  421: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  422: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  423: 
  424: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  425: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  426: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  427: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  428: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  429: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  430: 	}
  431: 	$answer =~ s-\n-<br />-g;
  432: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  433:     } elsif ( $response eq 'organic') {
  434: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  435: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  436: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  437: 	return $result;
  438:     } elsif ( $response eq 'Task') {
  439: 	if ( $answer eq 'SUBMITTED') {
  440: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  441: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  442: 	    return $result;
  443: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  444: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  445: 			       keys(%{$record}));
  446: 	    return join('<br />',($version,@matches));
  447: 			       
  448: 			       
  449: 	} else {
  450: 	    my $result =
  451: 		'<p>'
  452: 		.&mt('Overall result: [_1]',
  453: 		     $record->{$version."resource.$respid.$partid.status"})
  454: 		.'</p>';
  455: 	    
  456: 	    $result .= '<ul>';
  457: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  458: 			     keys(%{$record}));
  459: 	    foreach my $grade (sort(@grade)) {
  460: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  461: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  462: 				     $dim, $record->{$grade}).
  463: 			  '</li>';
  464: 	    }
  465: 	    $result.='</ul>';
  466: 	    return $result;
  467: 	}
  468:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  469: 	$answer = 
  470: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  471: 							      $answer);
  472:     }
  473:     return $answer;
  474: }
  475: 
  476: #-- A couple of common js functions
  477: sub commonJSfunctions {
  478:     my $request = shift;
  479:     $request->print(<<COMMONJSFUNCTIONS);
  480: <script type="text/javascript" language="javascript">
  481:     function radioSelection(radioButton) {
  482: 	var selection=null;
  483: 	if (radioButton.length > 1) {
  484: 	    for (var i=0; i<radioButton.length; i++) {
  485: 		if (radioButton[i].checked) {
  486: 		    return radioButton[i].value;
  487: 		}
  488: 	    }
  489: 	} else {
  490: 	    if (radioButton.checked) return radioButton.value;
  491: 	}
  492: 	return selection;
  493:     }
  494: 
  495:     function pullDownSelection(selectOne) {
  496: 	var selection="";
  497: 	if (selectOne.length > 1) {
  498: 	    for (var i=0; i<selectOne.length; i++) {
  499: 		if (selectOne[i].selected) {
  500: 		    return selectOne[i].value;
  501: 		}
  502: 	    }
  503: 	} else {
  504:             // only one value it must be the selected one
  505: 	    return selectOne.value;
  506: 	}
  507:     }
  508: </script>
  509: COMMONJSFUNCTIONS
  510: }
  511: 
  512: #--- Dumps the class list with usernames,list of sections,
  513: #--- section, ids and fullnames for each user.
  514: sub getclasslist {
  515:     my ($getsec,$filterlist,$getgroup) = @_;
  516:     my @getsec;
  517:     my @getgroup;
  518:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  519:     if (!ref($getsec)) {
  520: 	if ($getsec ne '' && $getsec ne 'all') {
  521: 	    @getsec=($getsec);
  522: 	}
  523:     } else {
  524: 	@getsec=@{$getsec};
  525:     }
  526:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  527:     if (!ref($getgroup)) {
  528: 	if ($getgroup ne '' && $getgroup ne 'all') {
  529: 	    @getgroup=($getgroup);
  530: 	}
  531:     } else {
  532: 	@getgroup=@{$getgroup};
  533:     }
  534:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  535: 
  536:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  537:     # Bail out if we were unable to get the classlist
  538:     return if (! defined($classlist));
  539:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  540:     #
  541:     my %sections;
  542:     my %fullnames;
  543:     foreach my $student (keys(%$classlist)) {
  544:         my $end      = 
  545:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  546:         my $start    = 
  547:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  548:         my $id       = 
  549:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  550:         my $section  = 
  551:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  552:         my $fullname = 
  553:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  554:         my $status   = 
  555:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  556:         my $group   = 
  557:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  558: 	# filter students according to status selected
  559: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  560: 	    if (!($stu_status =~ $status)) {
  561: 		delete($classlist->{$student});
  562: 		next;
  563: 	    }
  564: 	}
  565: 	# filter students according to groups selected
  566: 	my @stu_groups = split(/,/,$group);
  567: 	if (@getgroup) {
  568: 	    my $exclude = 1;
  569: 	    foreach my $grp (@getgroup) {
  570: 	        foreach my $stu_group (@stu_groups) {
  571: 	            if ($stu_group eq $grp) {
  572: 	                $exclude = 0;
  573:     	            } 
  574: 	        }
  575:     	        if (($grp eq 'none') && !$group) {
  576:         	        $exclude = 0;
  577:         	}
  578: 	    }
  579: 	    if ($exclude) {
  580: 	        delete($classlist->{$student});
  581: 	    }
  582: 	}
  583: 	$section = ($section ne '' ? $section : 'none');
  584: 	if (&canview($section)) {
  585: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  586: 		$sections{$section}++;
  587: 		if ($classlist->{$student}) {
  588: 		    $fullnames{$student}=$fullname;
  589: 		}
  590: 	    } else {
  591: 		delete($classlist->{$student});
  592: 	    }
  593: 	} else {
  594: 	    delete($classlist->{$student});
  595: 	}
  596:     }
  597:     my %seen = ();
  598:     my @sections = sort(keys(%sections));
  599:     return ($classlist,\@sections,\%fullnames);
  600: }
  601: 
  602: sub canmodify {
  603:     my ($sec)=@_;
  604:     if ($perm{'mgr'}) {
  605: 	if (!defined($perm{'mgr_section'})) {
  606: 	    # can modify whole class
  607: 	    return 1;
  608: 	} else {
  609: 	    if ($sec eq $perm{'mgr_section'}) {
  610: 		#can modify the requested section
  611: 		return 1;
  612: 	    } else {
  613: 		# can't modify the request section
  614: 		return 0;
  615: 	    }
  616: 	}
  617:     }
  618:     #can't modify
  619:     return 0;
  620: }
  621: 
  622: sub canview {
  623:     my ($sec)=@_;
  624:     if ($perm{'vgr'}) {
  625: 	if (!defined($perm{'vgr_section'})) {
  626: 	    # can modify whole class
  627: 	    return 1;
  628: 	} else {
  629: 	    if ($sec eq $perm{'vgr_section'}) {
  630: 		#can modify the requested section
  631: 		return 1;
  632: 	    } else {
  633: 		# can't modify the request section
  634: 		return 0;
  635: 	    }
  636: 	}
  637:     }
  638:     #can't modify
  639:     return 0;
  640: }
  641: 
  642: #--- Retrieve the grade status of a student for all the parts
  643: sub student_gradeStatus {
  644:     my ($symb,$udom,$uname,$partlist) = @_;
  645:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  646:     my %partstatus = ();
  647:     foreach (@$partlist) {
  648: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  649: 	$status              = 'nothing' if ($status eq '');
  650: 	$partstatus{$_}      = $status;
  651: 	my $subkey           = "resource.$_.submitted_by";
  652: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  653:     }
  654:     return %partstatus;
  655: }
  656: 
  657: # hidden form and javascript that calls the form
  658: # Use by verifyscript and viewgrades
  659: # Shows a student's view of problem and submission
  660: sub jscriptNform {
  661:     my ($symb) = @_;
  662:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  663:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  664: 	'    function viewOneStudent(user,domain) {'."\n".
  665: 	'	document.onestudent.student.value = user;'."\n".
  666: 	'	document.onestudent.userdom.value = domain;'."\n".
  667: 	'	document.onestudent.submit();'."\n".
  668: 	'    }'."\n".
  669: 	'</script>'."\n";
  670:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  671: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  672: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  673: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  674: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  675: 	'<input type="hidden" name="command" value="submission" />'."\n".
  676: 	'<input type="hidden" name="student" value="" />'."\n".
  677: 	'<input type="hidden" name="userdom" value="" />'."\n".
  678: 	'</form>'."\n";
  679:     return $jscript;
  680: }
  681: 
  682: 
  683: 
  684: # Given the score (as a number [0-1] and the weight) what is the final
  685: # point value? This function will round to the nearest tenth, third,
  686: # or quarter if one of those is within the tolerance of .00001.
  687: sub compute_points {
  688:     my ($score, $weight) = @_;
  689:     
  690:     my $tolerance = .00001;
  691:     my $points = $score * $weight;
  692: 
  693:     # Check for nearness to 1/x.
  694:     my $check_for_nearness = sub {
  695:         my ($factor) = @_;
  696:         my $num = ($points * $factor) + $tolerance;
  697:         my $floored_num = floor($num);
  698:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  699:             return $floored_num / $factor;
  700:         }
  701:         return $points;
  702:     };
  703: 
  704:     $points = $check_for_nearness->(10);
  705:     $points = $check_for_nearness->(3);
  706:     $points = $check_for_nearness->(4);
  707:     
  708:     return $points;
  709: }
  710: 
  711: #------------------ End of general use routines --------------------
  712: 
  713: #
  714: # Find most similar essay
  715: #
  716: 
  717: sub most_similar {
  718:     my ($uname,$udom,$uessay,$old_essays)=@_;
  719: 
  720: # ignore spaces and punctuation
  721: 
  722:     $uessay=~s/\W+/ /gs;
  723: 
  724: # ignore empty submissions (occuring when only files are sent)
  725: 
  726:     unless ($uessay=~/\w+/) { return ''; }
  727: 
  728: # these will be returned. Do not care if not at least 50 percent similar
  729:     my $limit=0.6;
  730:     my $sname='';
  731:     my $sdom='';
  732:     my $scrsid='';
  733:     my $sessay='';
  734: # go through all essays ...
  735:     foreach my $tkey (keys(%$old_essays)) {
  736: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  737: # ... except the same student
  738:         next if (($tname eq $uname) && ($tdom eq $udom));
  739: 	my $tessay=$old_essays->{$tkey};
  740: 	$tessay=~s/\W+/ /gs;
  741: # String similarity gives up if not even limit
  742: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  743: # Found one
  744: 	if ($tsimilar>$limit) {
  745: 	    $limit=$tsimilar;
  746: 	    $sname=$tname;
  747: 	    $sdom=$tdom;
  748: 	    $scrsid=$tcrsid;
  749: 	    $sessay=$old_essays->{$tkey};
  750: 	}
  751:     }
  752:     if ($limit>0.6) {
  753:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  754:     } else {
  755:        return ('','','','',0);
  756:     }
  757: }
  758: 
  759: #-------------------------------------------------------------------
  760: 
  761: #------------------------------------ Receipt Verification Routines
  762: #
  763: #--- Check whether a receipt number is valid.---
  764: sub verifyreceipt {
  765:     my $request  = shift;
  766: 
  767:     my $courseid = $env{'request.course.id'};
  768:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  769: 	$env{'form.receipt'};
  770:     $receipt     =~ s/[^\-\d]//g;
  771:     my ($symb)   = &get_symb($request);
  772: 
  773:     my $title.=
  774: 	'<h3><span class="LC_info">'.
  775: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  776: 	'</span></h3>'."\n".
  777: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  778: 	'</h4>'."\n";
  779: 
  780:     my ($string,$contents,$matches) = ('','',0);
  781:     my (undef,undef,$fullname) = &getclasslist('all','0');
  782:     
  783:     my $receiptparts=0;
  784:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  785: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  786:     my $parts=['0'];
  787:     if ($receiptparts) {
  788:         my $res_error; 
  789:         ($parts)=&response_type($symb,\$res_error);
  790:         if ($res_error) {
  791:             return &navmap_errormsg();
  792:         } 
  793:     }
  794:     
  795:     my $header = 
  796: 	&Apache::loncommon::start_data_table().
  797: 	&Apache::loncommon::start_data_table_header_row().
  798: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  799: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  800: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  801:     if ($receiptparts) {
  802: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  803:     }
  804:     $header.=
  805: 	&Apache::loncommon::end_data_table_header_row();
  806: 
  807:     foreach (sort 
  808: 	     {
  809: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  810: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  811: 		 }
  812: 		 return $a cmp $b;
  813: 	     } (keys(%$fullname))) {
  814: 	my ($uname,$udom)=split(/\:/);
  815: 	foreach my $part (@$parts) {
  816: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  817: 		$contents.=
  818: 		    &Apache::loncommon::start_data_table_row().
  819: 		    '<td>&nbsp;'."\n".
  820: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  821: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  822: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  823: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  824: 		if ($receiptparts) {
  825: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  826: 		}
  827: 		$contents.= 
  828: 		    &Apache::loncommon::end_data_table_row()."\n";
  829: 		
  830: 		$matches++;
  831: 	    }
  832: 	}
  833:     }
  834:     if ($matches == 0) {
  835: 	$string = $title.&mt('No match found for the above receipt.');
  836:     } else {
  837: 	$string = &jscriptNform($symb).$title.
  838: 	    '<p>'.
  839: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  840: 	    '</p>'.
  841: 	    $header.
  842: 	    $contents.
  843: 	    &Apache::loncommon::end_data_table()."\n";
  844:     }
  845:     return $string.&show_grading_menu_form($symb);
  846: }
  847: 
  848: #--- This is called by a number of programs.
  849: #--- Called from the Grading Menu - View/Grade an individual student
  850: #--- Also called directly when one clicks on the subm button 
  851: #    on the problem page.
  852: sub listStudents {
  853:     my ($request) = shift;
  854: 
  855:     my ($symb) = &get_symb($request);
  856:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  857:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  858:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  859:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  860:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  861:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  862:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  863: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  864: 
  865:     my $result='<h3><span class="LC_info">&nbsp;'
  866: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  867: 	.'</span></h3>';
  868: 
  869:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  870: 
  871:     my %lt = &Apache::lonlocal::texthash (
  872: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  873: 		'single'   => 'Please select the student before clicking on the Next button.',
  874: 	     );
  875:     $request->print(<<LISTJAVASCRIPT);
  876: <script type="text/javascript" language="javascript">
  877:     function checkSelect(checkBox) {
  878: 	var ctr=0;
  879: 	var sense="";
  880: 	if (checkBox.length > 1) {
  881: 	    for (var i=0; i<checkBox.length; i++) {
  882: 		if (checkBox[i].checked) {
  883: 		    ctr++;
  884: 		}
  885: 	    }
  886: 	    sense = '$lt{'multiple'}';
  887: 	} else {
  888: 	    if (checkBox.checked) {
  889: 		ctr = 1;
  890: 	    }
  891: 	    sense = '$lt{'single'}';
  892: 	}
  893: 	if (ctr == 0) {
  894: 	    alert(sense);
  895: 	    return false;
  896: 	}
  897: 	document.gradesub.submit();
  898:     }
  899: 
  900:     function reLoadList(formname) {
  901: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  902: 	formname.command.value = 'submission';
  903: 	formname.submit();
  904:     }
  905: </script>
  906: LISTJAVASCRIPT
  907: 
  908:     &commonJSfunctions($request);
  909:     $request->print($result);
  910: 
  911:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  912:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  913:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  914: 	"\n".$table;
  915: 	
  916:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  917:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  918:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  919:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  920:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  921:                   .&Apache::lonhtmlcommon::row_closure();
  922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  923:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  924:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  925:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  926:                   .&Apache::lonhtmlcommon::row_closure();
  927: 
  928:     my $submission_options;
  929:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  930: 	$submission_options.=
  931: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  932:     }
  933:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  934:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  935:     $env{'form.Status'} = $saveStatus;
  936:     $submission_options.=
  937: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  938: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  939: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  940: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  941:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  942:                   .$submission_options
  943:                   .&Apache::lonhtmlcommon::row_closure();
  944: 
  945:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  946:                   .'<select name="increment">'
  947:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  948:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  949:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  950:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  951:                   .'</select>'
  952:                   .&Apache::lonhtmlcommon::row_closure();
  953: 
  954:     $gradeTable .= 
  955:         &build_section_inputs().
  956: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  957: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  958: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  959: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  960: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  961: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  962: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  963: 
  964:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  965: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  966:     } else {
  967:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  968:                       .&Apache::lonhtmlcommon::StatusOptions(
  969:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  970:                       .&Apache::lonhtmlcommon::row_closure();
  971:     }
  972: 
  973:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  974:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  975:                   .&Apache::lonhtmlcommon::row_closure(1)
  976:                   .&Apache::lonhtmlcommon::end_pick_box();
  977: 
  978:     $gradeTable .= '<p>'
  979:                   .&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"
  980:                   .'<input type="hidden" name="command" value="processGroup" />'
  981:                   .'</p>';
  982: 
  983: # checkall buttons
  984:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  985:     $gradeTable.='<input type="button" '."\n".
  986: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  987: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  988:     $gradeTable.=&check_buttons();
  989:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  990:     $gradeTable.= &Apache::loncommon::start_data_table().
  991: 	&Apache::loncommon::start_data_table_header_row();
  992:     my $loop = 0;
  993:     while ($loop < 2) {
  994: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  995: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  996: 	if ($env{'form.showgrading'} eq 'yes' 
  997: 	    && $submitonly ne 'queued'
  998: 	    && $submitonly ne 'all') {
  999: 	    foreach my $part (sort(@$partlist)) {
 1000: 		my $display_part=
 1001: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1002: 		$gradeTable.=
 1003: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1004: 	    }
 1005: 	} elsif ($submitonly eq 'queued') {
 1006: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1007: 	}
 1008: 	$loop++;
 1009: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1010:     }
 1011:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1012: 
 1013:     my $ctr = 0;
 1014:     foreach my $student (sort 
 1015: 			 {
 1016: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1017: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1018: 			     }
 1019: 			     return $a cmp $b;
 1020: 			 }
 1021: 			 (keys(%$fullname))) {
 1022: 	my ($uname,$udom) = split(/:/,$student);
 1023: 
 1024: 	my %status = ();
 1025: 
 1026: 	if ($submitonly eq 'queued') {
 1027: 	    my %queue_status = 
 1028: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1029: 							$udom,$uname);
 1030: 	    next if (!defined($queue_status{'gradingqueue'}));
 1031: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1032: 	}
 1033: 
 1034: 	if ($env{'form.showgrading'} eq 'yes' 
 1035: 	    && $submitonly ne 'queued'
 1036: 	    && $submitonly ne 'all') {
 1037: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1038: 	    my $submitted = 0;
 1039: 	    my $graded = 0;
 1040: 	    my $incorrect = 0;
 1041: 	    foreach (keys(%status)) {
 1042: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1043: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1044: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1045: 		
 1046: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1047: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1048: 		    $submitted = 0;
 1049: 		    my ($part)=split(/\./,$partid);
 1050: 		    $gradeTable.='<input type="hidden" name="'.
 1051: 			$student.':'.$part.':submitted_by" value="'.
 1052: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1053: 		}
 1054: 	    }
 1055: 	    
 1056: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1057: 				     $submitonly eq 'incorrect' ||
 1058: 				     $submitonly eq 'graded'));
 1059: 	    next if (!$graded && ($submitonly eq 'graded'));
 1060: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1061: 	}
 1062: 
 1063: 	$ctr++;
 1064: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1065:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1066: 	if ( $perm{'vgr'} eq 'F' ) {
 1067: 	    if ($ctr%2 ==1) {
 1068: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1069: 	    }
 1070: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1071:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1072:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1073: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1074: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1075: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1076: 
 1077: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1078: 		foreach (sort(keys(%status))) {
 1079: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1080: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1081: 		}
 1082: 	    }
 1083: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1084: 	    if ($ctr%2 ==0) {
 1085: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1086: 	    }
 1087: 	}
 1088:     }
 1089:     if ($ctr%2 ==1) {
 1090: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1091: 	    if ($env{'form.showgrading'} eq 'yes' 
 1092: 		&& $submitonly ne 'queued'
 1093: 		&& $submitonly ne 'all') {
 1094: 		foreach (@$partlist) {
 1095: 		    $gradeTable.='<td>&nbsp;</td>';
 1096: 		}
 1097: 	    } elsif ($submitonly eq 'queued') {
 1098: 		$gradeTable.='<td>&nbsp;</td>';
 1099: 	    }
 1100: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1101:     }
 1102: 
 1103:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1104: 	'<input type="button" '.
 1105: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1106: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1107:     if ($ctr == 0) {
 1108: 	my $num_students=(scalar(keys(%$fullname)));
 1109: 	if ($num_students eq 0) {
 1110: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1111: 	} else {
 1112: 	    my $submissions='submissions';
 1113: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1114: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1115: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1116: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1117: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1118: 		    $num_students).
 1119: 		'</span><br />';
 1120: 	}
 1121:     } elsif ($ctr == 1) {
 1122: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1123:     }
 1124:     $gradeTable.=&show_grading_menu_form($symb);
 1125:     $request->print($gradeTable);
 1126:     return '';
 1127: }
 1128: 
 1129: #---- Called from the listStudents routine
 1130: 
 1131: sub check_script {
 1132:     my ($form, $type)=@_;
 1133:     my $chkallscript='<script type="text/javascript">
 1134:     function checkall() {
 1135:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1136:             ele = document.forms.'.$form.'.elements[i];
 1137:             if (ele.name == "'.$type.'") {
 1138:             document.forms.'.$form.'.elements[i].checked=true;
 1139:                                        }
 1140:         }
 1141:     }
 1142: 
 1143:     function checksec() {
 1144:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1145:             ele = document.forms.'.$form.'.elements[i];
 1146:            string = document.forms.'.$form.'.chksec.value;
 1147:            if
 1148:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1149:               document.forms.'.$form.'.elements[i].checked=true;
 1150:             }
 1151:         }
 1152:     }
 1153: 
 1154: 
 1155:     function uncheckall() {
 1156:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1157:             ele = document.forms.'.$form.'.elements[i];
 1158:             if (ele.name == "'.$type.'") {
 1159:             document.forms.'.$form.'.elements[i].checked=false;
 1160:                                        }
 1161:         }
 1162:     }
 1163: 
 1164: </script>'."\n";
 1165:     return $chkallscript;
 1166: }
 1167: 
 1168: sub check_buttons {
 1169:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1170:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1171:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1172:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1173:     return $buttons;
 1174: }
 1175: 
 1176: #     Displays the submissions for one student or a group of students
 1177: sub processGroup {
 1178:     my ($request)  = shift;
 1179:     my $ctr        = 0;
 1180:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1181:     my $total      = scalar(@stuchecked)-1;
 1182: 
 1183:     foreach my $student (@stuchecked) {
 1184: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1185: 	$env{'form.student'}        = $uname;
 1186: 	$env{'form.userdom'}        = $udom;
 1187: 	$env{'form.fullname'}       = $fullname;
 1188: 	&submission($request,$ctr,$total);
 1189: 	$ctr++;
 1190:     }
 1191:     return '';
 1192: }
 1193: 
 1194: #------------------------------------------------------------------------------------
 1195: #
 1196: #-------------------------- Next few routines handles grading by student, essentially
 1197: #                           handles essay response type problem/part
 1198: #
 1199: #--- Javascript to handle the submission page functionality ---
 1200: sub sub_page_js {
 1201:     my $request = shift;
 1202: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1203:     $request->print(<<SUBJAVASCRIPT);
 1204: <script type="text/javascript" language="javascript">
 1205:     function updateRadio(formname,id,weight) {
 1206: 	var gradeBox = formname["GD_BOX"+id];
 1207: 	var radioButton = formname["RADVAL"+id];
 1208: 	var oldpts = formname["oldpts"+id].value;
 1209: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1210: 	gradeBox.value = pts;
 1211: 	var resetbox = false;
 1212: 	if (isNaN(pts) || pts < 0) {
 1213: 	    alert("$alertmsg"+pts);
 1214: 	    for (var i=0; i<radioButton.length; i++) {
 1215: 		if (radioButton[i].checked) {
 1216: 		    gradeBox.value = i;
 1217: 		    resetbox = true;
 1218: 		}
 1219: 	    }
 1220: 	    if (!resetbox) {
 1221: 		formtextbox.value = "";
 1222: 	    }
 1223: 	    return;
 1224: 	}
 1225: 
 1226: 	if (pts > weight) {
 1227: 	    var resp = confirm("You entered a value ("+pts+
 1228: 			       ") greater than the weight for the part. Accept?");
 1229: 	    if (resp == false) {
 1230: 		gradeBox.value = oldpts;
 1231: 		return;
 1232: 	    }
 1233: 	}
 1234: 
 1235: 	for (var i=0; i<radioButton.length; i++) {
 1236: 	    radioButton[i].checked=false;
 1237: 	    if (pts == i && pts != "") {
 1238: 		radioButton[i].checked=true;
 1239: 	    }
 1240: 	}
 1241: 	updateSelect(formname,id);
 1242: 	formname["stores"+id].value = "0";
 1243:     }
 1244: 
 1245:     function writeBox(formname,id,pts) {
 1246: 	var gradeBox = formname["GD_BOX"+id];
 1247: 	if (checkSolved(formname,id) == 'update') {
 1248: 	    gradeBox.value = pts;
 1249: 	} else {
 1250: 	    var oldpts = formname["oldpts"+id].value;
 1251: 	    gradeBox.value = oldpts;
 1252: 	    var radioButton = formname["RADVAL"+id];
 1253: 	    for (var i=0; i<radioButton.length; i++) {
 1254: 		radioButton[i].checked=false;
 1255: 		if (i == oldpts) {
 1256: 		    radioButton[i].checked=true;
 1257: 		}
 1258: 	    }
 1259: 	}
 1260: 	formname["stores"+id].value = "0";
 1261: 	updateSelect(formname,id);
 1262: 	return;
 1263:     }
 1264: 
 1265:     function clearRadBox(formname,id) {
 1266: 	if (checkSolved(formname,id) == 'noupdate') {
 1267: 	    updateSelect(formname,id);
 1268: 	    return;
 1269: 	}
 1270: 	gradeSelect = formname["GD_SEL"+id];
 1271: 	for (var i=0; i<gradeSelect.length; i++) {
 1272: 	    if (gradeSelect[i].selected) {
 1273: 		var selectx=i;
 1274: 	    }
 1275: 	}
 1276: 	var stores = formname["stores"+id];
 1277: 	if (selectx == stores.value) { return };
 1278: 	var gradeBox = formname["GD_BOX"+id];
 1279: 	gradeBox.value = "";
 1280: 	var radioButton = formname["RADVAL"+id];
 1281: 	for (var i=0; i<radioButton.length; i++) {
 1282: 	    radioButton[i].checked=false;
 1283: 	}
 1284: 	stores.value = selectx;
 1285:     }
 1286: 
 1287:     function checkSolved(formname,id) {
 1288: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1289: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1290: 	    if (!reply) {return "noupdate";}
 1291: 	    formname.overRideScore.value = 'yes';
 1292: 	}
 1293: 	return "update";
 1294:     }
 1295: 
 1296:     function updateSelect(formname,id) {
 1297: 	formname["GD_SEL"+id][0].selected = true;
 1298: 	return;
 1299:     }
 1300: 
 1301: //=========== Check that a point is assigned for all the parts  ============
 1302:     function checksubmit(formname,val,total,parttot) {
 1303: 	formname.gradeOpt.value = val;
 1304: 	if (val == "Save & Next") {
 1305: 	    for (i=0;i<=total;i++) {
 1306: 		for (j=0;j<parttot;j++) {
 1307: 		    var partid = formname["partid"+i+"_"+j].value;
 1308: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1309: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1310: 			if (points == "") {
 1311: 			    var name = formname["name"+i].value;
 1312: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1313: 			    var resp = confirm("You did not assign a score for "+studentID+
 1314: 					       ", part "+partid+". Continue?");
 1315: 			    if (resp == false) {
 1316: 				formname["GD_BOX"+i+"_"+partid].focus();
 1317: 				return false;
 1318: 			    }
 1319: 			}
 1320: 		    }
 1321: 		    
 1322: 		}
 1323: 	    }
 1324: 	    
 1325: 	}
 1326: 	if (val == "Grade Student") {
 1327: 	    formname.showgrading.value = "yes";
 1328: 	    if (formname.Status.value == "") {
 1329: 		formname.Status.value = "Active";
 1330: 	    }
 1331: 	    formname.studentNo.value = total;
 1332: 	}
 1333: 	formname.submit();
 1334:     }
 1335: 
 1336: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1337:     function checkSubmitPage(formname,total) {
 1338: 	noscore = new Array(100);
 1339: 	var ptr = 0;
 1340: 	for (i=1;i<total;i++) {
 1341: 	    var partid = formname["q_"+i].value;
 1342: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1343: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1344: 		var status = formname["solved"+i+"_"+partid].value;
 1345: 		if (points == "" && status != "correct_by_student") {
 1346: 		    noscore[ptr] = i;
 1347: 		    ptr++;
 1348: 		}
 1349: 	    }
 1350: 	}
 1351: 	if (ptr != 0) {
 1352: 	    var sense = ptr == 1 ? ": " : "s: ";
 1353: 	    var prolist = "";
 1354: 	    if (ptr == 1) {
 1355: 		prolist = noscore[0];
 1356: 	    } else {
 1357: 		var i = 0;
 1358: 		while (i < ptr-1) {
 1359: 		    prolist += noscore[i]+", ";
 1360: 		    i++;
 1361: 		}
 1362: 		prolist += "and "+noscore[i];
 1363: 	    }
 1364: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1365: 	    if (resp == false) {
 1366: 		return false;
 1367: 	    }
 1368: 	}
 1369: 
 1370: 	formname.submit();
 1371:     }
 1372: </script>
 1373: SUBJAVASCRIPT
 1374: }
 1375: 
 1376: #--- javascript for essay type problem --
 1377: sub sub_page_kw_js {
 1378:     my $request = shift;
 1379:     my $iconpath = $request->dir_config('lonIconsURL');
 1380:     &commonJSfunctions($request);
 1381: 
 1382:     my $inner_js_msg_central=<<INNERJS;
 1383:     <script text="text/javascript">
 1384:     function checkInput() {
 1385:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1386:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1387:       var usrctr = document.msgcenter.usrctr.value;
 1388:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1389:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1390: 
 1391:       var msgchk = "";
 1392:       if (document.msgcenter.subchk.checked) {
 1393:          msgchk = "msgsub,";
 1394:       }
 1395:       var includemsg = 0;
 1396:       for (var i=1; i<=nmsg; i++) {
 1397:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1398:           var frmmsg = document.msgcenter["msg"+i];
 1399:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1400:           var showflg = opener.document.SCORE["shownOnce"+i];
 1401:           showflg.value = "1";
 1402:           var chkbox = document.msgcenter["msgn"+i];
 1403:           if (chkbox.checked) {
 1404:              msgchk += "savemsg"+i+",";
 1405:              includemsg = 1;
 1406:           }
 1407:       }
 1408:       if (document.msgcenter.newmsgchk.checked) {
 1409:          msgchk += "newmsg"+usrctr;
 1410:          includemsg = 1;
 1411:       }
 1412:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1413:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1414:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1415:       includemsg.value = msgchk;
 1416: 
 1417:       self.close()
 1418: 
 1419:     }
 1420:     </script>
 1421: INNERJS
 1422: 
 1423:     my $inner_js_highlight_central=<<INNERJS;
 1424:  <script type="text/javascript">
 1425:     function updateChoice(flag) {
 1426:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1427:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1428:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1429:       opener.document.SCORE.refresh.value = "on";
 1430:       if (opener.document.SCORE.keywords.value!=""){
 1431:          opener.document.SCORE.submit();
 1432:       }
 1433:       self.close()
 1434:     }
 1435: </script>
 1436: INNERJS
 1437: 
 1438:     my $start_page_msg_central = 
 1439:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1440: 				       {'js_ready'  => 1,
 1441: 					'only_body' => 1,
 1442: 					'bgcolor'   =>'#FFFFFF',});
 1443:     my $end_page_msg_central = 
 1444: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1445: 
 1446: 
 1447:     my $start_page_highlight_central = 
 1448:         &Apache::loncommon::start_page('Highlight Central',
 1449: 				       $inner_js_highlight_central,
 1450: 				       {'js_ready'  => 1,
 1451: 					'only_body' => 1,
 1452: 					'bgcolor'   =>'#FFFFFF',});
 1453:     my $end_page_highlight_central = 
 1454: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1455: 
 1456:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1457:     $docopen=~s/^document\.//;
 1458:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1459:     $request->print(<<SUBJAVASCRIPT);
 1460: <script type="text/javascript" language="javascript">
 1461: 
 1462: //===================== Show list of keywords ====================
 1463:   function keywords(formname) {
 1464:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1465:     if (nret==null) return;
 1466:     formname.keywords.value = nret;
 1467: 
 1468:     if (formname.keywords.value != "") {
 1469: 	formname.refresh.value = "on";
 1470: 	formname.submit();
 1471:     }
 1472:     return;
 1473:   }
 1474: 
 1475: //===================== Script to view submitted by ==================
 1476:   function viewSubmitter(submitter) {
 1477:     document.SCORE.refresh.value = "on";
 1478:     document.SCORE.NCT.value = "1";
 1479:     document.SCORE.unamedom0.value = submitter;
 1480:     document.SCORE.submit();
 1481:     return;
 1482:   }
 1483: 
 1484: //===================== Script to add keyword(s) ==================
 1485:   function getSel() {
 1486:     if (document.getSelection) txt = document.getSelection();
 1487:     else if (document.selection) txt = document.selection.createRange().text;
 1488:     else return;
 1489:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1490:     if (cleantxt=="") {
 1491: 	alert("$alertmsg");
 1492: 	return;
 1493:     }
 1494:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1495:     if (nret==null) return;
 1496:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1497:     if (document.SCORE.keywords.value != "") {
 1498: 	document.SCORE.refresh.value = "on";
 1499: 	document.SCORE.submit();
 1500:     }
 1501:     return;
 1502:   }
 1503: 
 1504: //====================== Script for composing message ==============
 1505:    // preload images
 1506:    img1 = new Image();
 1507:    img1.src = "$iconpath/mailbkgrd.gif";
 1508:    img2 = new Image();
 1509:    img2.src = "$iconpath/mailto.gif";
 1510: 
 1511:   function msgCenter(msgform,usrctr,fullname) {
 1512:     var Nmsg  = msgform.savemsgN.value;
 1513:     savedMsgHeader(Nmsg,usrctr,fullname);
 1514:     var subject = msgform.msgsub.value;
 1515:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1516:     re = /msgsub/;
 1517:     var shwsel = "";
 1518:     if (re.test(msgchk)) { shwsel = "checked" }
 1519:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1520:     displaySubject(checkEntities(subject),shwsel);
 1521:     for (var i=1; i<=Nmsg; i++) {
 1522: 	var testmsg = "savemsg"+i+",";
 1523: 	re = new RegExp(testmsg,"g");
 1524: 	shwsel = "";
 1525: 	if (re.test(msgchk)) { shwsel = "checked" }
 1526: 	var message = document.SCORE["savemsg"+i].value;
 1527: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1528: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1529: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1530:     }
 1531:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1532:     shwsel = "";
 1533:     re = /newmsg/;
 1534:     if (re.test(msgchk)) { shwsel = "checked" }
 1535:     newMsg(newmsg,shwsel);
 1536:     msgTail(); 
 1537:     return;
 1538:   }
 1539: 
 1540:   function checkEntities(strx) {
 1541:     if (strx.length == 0) return strx;
 1542:     var orgStr = ["&", "<", ">", '"']; 
 1543:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1544:     var counter = 0;
 1545:     while (counter < 4) {
 1546: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1547: 	counter++;
 1548:     }
 1549:     return strx;
 1550:   }
 1551: 
 1552:   function strReplace(strx, orgStr, newStr) {
 1553:     return strx.split(orgStr).join(newStr);
 1554:   }
 1555: 
 1556:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1557:     var height = 70*Nmsg+250;
 1558:     var scrollbar = "no";
 1559:     if (height > 600) {
 1560: 	height = 600;
 1561: 	scrollbar = "yes";
 1562:     }
 1563:     var xpos = (screen.width-600)/2;
 1564:     xpos = (xpos < 0) ? '0' : xpos;
 1565:     var ypos = (screen.height-height)/2-30;
 1566:     ypos = (ypos < 0) ? '0' : ypos;
 1567: 
 1568:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1569:     pWin.focus();
 1570:     pDoc = pWin.document;
 1571:     pDoc.$docopen;
 1572:     pDoc.write('$start_page_msg_central');
 1573: 
 1574:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1575:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1576:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1577: 
 1578:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1579:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1580:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1581: }
 1582:     function displaySubject(msg,shwsel) {
 1583:     pDoc = pWin.document;
 1584:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1585:     pDoc.write("<td>Subject<\\/td>");
 1586:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1587:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1588: }
 1589: 
 1590:   function displaySavedMsg(ctr,msg,shwsel) {
 1591:     pDoc = pWin.document;
 1592:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1593:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1594:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1595:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1596: }
 1597: 
 1598:   function newMsg(newmsg,shwsel) {
 1599:     pDoc = pWin.document;
 1600:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1601:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1602:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1603:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1604: }
 1605: 
 1606:   function msgTail() {
 1607:     pDoc = pWin.document;
 1608:     pDoc.write("<\\/table>");
 1609:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1610:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1611:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1612:     pDoc.write("<\\/form>");
 1613:     pDoc.write('$end_page_msg_central');
 1614:     pDoc.close();
 1615: }
 1616: 
 1617: //====================== Script for keyword highlight options ==============
 1618:   function kwhighlight() {
 1619:     var kwclr    = document.SCORE.kwclr.value;
 1620:     var kwsize   = document.SCORE.kwsize.value;
 1621:     var kwstyle  = document.SCORE.kwstyle.value;
 1622:     var redsel = "";
 1623:     var grnsel = "";
 1624:     var blusel = "";
 1625:     if (kwclr=="red")   {var redsel="checked"};
 1626:     if (kwclr=="green") {var grnsel="checked"};
 1627:     if (kwclr=="blue")  {var blusel="checked"};
 1628:     var sznsel = "";
 1629:     var sz1sel = "";
 1630:     var sz2sel = "";
 1631:     if (kwsize=="0")  {var sznsel="checked"};
 1632:     if (kwsize=="+1") {var sz1sel="checked"};
 1633:     if (kwsize=="+2") {var sz2sel="checked"};
 1634:     var synsel = "";
 1635:     var syisel = "";
 1636:     var sybsel = "";
 1637:     if (kwstyle=="")    {var synsel="checked"};
 1638:     if (kwstyle=="<i>") {var syisel="checked"};
 1639:     if (kwstyle=="<b>") {var sybsel="checked"};
 1640:     highlightCentral();
 1641:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1642:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1643:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1644:     highlightend();
 1645:     return;
 1646:   }
 1647: 
 1648:   function highlightCentral() {
 1649: //    if (window.hwdWin) window.hwdWin.close();
 1650:     var xpos = (screen.width-400)/2;
 1651:     xpos = (xpos < 0) ? '0' : xpos;
 1652:     var ypos = (screen.height-330)/2-30;
 1653:     ypos = (ypos < 0) ? '0' : ypos;
 1654: 
 1655:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1656:     hwdWin.focus();
 1657:     var hDoc = hwdWin.document;
 1658:     hDoc.$docopen;
 1659:     hDoc.write('$start_page_highlight_central');
 1660:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1661:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1662: 
 1663:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1664:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1665:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1666:   }
 1667: 
 1668:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1669:     var hDoc = hwdWin.document;
 1670:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1671:     hDoc.write("<td align=\\"left\\">");
 1672:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1673:     hDoc.write("<td align=\\"left\\">");
 1674:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1675:     hDoc.write("<td align=\\"left\\">");
 1676:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1677:     hDoc.write("<\\/tr>");
 1678:   }
 1679: 
 1680:   function highlightend() { 
 1681:     var hDoc = hwdWin.document;
 1682:     hDoc.write("<\\/table>");
 1683:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1684:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1685:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1686:     hDoc.write("<\\/form>");
 1687:     hDoc.write('$end_page_highlight_central');
 1688:     hDoc.close();
 1689:   }
 1690: 
 1691: </script>
 1692: SUBJAVASCRIPT
 1693: }
 1694: 
 1695: sub get_increment {
 1696:     my $increment = $env{'form.increment'};
 1697:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1698:         $increment != .1) {
 1699:         $increment = 1;
 1700:     }
 1701:     return $increment;
 1702: }
 1703: 
 1704: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1705: sub gradeBox {
 1706:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1707:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1708: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1709:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1710:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1711:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1712:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1713:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1714: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1715:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1716:     my $display_part= &get_display_part($partid,$symb);
 1717:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1718: 				       [$partid]);
 1719:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1720:     if ($last_resets{$partid}) {
 1721:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1722:     }
 1723:     $result.='<table border="0"><tr>';
 1724:     my $ctr = 0;
 1725:     my $thisweight = 0;
 1726:     my $increment = &get_increment();
 1727: 
 1728:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1729:     while ($thisweight<=$wgt) {
 1730: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1731: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1732: 	    $thisweight.')" value="'.$thisweight.'" '.
 1733: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1734: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1735:         $thisweight += $increment;
 1736: 	$ctr++;
 1737:     }
 1738:     $radio.='</tr></table>';
 1739: 
 1740:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1741: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1742: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1743: 	$wgt.')" /></td>'."\n";
 1744:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1745: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1746: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1747:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1748: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1749:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1750: 	$line.='<option></option>'.
 1751: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1752:     } else {
 1753: 	$line.='<option selected="selected"></option>'.
 1754: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1755:     }
 1756:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1757: 
 1758: 
 1759: 	#&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);
 1760:     $result .= 
 1761: 	    '<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>';
 1762:     $result.='</tr></table>'."\n";
 1763:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1764: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1765: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1766: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1767:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1768:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1769:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1770:         $aggtries.'" />'."\n";
 1771:     my $res_error;
 1772:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1773:     if ($res_error) {
 1774:         return &navmap_errormsg();
 1775:     }
 1776:     return $result;
 1777: }
 1778: 
 1779: sub handback_box {
 1780:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1781:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1782:     my (@respids);
 1783:      my @part_response_id = &flatten_responseType($responseType);
 1784:     foreach my $part_response_id (@part_response_id) {
 1785:     	my ($part,$resp) = @{ $part_response_id };
 1786:         if ($part eq $partid) {
 1787:             push(@respids,$resp);
 1788:         }
 1789:     }
 1790:     my $result;
 1791:     foreach my $respid (@respids) {
 1792: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1793: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1794: 	next if (!@$files);
 1795: 	my $file_counter = 1;
 1796: 	foreach my $file (@$files) {
 1797: 	    if ($file =~ /\/portfolio\//) {
 1798:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1799:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1800:     	        $file_disp = "$name.$ext";
 1801:     	        $file = $file_path.$file_disp;
 1802:     	        $result.=&mt('Return commented version of [_1] to student.',
 1803:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1804:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1805:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1806:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1807:     	        $file_counter++;
 1808: 	    }
 1809: 	}
 1810:     }
 1811:     return $result;    
 1812: }
 1813: 
 1814: sub show_problem {
 1815:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1816:     my $rendered;
 1817:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1818:     &Apache::lonxml::remember_problem_counter();
 1819:     if ($mode eq 'both' or $mode eq 'text') {
 1820: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1821: 						       $env{'request.course.id'},
 1822: 						       undef,\%form);
 1823:     }
 1824:     if ($removeform) {
 1825: 	$rendered=~s|<form(.*?)>||g;
 1826: 	$rendered=~s|</form>||g;
 1827: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1828:     }
 1829:     my $companswer;
 1830:     if ($mode eq 'both' or $mode eq 'answer') {
 1831: 	&Apache::lonxml::restore_problem_counter();
 1832: 	$companswer=
 1833: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1834: 						    $env{'request.course.id'},
 1835: 						    %form);
 1836:     }
 1837:     if ($removeform) {
 1838: 	$companswer=~s|<form(.*?)>||g;
 1839: 	$companswer=~s|</form>||g;
 1840: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1841:     }
 1842:     $rendered=
 1843: 	'<div class="LC_grade_show_problem_header">'.
 1844: 	&mt('View of the problem').
 1845: 	'</div><div class="LC_grade_show_problem_problem">'.
 1846: 	$rendered.
 1847: 	'</div>';
 1848:     $companswer=
 1849: 	'<div class="LC_grade_show_problem_header">'.
 1850: 	&mt('Correct answer').
 1851: 	'</div><div class="LC_grade_show_problem_problem">'.
 1852: 	$companswer.
 1853: 	'</div>';
 1854:     my $result;
 1855:     if ($mode eq 'both') {
 1856: 	$result=$rendered.$companswer;
 1857:     } elsif ($mode eq 'text') {
 1858: 	$result=$rendered;
 1859:     } elsif ($mode eq 'answer') {
 1860: 	$result=$companswer;
 1861:     }
 1862:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1863:     return $result;
 1864: }
 1865: 
 1866: sub files_exist {
 1867:     my ($r, $symb) = @_;
 1868:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1869: 
 1870:     foreach my $student (@students) {
 1871:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1872:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1873: 					      $udom,$uname);
 1874:         my ($string,$timestamp)= &get_last_submission(\%record);
 1875:         foreach my $submission (@$string) {
 1876:             my ($partid,$respid) =
 1877: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1878:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1879: 					   \%record);
 1880:             return 1 if (@$files);
 1881:         }
 1882:     }
 1883:     return 0;
 1884: }
 1885: 
 1886: sub download_all_link {
 1887:     my ($r,$symb) = @_;
 1888:     my $all_students = 
 1889: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1890: 
 1891:     my $parts =
 1892: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1893: 
 1894:     my $identifier = &Apache::loncommon::get_cgi_id();
 1895:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1896:                              'cgi.'.$identifier.'.symb' => $symb,
 1897:                              'cgi.'.$identifier.'.parts' => $parts,});
 1898:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1899: 	      &mt('Download All Submitted Documents').'</a>');
 1900:     return
 1901: }
 1902: 
 1903: sub build_section_inputs {
 1904:     my $section_inputs;
 1905:     if ($env{'form.section'} eq '') {
 1906:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1907:     } else {
 1908:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1909:         foreach my $section (@sections) {
 1910:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1911:         }
 1912:     }
 1913:     return $section_inputs;
 1914: }
 1915: 
 1916: # --------------------------- show submissions of a student, option to grade 
 1917: sub submission {
 1918:     my ($request,$counter,$total) = @_;
 1919:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1920:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1921:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1922:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1923:     my $symb = &get_symb($request); 
 1924:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1925: 
 1926:     if (!&canview($usec)) {
 1927: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1928: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1929: 			$env{'request.course.id'}.')</span>');
 1930: 	$request->print(&show_grading_menu_form($symb));
 1931: 	return;
 1932:     }
 1933: 
 1934:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1935:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1936:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1937:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1938:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1939: 	'" src="'.$request->dir_config('lonIconsURL').
 1940: 	'/check.gif" height="16" border="0" />';
 1941: 
 1942:     my %old_essays;
 1943:     # header info
 1944:     if ($counter == 0) {
 1945: 	&sub_page_js($request);
 1946: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1947: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1948: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1949: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1950: 	    &download_all_link($request, $symb);
 1951: 	}
 1952: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1953: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1954: 
 1955: 	# option to display problem, only once else it cause problems 
 1956:         # with the form later since the problem has a form.
 1957: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1958: 	    my $mode;
 1959: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1960: 		$mode='both';
 1961: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1962: 		$mode='text';
 1963: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1964: 		$mode='answer';
 1965: 	    }
 1966: 	    &Apache::lonxml::clear_problem_counter();
 1967: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1968: 	}
 1969: 
 1970: 	# kwclr is the only variable that is guaranteed to be non blank 
 1971:         # if this subroutine has been called once.
 1972: 	my %keyhash = ();
 1973: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1974: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1975: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1976: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1977: 
 1978: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1979: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1980: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1981: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1982: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1983: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1984: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1985: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1986: 	}
 1987: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1988: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1989: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1990: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1991: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1992: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1993: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1994: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1995: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1996: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1997: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1998: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1999: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2000: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2001: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2002: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2003: 			&build_section_inputs().
 2004: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2005: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2006: 			'<input type="hidden" name="NCT"'.
 2007: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2008: 	if ($env{'form.handgrade'} eq 'yes') {
 2009: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2010: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2011: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2012: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2013: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2014: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2015: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2016: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2017: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2018: 	    }
 2019: 	}
 2020: 	
 2021: 	my ($cts,$prnmsg) = (1,'');
 2022: 	while ($cts <= $env{'form.savemsgN'}) {
 2023: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2024: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2025: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2026: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2027: 		'" />'."\n".
 2028: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2029: 	    $cts++;
 2030: 	}
 2031: 	$request->print($prnmsg);
 2032: 
 2033: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2034: #
 2035: # Print out the keyword options line
 2036: #
 2037: 	    $request->print(<<KEYWORDS);
 2038: &nbsp;<b>Keyword Options:</b>&nbsp;
 2039: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2040: <a href="#" onMouseDown="javascript:getSel(); return false"
 2041:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2042: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2043: KEYWORDS
 2044: #
 2045: # Load the other essays for similarity check
 2046: #
 2047:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2048: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2049: 	    $apath=&escape($apath);
 2050: 	    $apath=~s/\W/\_/gs;
 2051: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2052:         }
 2053:     }
 2054: 
 2055: # This is where output for one specific student would start
 2056:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2057:     $request->print("\n\n".
 2058:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2059: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2060: 		    '<div class="LC_grade_show_user_body">'."\n");
 2061: 
 2062:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2063: 	my $mode;
 2064: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2065: 	    $mode='both';
 2066: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2067: 	    $mode='text';
 2068: 	} elsif ($env{'form.vAns'} eq 'all') {
 2069: 	    $mode='answer';
 2070: 	}
 2071: 	&Apache::lonxml::clear_problem_counter();
 2072: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2073:     }
 2074: 
 2075:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2076:     my $res_error;
 2077:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2078:     if ($res_error) {
 2079:         $request->print(&navmap_errormsg());
 2080:         return;
 2081:     }
 2082: 
 2083:     # Display student info
 2084:     $request->print(($counter == 0 ? '' : '<br />'));
 2085:     my $result='<div class="LC_grade_submissions">';
 2086:     
 2087:     $result.='<div class="LC_grade_submissions_header">';
 2088:     $result.= &mt('Submissions');
 2089:     $result.='<input type="hidden" name="name'.$counter.
 2090: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2091:     if ($env{'form.handgrade'} eq 'no') {
 2092: 	$result.='<span class="LC_grade_check_note">'.
 2093: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2094: 
 2095:     }
 2096: 
 2097: 
 2098: 
 2099:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2100:     my $fullname;
 2101:     my $col_fullnames = [];
 2102:     if ($env{'form.handgrade'} eq 'yes') {
 2103: 	(my $sub_result,$fullname,$col_fullnames)=
 2104: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2105: 				 $counter);
 2106: 	$result.=$sub_result;
 2107:     }
 2108:     $request->print($result."\n");
 2109:     $request->print('</div>'."\n");
 2110:     # print student answer/submission
 2111:     # Options are (1) Handgaded submission only
 2112:     #             (2) Last submission, includes submission that is not handgraded 
 2113:     #                  (for multi-response type part)
 2114:     #             (3) Last submission plus the parts info
 2115:     #             (4) The whole record for this student
 2116:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2117: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2118: 	
 2119: 	my $lastsubonly;
 2120: 
 2121: 	if ($$timestamp eq '') {
 2122: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2123: 	} else {
 2124: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2125: 
 2126: 	    my %seenparts;
 2127: 	    my @part_response_id = &flatten_responseType($responseType);
 2128: 	    foreach my $part (@part_response_id) {
 2129: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2130: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2131: 
 2132: 		my ($partid,$respid) = @{ $part };
 2133: 		my $display_part=&get_display_part($partid,$symb);
 2134: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2135: 		    if (exists($seenparts{$partid})) { next; }
 2136: 		    $seenparts{$partid}=1;
 2137: 		    my $submitby='<b>Part:</b> '.$display_part.
 2138: 			' <b>Collaborative submission by:</b> '.
 2139: 			'<a href="javascript:viewSubmitter(\''.
 2140: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2141: 			'\');" target="_self">'.
 2142: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2143: 		    $request->print($submitby);
 2144: 		    next;
 2145: 		}
 2146: 		my $responsetype = $responseType->{$partid}->{$respid};
 2147: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2148:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
 2149:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2150:                         ' <span class="LC_internal_info">'.
 2151:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
 2152:                         '</span>&nbsp; &nbsp;'.
 2153: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2154: 		    next;
 2155: 		}
 2156: 		foreach my $submission (@$string) {
 2157: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2158: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2159: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2160: 		    # Similarity check
 2161: 		    my $similar='';
 2162: 		    if($env{'form.checkPlag'}){
 2163: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2164: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2165: 			if ($osim) {
 2166: 			    $osim=int($osim*100.0);
 2167: 			    my %old_course_desc = 
 2168: 				&Apache::lonnet::coursedescription($ocrsid,
 2169: 								   {'one_time' => 1});
 2170: 
 2171: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2172: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2173: 				    $osim,
 2174: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2175: 				    $old_course_desc{'description'},
 2176: 				    $old_course_desc{'num'},
 2177: 				    $old_course_desc{'domain'}).
 2178: 				'</span></h3><blockquote><i>'.
 2179: 				&keywords_highlight($oessay).
 2180: 				'</i></blockquote><hr />';
 2181: 			}
 2182: 		    }
 2183: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2184: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2185: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2186: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2187: 			my $display_part=&get_display_part($partid,$symb);
 2188:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
 2189:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
 2190:                             ' <span class="LC_internal_info">'.
 2191:                             '('.&mt('Part ID: [_1]',$respid).')'.
 2192:                             '</b></span>&nbsp; &nbsp;';
 2193: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2194: 			if (@$files) {
 2195: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2196: 			    my $file_counter = 0;
 2197: 			    foreach my $file (@$files) {
 2198: 			        $file_counter++;
 2199: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2200: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2201: 			    }
 2202: 			    $lastsubonly.='<br />';
 2203: 			}
 2204: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2205: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2206: 					 $respid,\%record,$order,undef,$uname,$udom);
 2207: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2208: 			$lastsubonly.='</div>';
 2209: 		    }
 2210: 		}
 2211: 	    }
 2212: 	    $lastsubonly.='</div>'."\n";
 2213: 	}
 2214: 	$request->print($lastsubonly);
 2215:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2216: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2217: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2218:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2219: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2220: 								 $env{'request.course.id'},
 2221: 								 $last,'.submission',
 2222: 								 'Apache::grades::keywords_highlight'));
 2223:     }
 2224: 
 2225:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2226: 	.$udom.'" />'."\n");
 2227:     # return if view submission with no grading option
 2228:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2229: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2230: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2231: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2232: 	$toGrade.='</div>'."\n";
 2233: 	if (($env{'form.command'} eq 'submission') || 
 2234: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2235: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2236: 	}
 2237: 	$request->print($toGrade);
 2238: 	return;
 2239:     } else {
 2240: 	$request->print('</div>'."\n");
 2241:     }
 2242: 
 2243:     # essay grading message center
 2244:     if ($env{'form.handgrade'} eq 'yes') {
 2245: 	my $result='<div class="LC_grade_message_center">';
 2246:     
 2247: 	$result.='<div class="LC_grade_message_center_header">'.
 2248: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2249: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2250: 	my $msgfor = $givenn.' '.$lastname;
 2251: 	if (scalar(@$col_fullnames) > 0) {
 2252: 	    my $lastone = pop(@$col_fullnames);
 2253: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2254: 	}
 2255: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2256: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2257: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2258: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2259: 	    ',\''.$msgfor.'\');" target="_self">'.
 2260: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2261: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2262: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2263: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2264: 	    '<br />&nbsp;('.
 2265: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2266: 	$result.='</div></div>';
 2267: 	$request->print($result);
 2268:     }
 2269: 
 2270:     my %seen = ();
 2271:     my @partlist;
 2272:     my @gradePartRespid;
 2273:     my @part_response_id = &flatten_responseType($responseType);
 2274:     $request->print('<div class="LC_grade_assign">'.
 2275: 		    
 2276: 		    '<div class="LC_grade_assign_header">'.
 2277: 		    &mt('Assign Grades').'</div>'.
 2278: 		    '<div class="LC_grade_assign_body">');
 2279:     foreach my $part_response_id (@part_response_id) {
 2280:     	my ($partid,$respid) = @{ $part_response_id };
 2281: 	my $part_resp = join('_',@{ $part_response_id });
 2282: 	next if ($seen{$partid} > 0);
 2283: 	$seen{$partid}++;
 2284: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2285: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2286: 	push(@partlist,$partid);
 2287: 	push(@gradePartRespid,$partid.'.'.$respid);
 2288: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2289:     }
 2290:     $request->print('</div></div>');
 2291: 
 2292:     $request->print('<div class="LC_grade_info_links">');
 2293:     if ($perm{'vgr'}) {
 2294: 	$request->print(
 2295: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2296: 						   $uname,$udom,'check'));
 2297:     }
 2298:     if ($perm{'opa'}) {
 2299: 	$request->print(
 2300: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2301: 					 $uname,$udom,$symb,'check'));
 2302:     }
 2303:     $request->print('</div>');
 2304: 
 2305:     $result='<input type="hidden" name="partlist'.$counter.
 2306: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2307:     $result.='<input type="hidden" name="gradePartRespid'.
 2308: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2309:     my $ctr = 0;
 2310:     while ($ctr < scalar(@partlist)) {
 2311: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2312: 	    $partlist[$ctr].'" />'."\n";
 2313: 	$ctr++;
 2314:     }
 2315:     $request->print($result.''."\n");
 2316: 
 2317: # Done with printing info for one student
 2318: 
 2319:     $request->print('</div>');#LC_grade_show_user_body
 2320:     $request->print('</div>');#LC_grade_show_user
 2321: 
 2322: 
 2323:     # print end of form
 2324:     if ($counter == $total) {
 2325: 	my $endform='<table border="0"><tr><td>'."\n";
 2326: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2327: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2328: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2329: 	my $ntstu ='<select name="NTSTU">'.
 2330: 	    '<option>1</option><option>2</option>'.
 2331: 	    '<option>3</option><option>5</option>'.
 2332: 	    '<option>7</option><option>10</option></select>'."\n";
 2333: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2334: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2335:         $endform.=&mt('[_1]student(s)',$ntstu);
 2336: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2337: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2338: 	    '<input type="button" value="'.&mt('Next').'" '.
 2339: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2340: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2341:         $endform.="<input type='hidden' value='".&get_increment().
 2342:             "' name='increment' />";
 2343: 	$endform.='</td></tr></table></form>';
 2344: 	$endform.=&show_grading_menu_form($symb);
 2345: 	$request->print($endform);
 2346:     }
 2347:     return '';
 2348: }
 2349: 
 2350: sub check_collaborators {
 2351:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2352:     my ($result,@col_fullnames);
 2353:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2354:     foreach my $part (keys(%$handgrade)) {
 2355: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2356: 					'.maxcollaborators',
 2357: 					$symb,$udom,$uname);
 2358: 	next if ($ncol <= 0);
 2359: 	$part =~ s/\_/\./g;
 2360: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2361: 	my (@good_collaborators, @bad_collaborators);
 2362: 	foreach my $possible_collaborator
 2363: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2364: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2365: 	    next if ($possible_collaborator eq '');
 2366: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2367: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2368: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2369: 	    # Doing this grep allows 'fuzzy' specification
 2370: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2371: 			       keys(%$classlist));
 2372: 	    if (! scalar(@matches)) {
 2373: 		push(@bad_collaborators, $possible_collaborator);
 2374: 	    } else {
 2375: 		push(@good_collaborators, @matches);
 2376: 	    }
 2377: 	}
 2378: 	if (scalar(@good_collaborators) != 0) {
 2379: 	    $result.='<br />'.&mt('Collaborators: ');
 2380: 	    foreach my $name (@good_collaborators) {
 2381: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2382: 		push(@col_fullnames, $givenn.' '.$lastname);
 2383: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2384: 	    }
 2385: 	    $result.='<br />'."\n";
 2386: 	    my ($part)=split(/\./,$part);
 2387: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2388: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2389: 		"\n";
 2390: 	}
 2391: 	if (scalar(@bad_collaborators) > 0) {
 2392: 	    $result.='<div class="LC_warning">';
 2393: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2394: 	    $result .= '</div>';
 2395: 	}         
 2396: 	if (scalar(@bad_collaborators > $ncol)) {
 2397: 	    $result .= '<div class="LC_warning">';
 2398: 	    $result .= &mt('This student has submitted too many '.
 2399: 		'collaborators.  Maximum is [_1].',$ncol);
 2400: 	    $result .= '</div>';
 2401: 	}
 2402:     }
 2403:     return ($result,$fullname,\@col_fullnames);
 2404: }
 2405: 
 2406: #--- Retrieve the last submission for all the parts
 2407: sub get_last_submission {
 2408:     my ($returnhash)=@_;
 2409:     my (@string,$timestamp);
 2410:     if ($$returnhash{'version'}) {
 2411: 	my %lasthash=();
 2412: 	my ($version);
 2413: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2414: 	    foreach my $key (sort(split(/\:/,
 2415: 					$$returnhash{$version.':keys'}))) {
 2416: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2417: 		$timestamp = 
 2418: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2419: 	    }
 2420: 	}
 2421: 	foreach my $key (keys(%lasthash)) {
 2422: 	    next if ($key !~ /\.submission$/);
 2423: 
 2424: 	    my ($partid,$foo) = split(/submission$/,$key);
 2425: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2426: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2427: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2428: 	}
 2429:     }
 2430:     if (!@string) {
 2431: 	$string[0] =
 2432: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2433:     }
 2434:     return (\@string,\$timestamp);
 2435: }
 2436: 
 2437: #--- High light keywords, with style choosen by user.
 2438: sub keywords_highlight {
 2439:     my $string    = shift;
 2440:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2441:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2442:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2443:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2444:     foreach my $keyword (@keylist) {
 2445: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2446:     }
 2447:     return $string;
 2448: }
 2449: 
 2450: #--- Called from submission routine
 2451: sub processHandGrade {
 2452:     my ($request) = shift;
 2453:     my $symb   = &get_symb($request);
 2454:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2455:     my $button = $env{'form.gradeOpt'};
 2456:     my $ngrade = $env{'form.NCT'};
 2457:     my $ntstu  = $env{'form.NTSTU'};
 2458:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2459:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2460: 
 2461:     if ($button eq 'Save & Next') {
 2462: 	my $ctr = 0;
 2463: 	while ($ctr < $ngrade) {
 2464: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2465: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2466: 	    if ($errorflag eq 'no_score') {
 2467: 		$ctr++;
 2468: 		next;
 2469: 	    }
 2470: 	    if ($errorflag eq 'not_allowed') {
 2471: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2472: 		$ctr++;
 2473: 		next;
 2474: 	    }
 2475: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2476: 	    my ($subject,$message,$msgstatus) = ('','','');
 2477: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2478:             my ($feedurl,$showsymb) =
 2479: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2480: 	    my $messagetail;
 2481: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2482: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2483: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2484: 		$subject.=' ['.$restitle.']';
 2485: 		my (@msgnum) = split(/,/,$includemsg);
 2486: 		foreach (@msgnum) {
 2487: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2488: 		}
 2489: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2490: 		if ($env{'form.withgrades'.$ctr}) {
 2491: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2492: 		    $messagetail = " for <a href=\"".
 2493: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2494: 		}
 2495: 		$msgstatus = 
 2496:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2497: 						     $message.$messagetail,
 2498:                                                      undef,$feedurl,undef,
 2499:                                                      undef,undef,$showsymb,
 2500:                                                      $restitle);
 2501: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2502: 				$msgstatus);
 2503: 	    }
 2504: 	    if ($env{'form.collaborator'.$ctr}) {
 2505: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2506: 		foreach my $collabstr (@collabstrs) {
 2507: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2508: 		    foreach my $collaborator (@collaborators) {
 2509: 			my ($errorflag,$pts,$wgt) = 
 2510: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2511: 					   $env{'form.unamedom'.$ctr},$part);
 2512: 			if ($errorflag eq 'not_allowed') {
 2513: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2514: 			    next;
 2515: 			} elsif ($message ne '') {
 2516: 			    my ($baseurl,$showsymb) = 
 2517: 				&get_feedurl_and_symb($symb,$collaborator,
 2518: 						      $udom);
 2519: 			    if ($env{'form.withgrades'.$ctr}) {
 2520: 				$messagetail = " for <a href=\"".
 2521:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2522: 			    }
 2523: 			    $msgstatus = 
 2524: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2525: 			}
 2526: 		    }
 2527: 		}
 2528: 	    }
 2529: 	    $ctr++;
 2530: 	}
 2531:     }
 2532: 
 2533:     if ($env{'form.handgrade'} eq 'yes') {
 2534: 	# Keywords sorted in alphabatical order
 2535: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2536: 	my %keyhash = ();
 2537: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2538: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2539: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2540: 	$env{'form.keywords'} = join(' ',@keywords);
 2541: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2542: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2543: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2544: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2545: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2546: 
 2547: 	# message center - Order of message gets changed. Blank line is eliminated.
 2548: 	# New messages are saved in env for the next student.
 2549: 	# All messages are saved in nohist_handgrade.db
 2550: 	my ($ctr,$idx) = (1,1);
 2551: 	while ($ctr <= $env{'form.savemsgN'}) {
 2552: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2553: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2554: 		$idx++;
 2555: 	    }
 2556: 	    $ctr++;
 2557: 	}
 2558: 	$ctr = 0;
 2559: 	while ($ctr < $ngrade) {
 2560: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2561: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2562: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2563: 		$idx++;
 2564: 	    }
 2565: 	    $ctr++;
 2566: 	}
 2567: 	$env{'form.savemsgN'} = --$idx;
 2568: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2569: 	my $putresult = &Apache::lonnet::put
 2570: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2571:     }
 2572:     # Called by Save & Refresh from Highlight Attribute Window
 2573:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2574:     if ($env{'form.refresh'} eq 'on') {
 2575: 	my ($ctr,$total) = (0,0);
 2576: 	while ($ctr < $ngrade) {
 2577: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2578: 	    $ctr++;
 2579: 	}
 2580: 	$env{'form.NTSTU'}=$ngrade;
 2581: 	$ctr = 0;
 2582: 	while ($ctr < $total) {
 2583: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2584: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2585: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2586: 	    &submission($request,$ctr,$total-1);
 2587: 	    $ctr++;
 2588: 	}
 2589: 	return '';
 2590:     }
 2591: 
 2592: # Go directly to grade student - from submission or link from chart page
 2593:     if ($button eq 'Grade Student') {
 2594: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2595: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2596: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2597: 	$env{'form.fullname'} = $$fullname{$processUser};
 2598: 	&submission($request,0,0);
 2599: 	return '';
 2600:     }
 2601: 
 2602:     # Get the next/previous one or group of students
 2603:     my $firststu = $env{'form.unamedom0'};
 2604:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2605:     my $ctr = 2;
 2606:     while ($laststu eq '') {
 2607: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2608: 	$ctr++;
 2609: 	$laststu = $firststu if ($ctr > $ngrade);
 2610:     }
 2611: 
 2612:     my (@parsedlist,@nextlist);
 2613:     my ($nextflg) = 0;
 2614:     foreach my $item (sort 
 2615: 	     {
 2616: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2617: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2618: 		 }
 2619: 		 return $a cmp $b;
 2620: 	     } (keys(%$fullname))) {
 2621: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2622: 	    push(@parsedlist,$item);
 2623: 	}
 2624: 	$nextflg = 1 if ($item eq $laststu);
 2625: 	if ($button eq 'Previous') {
 2626: 	    last if ($item eq $firststu);
 2627: 	    push(@parsedlist,$item);
 2628: 	}
 2629:     }
 2630:     $ctr = 0;
 2631:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2632:     my $res_error;
 2633:     my ($partlist) = &response_type($symb,\$res_error);
 2634:     if ($res_error) {
 2635:         $request->print(&navmap_errormsg());
 2636:         return;
 2637:     }
 2638:     foreach my $student (@parsedlist) {
 2639: 	my $submitonly=$env{'form.submitonly'};
 2640: 	my ($uname,$udom) = split(/:/,$student);
 2641: 	
 2642: 	if ($submitonly eq 'queued') {
 2643: 	    my %queue_status = 
 2644: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2645: 							$udom,$uname);
 2646: 	    next if (!defined($queue_status{'gradingqueue'}));
 2647: 	}
 2648: 
 2649: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2650: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2651: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2652: 	    my $submitted = 0;
 2653: 	    my $ungraded = 0;
 2654: 	    my $incorrect = 0;
 2655: 	    foreach my $item (keys(%status)) {
 2656: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2657: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2658: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2659: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2660: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2661: 		    $submitted = 0;
 2662: 		}
 2663: 	    }
 2664: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2665: 				     $submitonly eq 'incorrect' ||
 2666: 				     $submitonly eq 'graded'));
 2667: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2668: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2669: 	}
 2670: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2671: 	last if ($ctr == $ntstu);
 2672: 	$ctr++;
 2673:     }
 2674: 
 2675:     $ctr = 0;
 2676:     my $total = scalar(@nextlist)-1;
 2677: 
 2678:     foreach (sort(@nextlist)) {
 2679: 	my ($uname,$udom,$submitter) = split(/:/);
 2680: 	$env{'form.student'}  = $uname;
 2681: 	$env{'form.userdom'}  = $udom;
 2682: 	$env{'form.fullname'} = $$fullname{$_};
 2683: 	&submission($request,$ctr,$total);
 2684: 	$ctr++;
 2685:     }
 2686:     if ($total < 0) {
 2687: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2688: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2689: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2690: 	$the_end.=&show_grading_menu_form($symb);
 2691: 	$request->print($the_end);
 2692:     }
 2693:     return '';
 2694: }
 2695: 
 2696: #---- Save the score and award for each student, if changed
 2697: sub saveHandGrade {
 2698:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2699:     my @version_parts;
 2700:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2701: 					   $env{'request.course.id'});
 2702:     if (!&canmodify($usec)) { return('not_allowed'); }
 2703:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2704:     my @parts_graded;
 2705:     my %newrecord  = ();
 2706:     my ($pts,$wgt) = ('','');
 2707:     my %aggregate = ();
 2708:     my $aggregateflag = 0;
 2709:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2710:     foreach my $new_part (@parts) {
 2711: 	#collaborator ($submi may vary for different parts
 2712: 	if ($submitter && $new_part ne $part) { next; }
 2713: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2714: 	if ($dropMenu eq 'excused') {
 2715: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2716: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2717: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2718: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2719: 		}
 2720: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2721: 	    }
 2722: 	} elsif ($dropMenu eq 'reset status'
 2723: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2724: 	    foreach my $key (keys(%record)) {
 2725: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2726: 	    }
 2727: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2728: 		"$env{'user.name'}:$env{'user.domain'}";
 2729:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2730: 
 2731:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2732: 					       [$new_part]);
 2733:             my $aggtries =$totaltries;
 2734:             if ($last_resets{$new_part}) {
 2735:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2736: 					   $new_part);
 2737:             }
 2738: 
 2739:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2740:             if ($aggtries > 0) {
 2741:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2742:                 $aggregateflag = 1;
 2743:             }
 2744: 	} elsif ($dropMenu eq '') {
 2745: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2746: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2747: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2748: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2749: 		next;
 2750: 	    }
 2751: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2752: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2753: 	    my $partial= $pts/$wgt;
 2754: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2755: 		#do not update score for part if not changed.
 2756:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2757: 		next;
 2758: 	    } else {
 2759: 	        push(@parts_graded,$new_part);
 2760: 	    }
 2761: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2762: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2763: 	    }
 2764: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2765: 	    if ($partial == 0) {
 2766: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2767: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2768: 		}
 2769: 	    } else {
 2770: 		if ($record{$reckey} ne 'correct_by_override') {
 2771: 		    $newrecord{$reckey} = 'correct_by_override';
 2772: 		}
 2773: 	    }	    
 2774: 	    if ($submitter && 
 2775: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2776: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2777: 	    }
 2778: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2779: 		"$env{'user.name'}:$env{'user.domain'}";
 2780: 	}
 2781: 	# unless problem has been graded, set flag to version the submitted files
 2782: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2783: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2784: 	        $dropMenu eq 'reset status')
 2785: 	   {
 2786: 	    push(@version_parts,$new_part);
 2787: 	}
 2788:     }
 2789:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2790:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2791: 
 2792:     if (%newrecord) {
 2793:         if (@version_parts) {
 2794:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2795:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2796: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2797: 	    foreach my $new_part (@version_parts) {
 2798: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2799: 				$new_part,\%newrecord);
 2800: 	    }
 2801:         }
 2802: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2803: 				$env{'request.course.id'},$domain,$stuname);
 2804: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2805: 				     $cdom,$cnum,$domain,$stuname);
 2806:     }
 2807:     if ($aggregateflag) {
 2808:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2809: 			      $cdom,$cnum);
 2810:     }
 2811:     return ('',$pts,$wgt);
 2812: }
 2813: 
 2814: sub check_and_remove_from_queue {
 2815:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2816:     my @ungraded_parts;
 2817:     foreach my $part (@{$parts}) {
 2818: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2819: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2820: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2821: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2822: 		) {
 2823: 	    push(@ungraded_parts, $part);
 2824: 	}
 2825:     }
 2826:     if ( !@ungraded_parts ) {
 2827: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2828: 					       $cnum,$domain,$stuname);
 2829:     }
 2830: }
 2831: 
 2832: sub handback_files {
 2833:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2834:     my $portfolio_root = '/userfiles/portfolio';
 2835:     my $res_error;
 2836:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2837:     if ($res_error) {
 2838:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2839:         return;
 2840:     }
 2841:     my @part_response_id = &flatten_responseType($responseType);
 2842:     foreach my $part_response_id (@part_response_id) {
 2843:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2844: 	my $part_resp = join('_',@{ $part_response_id });
 2845:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2846:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2847:                 my $file_counter = 1;
 2848: 		my $file_msg;
 2849:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2850:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2851:                     my ($directory,$answer_file) = 
 2852:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2853:                     my ($answer_name,$answer_ver,$answer_ext) =
 2854: 		        &file_name_version_ext($answer_file);
 2855: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2856:                     my $getpropath = 1;
 2857: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2858: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2859:                     # fix file name
 2860:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2861:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2862:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2863:             	                                $save_file_name);
 2864:                     if ($result !~ m|^/uploaded/|) {
 2865:                         $request->print('<br /><span class="LC_error">'.
 2866:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2867:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2868:                                         '</span>');
 2869:                     } else {
 2870:                         # mark the file as read only
 2871:                         my @files = ($save_file_name);
 2872:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2873:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2874: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2875: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2876: 			}
 2877:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2878: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2879: 
 2880:                     }
 2881:                     $request->print("<br />".$fname." will be the uploaded file name");
 2882:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2883:                     $file_counter++;
 2884:                 }
 2885: 		my $subject = "File Handed Back by Instructor ";
 2886: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2887: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2888: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2889: 		$message .= " and can be found in your portfolio space.";
 2890: 		my ($feedurl,$showsymb) = 
 2891: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2892:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2893: 		my $msgstatus = 
 2894:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2895: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2896:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2897:             }
 2898:         }
 2899:     return;
 2900: }
 2901: 
 2902: sub get_feedurl_and_symb {
 2903:     my ($symb,$uname,$udom) = @_;
 2904:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2905:     $url = &Apache::lonnet::clutter($url);
 2906:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2907: 					$symb,$udom,$uname);
 2908:     if ($encrypturl =~ /^yes$/i) {
 2909: 	&Apache::lonenc::encrypted(\$url,1);
 2910: 	&Apache::lonenc::encrypted(\$symb,1);
 2911:     }
 2912:     return ($url,$symb);
 2913: }
 2914: 
 2915: sub get_submitted_files {
 2916:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2917:     my @files;
 2918:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2919:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2920:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2921:     	    push(@files,$file_url.$file);
 2922:         }
 2923:     }
 2924:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2925:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2926:     }
 2927:     return (\@files);
 2928: }
 2929: 
 2930: # ----------- Provides number of tries since last reset.
 2931: sub get_num_tries {
 2932:     my ($record,$last_reset,$part) = @_;
 2933:     my $timestamp = '';
 2934:     my $num_tries = 0;
 2935:     if ($$record{'version'}) {
 2936:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2937:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2938:                 $timestamp = $$record{$version.':timestamp'};
 2939:                 if ($timestamp > $last_reset) {
 2940:                     $num_tries ++;
 2941:                 } else {
 2942:                     last;
 2943:                 }
 2944:             }
 2945:         }
 2946:     }
 2947:     return $num_tries;
 2948: }
 2949: 
 2950: # ----------- Determine decrements required in aggregate totals 
 2951: sub decrement_aggs {
 2952:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2953:     my %decrement = (
 2954:                         attempts => 0,
 2955:                         users => 0,
 2956:                         correct => 0
 2957:                     );
 2958:     $decrement{'attempts'} = $aggtries;
 2959:     if ($solvedstatus =~ /^correct/) {
 2960:         $decrement{'correct'} = 1;
 2961:     }
 2962:     if ($aggtries == $totaltries) {
 2963:         $decrement{'users'} = 1;
 2964:     }
 2965:     foreach my $type (keys(%decrement)) {
 2966:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2967:     }
 2968:     return;
 2969: }
 2970: 
 2971: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2972: sub get_last_resets {
 2973:     my ($symb,$courseid,$partids) =@_;
 2974:     my %last_resets;
 2975:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2976:     my $cname = $env{'course.'.$courseid.'.num'};
 2977:     my @keys;
 2978:     foreach my $part (@{$partids}) {
 2979: 	push(@keys,"$symb\0$part\0resettime");
 2980:     }
 2981:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2982: 				     $cdom,$cname);
 2983:     foreach my $part (@{$partids}) {
 2984: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2985:     }
 2986:     return %last_resets;
 2987: }
 2988: 
 2989: # ----------- Handles creating versions for portfolio files as answers
 2990: sub version_portfiles {
 2991:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2992:     my $version_parts = join('|',@$v_flag);
 2993:     my @returned_keys;
 2994:     my $parts = join('|', @$parts_graded);
 2995:     my $portfolio_root = '/userfiles/portfolio';
 2996:     foreach my $key (keys(%$record)) {
 2997:         my $new_portfiles;
 2998:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2999:             my @versioned_portfiles;
 3000:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3001:             foreach my $file (@portfiles) {
 3002:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3003:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3004: 		my ($answer_name,$answer_ver,$answer_ext) =
 3005: 		    &file_name_version_ext($answer_file);
 3006:                 my $getpropath = 1;    
 3007:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3008:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3009:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3010:                 if ($new_answer ne 'problem getting file') {
 3011:                     push(@versioned_portfiles, $directory.$new_answer);
 3012:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3013:                         [$directory.$new_answer],
 3014:                         [$symb,$env{'request.course.id'},'graded']);
 3015:                 }
 3016:             }
 3017:             $$record{$key} = join(',',@versioned_portfiles);
 3018:             push(@returned_keys,$key);
 3019:         }
 3020:     } 
 3021:     return (@returned_keys);   
 3022: }
 3023: 
 3024: sub get_next_version {
 3025:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3026:     my $version;
 3027:     foreach my $row (@$dir_list) {
 3028:         my ($file) = split(/\&/,$row,2);
 3029:         my ($file_name,$file_version,$file_ext) =
 3030: 	    &file_name_version_ext($file);
 3031:         if (($file_name eq $answer_name) && 
 3032: 	    ($file_ext eq $answer_ext)) {
 3033:                 # gets here if filename and extension match, regardless of version
 3034:                 if ($file_version ne '') {
 3035:                 # a versioned file is found  so save it for later
 3036:                 if ($file_version > $version) {
 3037: 		    $version = $file_version;
 3038: 	        }
 3039:             }
 3040:         }
 3041:     } 
 3042:     $version ++;
 3043:     return($version);
 3044: }
 3045: 
 3046: sub version_selected_portfile {
 3047:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3048:     my ($answer_name,$answer_ver,$answer_ext) =
 3049:         &file_name_version_ext($file_name);
 3050:     my $new_answer;
 3051:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3052:     if($env{'form.copy'} eq '-1') {
 3053:         $new_answer = 'problem getting file';
 3054:     } else {
 3055:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3056:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3057:                             $stu_name,$domain,'copy',
 3058: 		        '/portfolio'.$directory.$new_answer);
 3059:     }    
 3060:     return ($new_answer);
 3061: }
 3062: 
 3063: sub file_name_version_ext {
 3064:     my ($file)=@_;
 3065:     my @file_parts = split(/\./, $file);
 3066:     my ($name,$version,$ext);
 3067:     if (@file_parts > 1) {
 3068: 	$ext=pop(@file_parts);
 3069: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3070: 	    $version=pop(@file_parts);
 3071: 	}
 3072: 	$name=join('.',@file_parts);
 3073:     } else {
 3074: 	$name=join('.',@file_parts);
 3075:     }
 3076:     return($name,$version,$ext);
 3077: }
 3078: 
 3079: #--------------------------------------------------------------------------------------
 3080: #
 3081: #-------------------------- Next few routines handles grading by section or whole class
 3082: #
 3083: #--- Javascript to handle grading by section or whole class
 3084: sub viewgrades_js {
 3085:     my ($request) = shift;
 3086: 
 3087:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3088:     $request->print(<<VIEWJAVASCRIPT);
 3089: <script type="text/javascript" language="javascript">
 3090:    function writePoint(partid,weight,point) {
 3091: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3092: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3093: 	if (point == "textval") {
 3094: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3095: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3096: 		alert("$alertmsg"+parseFloat(point));
 3097: 		var resetbox = false;
 3098: 		for (var i=0; i<radioButton.length; i++) {
 3099: 		    if (radioButton[i].checked) {
 3100: 			textbox.value = i;
 3101: 			resetbox = true;
 3102: 		    }
 3103: 		}
 3104: 		if (!resetbox) {
 3105: 		    textbox.value = "";
 3106: 		}
 3107: 		return;
 3108: 	    }
 3109: 	    if (parseFloat(point) > parseFloat(weight)) {
 3110: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3111: 				   ") greater than the weight for the part. Accept?");
 3112: 		if (resp == false) {
 3113: 		    textbox.value = "";
 3114: 		    return;
 3115: 		}
 3116: 	    }
 3117: 	    for (var i=0; i<radioButton.length; i++) {
 3118: 		radioButton[i].checked=false;
 3119: 		if (parseFloat(point) == i) {
 3120: 		    radioButton[i].checked=true;
 3121: 		}
 3122: 	    }
 3123: 
 3124: 	} else {
 3125: 	    textbox.value = parseFloat(point);
 3126: 	}
 3127: 	for (i=0;i<document.classgrade.total.value;i++) {
 3128: 	    var user = document.classgrade["ctr"+i].value;
 3129: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3130: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3131: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3132: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3133: 	    if (saveval != "correct") {
 3134: 		scorename.value = point;
 3135: 		if (selname[0].selected != true) {
 3136: 		    selname[0].selected = true;
 3137: 		}
 3138: 	    }
 3139: 	}
 3140: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3141:     }
 3142: 
 3143:     function writeRadText(partid,weight) {
 3144: 	var selval   = document.classgrade["SELVAL_"+partid];
 3145: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3146:         var override = document.classgrade["FORCE_"+partid].checked;
 3147: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3148: 	if (selval[1].selected || selval[2].selected) {
 3149: 	    for (var i=0; i<radioButton.length; i++) {
 3150: 		radioButton[i].checked=false;
 3151: 
 3152: 	    }
 3153: 	    textbox.value = "";
 3154: 
 3155: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3156: 		var user = document.classgrade["ctr"+i].value;
 3157: 		user = user.replace(new RegExp(':', 'g'),"_");
 3158: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3159: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3160: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3161: 		if ((saveval != "correct") || override) {
 3162: 		    scorename.value = "";
 3163: 		    if (selval[1].selected) {
 3164: 			selname[1].selected = true;
 3165: 		    } else {
 3166: 			selname[2].selected = true;
 3167: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3168: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3169: 		    }
 3170: 		}
 3171: 	    }
 3172: 	} else {
 3173: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3174: 		var user = document.classgrade["ctr"+i].value;
 3175: 		user = user.replace(new RegExp(':', 'g'),"_");
 3176: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3177: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3178: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3179: 		if ((saveval != "correct") || override) {
 3180: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3181: 		    selname[0].selected = true;
 3182: 		}
 3183: 	    }
 3184: 	}	    
 3185:     }
 3186: 
 3187:     function changeSelect(partid,user) {
 3188: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3189: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3190: 	var point  = textbox.value;
 3191: 	var weight = document.classgrade["weight_"+partid].value;
 3192: 
 3193: 	if (isNaN(point) || parseFloat(point) < 0) {
 3194: 	    alert("$alertmsg"+parseFloat(point));
 3195: 	    textbox.value = "";
 3196: 	    return;
 3197: 	}
 3198: 	if (parseFloat(point) > parseFloat(weight)) {
 3199: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3200: 			       ") greater than the weight of the part. Accept?");
 3201: 	    if (resp == false) {
 3202: 		textbox.value = "";
 3203: 		return;
 3204: 	    }
 3205: 	}
 3206: 	selval[0].selected = true;
 3207:     }
 3208: 
 3209:     function changeOneScore(partid,user) {
 3210: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3211: 	if (selval[1].selected || selval[2].selected) {
 3212: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3213: 	    if (selval[2].selected) {
 3214: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3215: 	    }
 3216:         }
 3217:     }
 3218: 
 3219:     function resetEntry(numpart) {
 3220: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3221: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3222: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3223: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3224: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3225: 	    for (var i=0; i<radioButton.length; i++) {
 3226: 		radioButton[i].checked=false;
 3227: 
 3228: 	    }
 3229: 	    textbox.value = "";
 3230: 	    selval[0].selected = true;
 3231: 
 3232: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3233: 		var user = document.classgrade["ctr"+i].value;
 3234: 		user = user.replace(new RegExp(':', 'g'),"_");
 3235: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3236: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3237: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3238: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3239: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3240: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3241: 		if (saveselval == "excused") {
 3242: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3243: 		} else {
 3244: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3245: 		}
 3246: 	    }
 3247: 	}
 3248:     }
 3249: 
 3250: </script>
 3251: VIEWJAVASCRIPT
 3252: }
 3253: 
 3254: #--- show scores for a section or whole class w/ option to change/update a score
 3255: sub viewgrades {
 3256:     my ($request) = shift;
 3257:     &viewgrades_js($request);
 3258: 
 3259:     my ($symb) = &get_symb($request);
 3260:     #need to make sure we have the correct data for later EXT calls, 
 3261:     #thus invalidate the cache
 3262:     &Apache::lonnet::devalidatecourseresdata(
 3263:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3264:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3265:     &Apache::lonnet::clear_EXT_cache_status();
 3266: 
 3267:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3268:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3269: 
 3270:     #view individual student submission form - called using Javascript viewOneStudent
 3271:     $result.=&jscriptNform($symb);
 3272: 
 3273:     #beginning of class grading form
 3274:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3275:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3276: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3277: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3278: 	&build_section_inputs().
 3279: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3280: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3281: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3282: 
 3283:     my ($common_header,$specific_header);
 3284:     if ($env{'form.section'} eq 'all') {
 3285: 	$common_header = &mt('Assign Common Grade to Class');
 3286:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3287:     } elsif ($env{'form.section'} eq 'none') {
 3288:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3289: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3290:     } else {
 3291:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3292:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3293: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3294:     }
 3295:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3296:     #radio buttons/text box for assigning points for a section or class.
 3297:     #handles different parts of a problem
 3298:     my $res_error;
 3299:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3300:     if ($res_error) {
 3301:         return &navmap_errormsg();
 3302:     }
 3303:     my %weight = ();
 3304:     my $ctsparts = 0;
 3305:     my %seen = ();
 3306:     my @part_response_id = &flatten_responseType($responseType);
 3307:     foreach my $part_response_id (@part_response_id) {
 3308:     	my ($partid,$respid) = @{ $part_response_id };
 3309: 	my $part_resp = join('_',@{ $part_response_id });
 3310: 	next if $seen{$partid};
 3311: 	$seen{$partid}++;
 3312: 	my $handgrade=$$handgrade{$part_resp};
 3313: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3314: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3315: 
 3316: 	my $display_part=&get_display_part($partid,$symb);
 3317: 	my $radio.='<table border="0"><tr>';  
 3318: 	my $ctr = 0;
 3319: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3320: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3321: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3322: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3323: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3324: 	    $ctr++;
 3325: 	}
 3326: 	$radio.='</tr></table>';
 3327: 	my $line = '<input type="text" name="TEXTVAL_'.
 3328: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3329: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3330: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3331: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3332: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3333: 		$weight{$partid}.')"> '.
 3334: 	    '<option selected="selected"> </option>'.
 3335: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3336: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3337: 	    '</select></td>'.
 3338:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3339: 	$line.='<input type="hidden" name="partid_'.
 3340: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3341: 	$line.='<input type="hidden" name="weight_'.
 3342: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3343: 
 3344: 	$result.=
 3345: 	    &Apache::loncommon::start_data_table_row()."\n".
 3346: 	    '<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>'.
 3347: 	    &Apache::loncommon::end_data_table_row()."\n";
 3348: 	$ctsparts++;
 3349:     }
 3350:     $result.=&Apache::loncommon::end_data_table()."\n".
 3351: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3352:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3353: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3354: 
 3355:     #table listing all the students in a section/class
 3356:     #header of table
 3357:     $result.= '<h3>'.$specific_header.'</h3>'.
 3358:               &Apache::loncommon::start_data_table().
 3359: 	      &Apache::loncommon::start_data_table_header_row().
 3360: 	      '<th>'.&mt('No.').'</th>'.
 3361: 	      '<th>'.&nameUserString('header')."</th>\n";
 3362:     my $partserror;
 3363:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3364:     if ($partserror) {
 3365:         return &navmap_errormsg();
 3366:     }
 3367:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3368:     my @partids = ();
 3369:     foreach my $part (@parts) {
 3370: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3371:         my $narrowtext = &mt('Tries');
 3372: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3373: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3374: 	my ($partid) = &split_part_type($part);
 3375:         push(@partids,$partid);
 3376: 	my $display_part=&get_display_part($partid,$symb);
 3377: 	if ($display =~ /^Partial Credit Factor/) {
 3378: 	    $result.='<th>'.
 3379: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3380: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3381: 	    next;
 3382: 	    
 3383: 	} else {
 3384: 	    if ($display =~ /Problem Status/) {
 3385: 		my $grade_status_mt = &mt('Grade Status');
 3386: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3387: 	    }
 3388: 	    my $part_mt = &mt('Part:');
 3389: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3390: 	}
 3391: 
 3392: 	$result.='<th>'.$display.'</th>'."\n";
 3393:     }
 3394:     $result.=&Apache::loncommon::end_data_table_header_row();
 3395: 
 3396:     my %last_resets = 
 3397: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3398: 
 3399:     #get info for each student
 3400:     #list all the students - with points and grade status
 3401:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3402:     my $ctr = 0;
 3403:     foreach (sort 
 3404: 	     {
 3405: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3406: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3407: 		 }
 3408: 		 return $a cmp $b;
 3409: 	     } (keys(%$fullname))) {
 3410: 	$ctr++;
 3411: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3412: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3413:     }
 3414:     $result.=&Apache::loncommon::end_data_table();
 3415:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3416:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3417: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3418:     if (scalar(%$fullname) eq 0) {
 3419: 	my $colspan=3+scalar(@parts);
 3420: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3421:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3422: 	$result='<span class="LC_warning">'.
 3423: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3424: 	        $section_display, $stu_status).
 3425: 	    '</span>';
 3426:     }
 3427:     $result.=&show_grading_menu_form($symb);
 3428:     return $result;
 3429: }
 3430: 
 3431: #--- call by previous routine to display each student
 3432: sub viewstudentgrade {
 3433:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3434:     my ($uname,$udom) = split(/:/,$student);
 3435:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3436:     my %aggregates = (); 
 3437:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3438: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3439: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3440: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3441: 	'\');" target="_self">'.$fullname.'</a> '.
 3442: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3443:     $student=~s/:/_/; # colon doen't work in javascript for names
 3444:     foreach my $apart (@$parts) {
 3445: 	my ($part,$type) = &split_part_type($apart);
 3446: 	my $score=$record{"resource.$part.$type"};
 3447:         $result.='<td align="center">';
 3448:         my ($aggtries,$totaltries);
 3449:         unless (exists($aggregates{$part})) {
 3450: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3451: 
 3452: 	    $aggtries = $totaltries;
 3453:             if ($$last_resets{$part}) {  
 3454:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3455: 					   $part);
 3456:             }
 3457:             $result.='<input type="hidden" name="'.
 3458:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3459:             $result.='<input type="hidden" name="'.
 3460:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3461:             $aggregates{$part} = 1;
 3462:         }
 3463: 	if ($type eq 'awarded') {
 3464: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3465: 	    $result.='<input type="hidden" name="'.
 3466: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3467: 	    $result.='<input type="text" name="'.
 3468: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3469: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3470: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3471: 	} elsif ($type eq 'solved') {
 3472: 	    my ($status,$foo)=split(/_/,$score,2);
 3473: 	    $status = 'nothing' if ($status eq '');
 3474: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3475: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3476: 	    $result.='&nbsp;<select name="'.
 3477: 		'GD_'.$student.'_'.$part.'_solved" '.
 3478: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3479: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3480: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3481: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3482: 	    $result.="</select>&nbsp;</td>\n";
 3483: 	} else {
 3484: 	    $result.='<input type="hidden" name="'.
 3485: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3486: 		    "\n";
 3487: 	    $result.='<input type="text" name="'.
 3488: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3489: 		'value="'.$score.'" size="4" /></td>'."\n";
 3490: 	}
 3491:     }
 3492:     $result.=&Apache::loncommon::end_data_table_row();
 3493:     return $result;
 3494: }
 3495: 
 3496: #--- change scores for all the students in a section/class
 3497: #    record does not get update if unchanged
 3498: sub editgrades {
 3499:     my ($request) = @_;
 3500: 
 3501:     my $symb=&get_symb($request);
 3502:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3503:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3504:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3505:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3506: 
 3507:     my $result= &Apache::loncommon::start_data_table().
 3508: 	&Apache::loncommon::start_data_table_header_row().
 3509: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3510: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3511:     my %scoreptr = (
 3512: 		    'correct'  =>'correct_by_override',
 3513: 		    'incorrect'=>'incorrect_by_override',
 3514: 		    'excused'  =>'excused',
 3515: 		    'ungraded' =>'ungraded_attempted',
 3516: 		    'nothing'  => '',
 3517: 		    );
 3518:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3519: 
 3520:     my (@partid);
 3521:     my %weight = ();
 3522:     my %columns = ();
 3523:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3524: 
 3525:     my $partserror;
 3526:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3527:     if ($partserror) {
 3528:         return &navmap_errormsg();
 3529:     }
 3530:     my $header;
 3531:     while ($ctr < $env{'form.totalparts'}) {
 3532: 	my $partid = $env{'form.partid_'.$ctr};
 3533: 	push(@partid,$partid);
 3534: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3535: 	$ctr++;
 3536:     }
 3537:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3538:     foreach my $partid (@partid) {
 3539: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3540: 	    '<th align="center">'.&mt('New Score').'</th>';
 3541: 	$columns{$partid}=2;
 3542: 	foreach my $stores (@parts) {
 3543: 	    my ($part,$type) = &split_part_type($stores);
 3544: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3545: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3546: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3547: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3548:             my $narrowtext = &mt('Tries');
 3549: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3550: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3551: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3552: 	    $columns{$partid}+=2;
 3553: 	}
 3554:     }
 3555:     foreach my $partid (@partid) {
 3556: 	my $display_part=&get_display_part($partid,$symb);
 3557: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3558: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3559: 	    '</th>';
 3560: 
 3561:     }
 3562:     $result .= &Apache::loncommon::end_data_table_header_row().
 3563: 	&Apache::loncommon::start_data_table_header_row().
 3564: 	$header.
 3565: 	&Apache::loncommon::end_data_table_header_row();
 3566:     my @noupdate;
 3567:     my ($updateCtr,$noupdateCtr) = (1,1);
 3568:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3569: 	my $line;
 3570: 	my $user = $env{'form.ctr'.$i};
 3571: 	my ($uname,$udom)=split(/:/,$user);
 3572: 	my %newrecord;
 3573: 	my $updateflag = 0;
 3574: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3575: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3576: 	if (!&canmodify($usec)) {
 3577: 	    my $numcols=scalar(@partid)*4+2;
 3578: 	    push(@noupdate,
 3579: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3580: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3581: 	    next;
 3582: 	}
 3583:         my %aggregate = ();
 3584:         my $aggregateflag = 0;
 3585: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3586: 	foreach (@partid) {
 3587: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3588: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3589: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3590: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3591: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3592: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3593: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3594: 	    my $score;
 3595: 	    if ($partial eq '') {
 3596: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3597: 	    } elsif ($partial > 0) {
 3598: 		$score = 'correct_by_override';
 3599: 	    } elsif ($partial == 0) {
 3600: 		$score = 'incorrect_by_override';
 3601: 	    }
 3602: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3603: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3604: 
 3605: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3606: 		"$env{'user.name'}:$env{'user.domain'}";
 3607: 	    if ($dropMenu eq 'reset status' &&
 3608: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3609: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3610: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3611: 		$newrecord{'resource.'.$_.'.award'} = '';
 3612: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3613: 		$updateflag = 1;
 3614:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3615:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3616:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3617:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3618:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3619:                     $aggregateflag = 1;
 3620:                 }
 3621: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3622: 		$updateflag = 1;
 3623: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3624: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3625: 		$rec_update++;
 3626: 	    }
 3627: 
 3628: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3629: 		'<td align="center">'.$awarded.
 3630: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3631: 
 3632: 
 3633: 	    my $partid=$_;
 3634: 	    foreach my $stores (@parts) {
 3635: 		my ($part,$type) = &split_part_type($stores);
 3636: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3637: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3638: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3639: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3640: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3641: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3642: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3643: 		    $updateflag=1;
 3644: 		}
 3645: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3646: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3647: 	    }
 3648: 	}
 3649: 	$line.="\n";
 3650: 
 3651: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3652: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3653: 
 3654: 	if ($updateflag) {
 3655: 	    $count++;
 3656: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3657: 				    $udom,$uname);
 3658: 
 3659: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3660: 					      $cnum,$udom,$uname)) {
 3661: 		# need to figure out if should be in queue.
 3662: 		my %record =  
 3663: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3664: 					     $udom,$uname);
 3665: 		my $all_graded = 1;
 3666: 		my $none_graded = 1;
 3667: 		foreach my $part (@parts) {
 3668: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3669: 			$all_graded = 0;
 3670: 		    } else {
 3671: 			$none_graded = 0;
 3672: 		    }
 3673: 		}
 3674: 
 3675: 		if ($all_graded || $none_graded) {
 3676: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3677: 							   $symb,$cdom,$cnum,
 3678: 							   $udom,$uname);
 3679: 		}
 3680: 	    }
 3681: 
 3682: 	    $result.=&Apache::loncommon::start_data_table_row().
 3683: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3684: 		&Apache::loncommon::end_data_table_row();
 3685: 	    $updateCtr++;
 3686: 	} else {
 3687: 	    push(@noupdate,
 3688: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3689: 	    $noupdateCtr++;
 3690: 	}
 3691:         if ($aggregateflag) {
 3692:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3693: 				  $cdom,$cnum);
 3694:         }
 3695:     }
 3696:     if (@noupdate) {
 3697: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3698: 	my $numcols=scalar(@partid)*4+2;
 3699: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3700: 	    '<td align="center" colspan="'.$numcols.'">'.
 3701: 	    &mt('No Changes Occurred For the Students Below').
 3702: 	    '</td>'.
 3703: 	    &Apache::loncommon::end_data_table_row();
 3704: 	foreach my $line (@noupdate) {
 3705: 	    $result.=
 3706: 		&Apache::loncommon::start_data_table_row().
 3707: 		$line.
 3708: 		&Apache::loncommon::end_data_table_row();
 3709: 	}
 3710:     }
 3711:     $result .= &Apache::loncommon::end_data_table().
 3712: 	&show_grading_menu_form($symb);
 3713:     my $msg = '<p><b>'.
 3714: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3715: 	    $rec_update,$count).'</b><br />'.
 3716: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3717: 	'</b></p>';
 3718:     return $title.$msg.$result;
 3719: }
 3720: 
 3721: sub split_part_type {
 3722:     my ($partstr) = @_;
 3723:     my ($temp,@allparts)=split(/_/,$partstr);
 3724:     my $type=pop(@allparts);
 3725:     my $part=join('_',@allparts);
 3726:     return ($part,$type);
 3727: }
 3728: 
 3729: #------------- end of section for handling grading by section/class ---------
 3730: #
 3731: #----------------------------------------------------------------------------
 3732: 
 3733: 
 3734: #----------------------------------------------------------------------------
 3735: #
 3736: #-------------------------- Next few routines handles grading by csv upload
 3737: #
 3738: #--- Javascript to handle csv upload
 3739: sub csvupload_javascript_reverse_associate {
 3740:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3741:     my $error2=&mt('You need to specify at least one grading field');
 3742:   return(<<ENDPICK);
 3743:   function verify(vf) {
 3744:     var foundsomething=0;
 3745:     var founduname=0;
 3746:     var foundID=0;
 3747:     for (i=0;i<=vf.nfields.value;i++) {
 3748:       tw=eval('vf.f'+i+'.selectedIndex');
 3749:       if (i==0 && tw!=0) { foundID=1; }
 3750:       if (i==1 && tw!=0) { founduname=1; }
 3751:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3752:     }
 3753:     if (founduname==0 && foundID==0) {
 3754: 	alert('$error1');
 3755: 	return;
 3756:     }
 3757:     if (foundsomething==0) {
 3758: 	alert('$error2');
 3759: 	return;
 3760:     }
 3761:     vf.submit();
 3762:   }
 3763:   function flip(vf,tf) {
 3764:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3765:     var i;
 3766:     for (i=0;i<=vf.nfields.value;i++) {
 3767:       //can not pick the same destination field for both name and domain
 3768:       if (((i ==0)||(i ==1)) && 
 3769:           ((tf==0)||(tf==1)) && 
 3770:           (i!=tf) &&
 3771:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3772:         eval('vf.f'+i+'.selectedIndex=0;')
 3773:       }
 3774:     }
 3775:   }
 3776: ENDPICK
 3777: }
 3778: 
 3779: sub csvupload_javascript_forward_associate {
 3780:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3781:     my $error2=&mt('You need to specify at least one grading field');
 3782:   return(<<ENDPICK);
 3783:   function verify(vf) {
 3784:     var foundsomething=0;
 3785:     var founduname=0;
 3786:     var foundID=0;
 3787:     for (i=0;i<=vf.nfields.value;i++) {
 3788:       tw=eval('vf.f'+i+'.selectedIndex');
 3789:       if (tw==1) { foundID=1; }
 3790:       if (tw==2) { founduname=1; }
 3791:       if (tw>3) { foundsomething=1; }
 3792:     }
 3793:     if (founduname==0 && foundID==0) {
 3794: 	alert('$error1');
 3795: 	return;
 3796:     }
 3797:     if (foundsomething==0) {
 3798: 	alert('$error2');
 3799: 	return;
 3800:     }
 3801:     vf.submit();
 3802:   }
 3803:   function flip(vf,tf) {
 3804:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3805:     var i;
 3806:     //can not pick the same destination field twice
 3807:     for (i=0;i<=vf.nfields.value;i++) {
 3808:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3809:         eval('vf.f'+i+'.selectedIndex=0;')
 3810:       }
 3811:     }
 3812:   }
 3813: ENDPICK
 3814: }
 3815: 
 3816: sub csvuploadmap_header {
 3817:     my ($request,$symb,$datatoken,$distotal)= @_;
 3818:     my $javascript;
 3819:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3820: 	$javascript=&csvupload_javascript_reverse_associate();
 3821:     } else {
 3822: 	$javascript=&csvupload_javascript_forward_associate();
 3823:     }
 3824: 
 3825:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3826:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3827:     my $ignore=&mt('Ignore First Line');
 3828:     $symb = &Apache::lonenc::check_encrypt($symb);
 3829:     $request->print(<<ENDPICK);
 3830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3831: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3832: $result
 3833: <hr />
 3834: <h3>Identify fields</h3>
 3835: Total number of records found in file: $distotal <hr />
 3836: Enter as many fields as you can. The system will inform you and bring you back
 3837: to this page if the data selected is insufficient to run your class.<hr />
 3838: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3839: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3840: <input type="hidden" name="associate"  value="" />
 3841: <input type="hidden" name="phase"      value="three" />
 3842: <input type="hidden" name="datatoken"  value="$datatoken" />
 3843: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3844: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3845: <input type="hidden" name="upfile_associate" 
 3846:                                        value="$env{'form.upfile_associate'}" />
 3847: <input type="hidden" name="symb"       value="$symb" />
 3848: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3849: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3850: <input type="hidden" name="command"    value="csvuploadoptions" />
 3851: <hr />
 3852: <script type="text/javascript" language="Javascript">
 3853: $javascript
 3854: </script>
 3855: ENDPICK
 3856:     return '';
 3857: 
 3858: }
 3859: 
 3860: sub csvupload_fields {
 3861:     my ($symb,$errorref) = @_;
 3862:     my (@parts) = &getpartlist($symb,$errorref);
 3863:     if (ref($errorref)) {
 3864:         if ($$errorref) {
 3865:             return;
 3866:         }
 3867:     }
 3868: 
 3869:     my @fields=(['ID','Student/Employee ID'],
 3870: 		['username','Student Username'],
 3871: 		['domain','Student Domain']);
 3872:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3873:     foreach my $part (sort(@parts)) {
 3874: 	my @datum;
 3875: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3876: 	my $name=$part;
 3877: 	if  (!$display) { $display = $name; }
 3878: 	@datum=($name,$display);
 3879: 	if ($name=~/^stores_(.*)_awarded/) {
 3880: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3881: 	}
 3882: 	push(@fields,\@datum);
 3883:     }
 3884:     return (@fields);
 3885: }
 3886: 
 3887: sub csvuploadmap_footer {
 3888:     my ($request,$i,$keyfields) =@_;
 3889:     $request->print(<<ENDPICK);
 3890: </table>
 3891: <input type="hidden" name="nfields" value="$i" />
 3892: <input type="hidden" name="keyfields" value="$keyfields" />
 3893: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3894: </form>
 3895: ENDPICK
 3896: }
 3897: 
 3898: sub checkforfile_js {
 3899:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3900:     my $result =<<CSVFORMJS;
 3901: <script type="text/javascript" language="javascript">
 3902:     function checkUpload(formname) {
 3903: 	if (formname.upfile.value == "") {
 3904: 	    alert("$alertmsg");
 3905: 	    return false;
 3906: 	}
 3907: 	formname.submit();
 3908:     }
 3909:     </script>
 3910: CSVFORMJS
 3911:     return $result;
 3912: }
 3913: 
 3914: sub upcsvScores_form {
 3915:     my ($request) = shift;
 3916:     my ($symb)=&get_symb($request);
 3917:     if (!$symb) {return '';}
 3918:     my $result=&checkforfile_js();
 3919:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3920:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3921:     $result.=$table;
 3922:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3923:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3924:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3925: 	'</b></td></tr>'."\n";
 3926:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3927:     my $upload=&mt("Upload Scores");
 3928:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3929:     my $ignore=&mt('Ignore First Line');
 3930:     $symb = &Apache::lonenc::check_encrypt($symb);
 3931:     $result.=<<ENDUPFORM;
 3932: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3933: <input type="hidden" name="symb" value="$symb" />
 3934: <input type="hidden" name="command" value="csvuploadmap" />
 3935: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3936: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3937: $upfile_select
 3938: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3939: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3940: </form>
 3941: ENDUPFORM
 3942:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3943:                            &mt("How do I create a CSV file from a spreadsheet"))
 3944:     .'</td></tr></table>'."\n";
 3945:     $result.='</td></tr></table><br /><br />'."\n";
 3946:     $result.=&show_grading_menu_form($symb);
 3947:     return $result;
 3948: }
 3949: 
 3950: 
 3951: sub csvuploadmap {
 3952:     my ($request)= @_;
 3953:     my ($symb)=&get_symb($request);
 3954:     if (!$symb) {return '';}
 3955: 
 3956:     my $datatoken;
 3957:     if (!$env{'form.datatoken'}) {
 3958: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3959:     } else {
 3960: 	$datatoken=$env{'form.datatoken'};
 3961: 	&Apache::loncommon::load_tmp_file($request);
 3962:     }
 3963:     my @records=&Apache::loncommon::upfile_record_sep();
 3964:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3965:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3966:     my ($i,$keyfields);
 3967:     if (@records) {
 3968:         my $fieldserror;
 3969: 	my @fields=&csvupload_fields($symb,\$fieldserror);
 3970:         if ($fieldserror) {
 3971:             $request->print(&navmap_errormsg());
 3972:             return;
 3973:         }
 3974: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3975: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3976: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3977: 							  \@fields);
 3978: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3979: 	    chop($keyfields);
 3980: 	} else {
 3981: 	    unshift(@fields,['none','']);
 3982: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3983: 							    \@fields);
 3984:             foreach my $rec (@records) {
 3985:                 my %temp = &Apache::loncommon::record_sep($rec);
 3986:                 if (%temp) {
 3987:                     $keyfields=join(',',sort(keys(%temp)));
 3988:                     last;
 3989:                 }
 3990:             }
 3991: 	}
 3992:     }
 3993:     &csvuploadmap_footer($request,$i,$keyfields);
 3994:     $request->print(&show_grading_menu_form($symb));
 3995: 
 3996:     return '';
 3997: }
 3998: 
 3999: sub csvuploadoptions {
 4000:     my ($request)= @_;
 4001:     my ($symb)=&get_symb($request);
 4002:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4003:     my $ignore=&mt('Ignore First Line');
 4004:     $request->print(<<ENDPICK);
 4005: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4006: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4007: <input type="hidden" name="command"    value="csvuploadassign" />
 4008: <!--
 4009: <p>
 4010: <label>
 4011:    <input type="checkbox" name="show_full_results" />
 4012:    Show a table of all changes
 4013: </label>
 4014: </p>
 4015: -->
 4016: <p>
 4017: <label>
 4018:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4019:    Overwrite any existing score
 4020: </label>
 4021: </p>
 4022: ENDPICK
 4023:     my %fields=&get_fields();
 4024:     if (!defined($fields{'domain'})) {
 4025: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4026: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4027:     }
 4028:     foreach my $key (sort(keys(%env))) {
 4029: 	if ($key !~ /^form\.(.*)$/) { next; }
 4030: 	my $cleankey=$1;
 4031: 	if ($cleankey eq 'command') { next; }
 4032: 	$request->print('<input type="hidden" name="'.$cleankey.
 4033: 			'"  value="'.$env{$key}.'" />'."\n");
 4034:     }
 4035:     # FIXME do a check for any duplicated user ids...
 4036:     # FIXME do a check for any invalid user ids?...
 4037:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4038: <hr /></form>'."\n");
 4039:     $request->print(&show_grading_menu_form($symb));
 4040:     return '';
 4041: }
 4042: 
 4043: sub get_fields {
 4044:     my %fields;
 4045:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4046:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4047: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4048: 	    if ($env{'form.f'.$i} ne 'none') {
 4049: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4050: 	    }
 4051: 	} else {
 4052: 	    if ($env{'form.f'.$i} ne 'none') {
 4053: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4054: 	    }
 4055: 	}
 4056:     }
 4057:     return %fields;
 4058: }
 4059: 
 4060: sub csvuploadassign {
 4061:     my ($request)= @_;
 4062:     my ($symb)=&get_symb($request);
 4063:     if (!$symb) {return '';}
 4064:     my $error_msg = '';
 4065:     &Apache::loncommon::load_tmp_file($request);
 4066:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4067:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4068:     my %fields=&get_fields();
 4069:     $request->print('<h3>Assigning Grades</h3>');
 4070:     my $courseid=$env{'request.course.id'};
 4071:     my ($classlist) = &getclasslist('all',0);
 4072:     my @notallowed;
 4073:     my @skipped;
 4074:     my $countdone=0;
 4075:     foreach my $grade (@gradedata) {
 4076: 	my %entries=&Apache::loncommon::record_sep($grade);
 4077: 	my $domain;
 4078: 	if ($entries{$fields{'domain'}}) {
 4079: 	    $domain=$entries{$fields{'domain'}};
 4080: 	} else {
 4081: 	    $domain=$env{'form.default_domain'};
 4082: 	}
 4083: 	$domain=~s/\s//g;
 4084: 	my $username=$entries{$fields{'username'}};
 4085: 	$username=~s/\s//g;
 4086: 	if (!$username) {
 4087: 	    my $id=$entries{$fields{'ID'}};
 4088: 	    $id=~s/\s//g;
 4089: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4090: 	    $username=$ids{$id};
 4091: 	}
 4092: 	if (!exists($$classlist{"$username:$domain"})) {
 4093: 	    my $id=$entries{$fields{'ID'}};
 4094: 	    $id=~s/\s//g;
 4095: 	    if ($id) {
 4096: 		push(@skipped,"$id:$domain");
 4097: 	    } else {
 4098: 		push(@skipped,"$username:$domain");
 4099: 	    }
 4100: 	    next;
 4101: 	}
 4102: 	my $usec=$classlist->{"$username:$domain"}[5];
 4103: 	if (!&canmodify($usec)) {
 4104: 	    push(@notallowed,"$username:$domain");
 4105: 	    next;
 4106: 	}
 4107: 	my %points;
 4108: 	my %grades;
 4109: 	foreach my $dest (keys(%fields)) {
 4110: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4111: 		$dest eq 'domain') { next; }
 4112: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4113: 	    if ($dest=~/stores_(.*)_points/) {
 4114: 		my $part=$1;
 4115: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4116: 					      $symb,$domain,$username);
 4117:                 if ($wgt) {
 4118:                     $entries{$fields{$dest}}=~s/\s//g;
 4119:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4120:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4121:                                           : 'correct_by_override';
 4122:                     $grades{"resource.$part.awarded"}=$pcr;
 4123:                     $grades{"resource.$part.solved"}=$award;
 4124:                     $points{$part}=1;
 4125:                 } else {
 4126:                     $error_msg = "<br />" .
 4127:                         &mt("Some point values were assigned"
 4128:                             ." for problems with a weight "
 4129:                             ."of zero. These values were "
 4130:                             ."ignored.");
 4131:                 }
 4132: 	    } else {
 4133: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4134: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4135: 		my $store_key=$dest;
 4136: 		$store_key=~s/^stores/resource/;
 4137: 		$store_key=~s/_/\./g;
 4138: 		$grades{$store_key}=$entries{$fields{$dest}};
 4139: 	    }
 4140: 	}
 4141: 	if (! %grades) { 
 4142:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4143:         } else {
 4144: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4145: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4146: 					   $env{'request.course.id'},
 4147: 					   $domain,$username);
 4148: 	   if ($result eq 'ok') {
 4149: 	      $request->print('.');
 4150: 	   } else {
 4151: 	      $request->print("<p><span class=\"LC_error\">".
 4152:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4153:                                   "$username:$domain",$result)."</span></p>");
 4154: 	   }
 4155: 	   $request->rflush();
 4156: 	   $countdone++;
 4157:         }
 4158:     }
 4159:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4160:     if (@skipped) {
 4161: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4162:         $request->print(join(', ',@skipped));
 4163:     }
 4164:     if (@notallowed) {
 4165: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4166: 	$request->print(join(', ',@notallowed));
 4167:     }
 4168:     $request->print("<br />\n");
 4169:     $request->print(&show_grading_menu_form($symb));
 4170:     return $error_msg;
 4171: }
 4172: #------------- end of section for handling csv file upload ---------
 4173: #
 4174: #-------------------------------------------------------------------
 4175: #
 4176: #-------------- Next few routines handle grading by page/sequence
 4177: #
 4178: #--- Select a page/sequence and a student to grade
 4179: sub pickStudentPage {
 4180:     my ($request) = shift;
 4181: 
 4182:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4183:     $request->print(<<LISTJAVASCRIPT);
 4184: <script type="text/javascript" language="javascript">
 4185: 
 4186: function checkPickOne(formname) {
 4187:     if (radioSelection(formname.student) == null) {
 4188: 	alert("$alertmsg");
 4189: 	return;
 4190:     }
 4191:     ptr = pullDownSelection(formname.selectpage);
 4192:     formname.page.value = formname["page"+ptr].value;
 4193:     formname.title.value = formname["title"+ptr].value;
 4194:     formname.submit();
 4195: }
 4196: 
 4197: </script>
 4198: LISTJAVASCRIPT
 4199:     &commonJSfunctions($request);
 4200:     my ($symb) = &get_symb($request);
 4201:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4202:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4203:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4204: 
 4205:     my $result='<h3><span class="LC_info">&nbsp;'.
 4206: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4207: 
 4208:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4209:     my $map_error;
 4210:     my ($titles,$symbx) = &getSymbMap($map_error);
 4211:     if ($map_error) {
 4212:         $request->print(&navmap_errormsg());
 4213:         return; 
 4214:     }
 4215:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4216: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4217: #    my $type=($curpage =~ /\.(page|sequence)/);
 4218:     my $select = '<select name="selectpage">'."\n";
 4219:     my $ctr=0;
 4220:     foreach (@$titles) {
 4221: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4222: 	$select.='<option value="'.$ctr.'" '.
 4223: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4224: 	    '>'.$showtitle.'</option>'."\n";
 4225: 	$ctr++;
 4226:     }
 4227:     $select.= '</select>';
 4228:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4229: 
 4230:     $ctr=0;
 4231:     foreach (@$titles) {
 4232: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4233: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4234: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4235: 	$ctr++;
 4236:     }
 4237:     $result.='<input type="hidden" name="page" />'."\n".
 4238: 	'<input type="hidden" name="title" />'."\n";
 4239: 
 4240:     my $options =
 4241: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4242: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4243:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4244: 
 4245:     $options =
 4246: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4247: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4248: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4249:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4250:     
 4251:     $result.=&build_section_inputs();
 4252:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4253:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4254: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4255: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4256: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4257: 
 4258:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4259: 
 4260:     $result.='&nbsp;<input type="button" '.
 4261: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4262: 
 4263:     $request->print($result);
 4264: 
 4265:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4266: 	&Apache::loncommon::start_data_table().
 4267: 	&Apache::loncommon::start_data_table_header_row().
 4268: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4269: 	'<th>'.&nameUserString('header').'</th>'.
 4270: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4271: 	'<th>'.&nameUserString('header').'</th>'.
 4272: 	&Apache::loncommon::end_data_table_header_row();
 4273:  
 4274:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4275:     my $ptr = 1;
 4276:     foreach my $student (sort 
 4277: 			 {
 4278: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4279: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4280: 			     }
 4281: 			     return $a cmp $b;
 4282: 			 } (keys(%$fullname))) {
 4283: 	my ($uname,$udom) = split(/:/,$student);
 4284: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4285:                                   : '</td>');
 4286: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4287: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4288: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4289: 	$studentTable.=
 4290: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4291:                          : '');
 4292: 	$ptr++;
 4293:     }
 4294:     if ($ptr%2 == 0) {
 4295: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4296: 	    &Apache::loncommon::end_data_table_row();
 4297:     }
 4298:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4299:     $studentTable.='<input type="button" '.
 4300: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4301: 
 4302:     $studentTable.=&show_grading_menu_form($symb);
 4303:     $request->print($studentTable);
 4304: 
 4305:     return '';
 4306: }
 4307: 
 4308: sub getSymbMap {
 4309:     my ($map_error) = @_;
 4310:     my $navmap = Apache::lonnavmaps::navmap->new();
 4311:     unless (ref($navmap)) {
 4312:         if (ref($map_error)) {
 4313:             $$map_error = 'navmap';
 4314:         }
 4315:         return;
 4316:     }
 4317:     my %symbx = ();
 4318:     my @titles = ();
 4319:     my $minder = 0;
 4320: 
 4321:     # Gather every sequence that has problems.
 4322:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4323: 					       1,0,1);
 4324:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4325: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4326: 	    my $title = $minder.'.'.
 4327: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4328: 	    push(@titles, $title); # minder in case two titles are identical
 4329: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4330: 	    $minder++;
 4331: 	}
 4332:     }
 4333:     return \@titles,\%symbx;
 4334: }
 4335: 
 4336: #
 4337: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4338: sub displayPage {
 4339:     my ($request) = shift;
 4340: 
 4341:     my ($symb) = &get_symb($request);
 4342:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4343:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4344:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4345:     my $pageTitle = $env{'form.page'};
 4346:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4347:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4348:     my $usec=$classlist->{$env{'form.student'}}[5];
 4349: 
 4350:     #need to make sure we have the correct data for later EXT calls, 
 4351:     #thus invalidate the cache
 4352:     &Apache::lonnet::devalidatecourseresdata(
 4353:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4354:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4355:     &Apache::lonnet::clear_EXT_cache_status();
 4356: 
 4357:     if (!&canview($usec)) {
 4358: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4359: 	$request->print(&show_grading_menu_form($symb));
 4360: 	return;
 4361:     }
 4362:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4363:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4364: 	'</h3>'."\n";
 4365:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4366:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4367: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4368:     } else {
 4369: 	delete($env{'form.CODE'});
 4370:     }
 4371:     &sub_page_js($request);
 4372:     $request->print($result);
 4373: 
 4374:     my $navmap = Apache::lonnavmaps::navmap->new();
 4375:     unless (ref($navmap)) {
 4376:         $request->print(&navmap_errormsg());
 4377:         $request->print(&show_grading_menu_form($symb));
 4378:         return;
 4379:     }
 4380:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4381:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4382:     if (!$map) {
 4383: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4384: 	$request->print(&show_grading_menu_form($symb));
 4385: 	return; 
 4386:     }
 4387:     my $iterator = $navmap->getIterator($map->map_start(),
 4388: 					$map->map_finish());
 4389: 
 4390:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4391: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4392: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4393: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4394: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4395: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4396: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4397: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4398: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4399: 
 4400:     if (defined($env{'form.CODE'})) {
 4401: 	$studentTable.=
 4402: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4403:     }
 4404:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4405: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4406: 
 4407:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4408: 	&Apache::loncommon::start_data_table().
 4409: 	&Apache::loncommon::start_data_table_header_row().
 4410: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4411: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4412: 	&Apache::loncommon::end_data_table_header_row();
 4413: 
 4414:     &Apache::lonxml::clear_problem_counter();
 4415:     my ($depth,$question,$prob) = (1,1,1);
 4416:     $iterator->next(); # skip the first BEGIN_MAP
 4417:     my $curRes = $iterator->next(); # for "current resource"
 4418:     while ($depth > 0) {
 4419:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4420:         if($curRes == $iterator->END_MAP) { $depth--; }
 4421: 
 4422:         if (ref($curRes) && $curRes->is_problem()) {
 4423: 	    my $parts = $curRes->parts();
 4424:             my $title = $curRes->compTitle();
 4425: 	    my $symbx = $curRes->symb();
 4426: 	    $studentTable.=
 4427: 		&Apache::loncommon::start_data_table_row().
 4428: 		'<td align="center" valign="top" >'.$prob.
 4429: 		(scalar(@{$parts}) == 1 ? '' 
 4430: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4431: 							scalar(@{$parts}))
 4432: 		 ).
 4433: 		 '</td>';
 4434: 	    $studentTable.='<td valign="top">';
 4435: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4436: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4437: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4438: 					     undef,'both',\%form);
 4439: 	    } else {
 4440: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4441: 		$companswer =~ s|<form(.*?)>||g;
 4442: 		$companswer =~ s|</form>||g;
 4443: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4444: #		    $companswer =~ s/$1/ /ms;
 4445: #		    $request->print('match='.$1."<br />\n");
 4446: #		}
 4447: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4448: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4449: 	    }
 4450: 
 4451: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4452: 
 4453: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4454: 		if ($record{'version'} eq '') {
 4455: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4456: 		} else {
 4457: 		    my %responseType = ();
 4458: 		    foreach my $partid (@{$parts}) {
 4459: 			my @responseIds =$curRes->responseIds($partid);
 4460: 			my @responseType =$curRes->responseType($partid);
 4461: 			my %responseIds;
 4462: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4463: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4464: 			}
 4465: 			$responseType{$partid} = \%responseIds;
 4466: 		    }
 4467: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4468: 
 4469: 		}
 4470: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4471: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4472: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4473: 									$env{'request.course.id'},
 4474: 									'','.submission');
 4475:  
 4476: 	    }
 4477: 	    if (&canmodify($usec)) {
 4478: 		foreach my $partid (@{$parts}) {
 4479: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4480: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4481: 		    $question++;
 4482: 		}
 4483: 		$prob++;
 4484: 	    }
 4485: 	    $studentTable.='</td></tr>';
 4486: 
 4487: 	}
 4488:         $curRes = $iterator->next();
 4489:     }
 4490: 
 4491:     $studentTable.='</table>'."\n".
 4492: 	'<input type="button" value="'.&mt('Save').'" '.
 4493: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4494: 	'</form>'."\n";
 4495:     $studentTable.=&show_grading_menu_form($symb);
 4496:     $request->print($studentTable);
 4497: 
 4498:     return '';
 4499: }
 4500: 
 4501: sub displaySubByDates {
 4502:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4503:     my $isCODE=0;
 4504:     my $isTask = ($symb =~/\.task$/);
 4505:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4506:     my $studentTable=&Apache::loncommon::start_data_table().
 4507: 	&Apache::loncommon::start_data_table_header_row().
 4508: 	'<th>'.&mt('Date/Time').'</th>'.
 4509: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4510: 	'<th>'.&mt('Submission').'</th>'.
 4511: 	'<th>'.&mt('Status').'</th>'.
 4512: 	&Apache::loncommon::end_data_table_header_row();
 4513:     my ($version);
 4514:     my %mark;
 4515:     my %orders;
 4516:     $mark{'correct_by_student'} = $checkIcon;
 4517:     if (!exists($$record{'1:timestamp'})) {
 4518: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4519:     }
 4520: 
 4521:     my $interaction;
 4522:     my $no_increment = 1;
 4523:     for ($version=1;$version<=$$record{'version'};$version++) {
 4524: 	my $timestamp = 
 4525: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4526: 	if (exists($$record{$version.':resource.0.version'})) {
 4527: 	    $interaction = $$record{$version.':resource.0.version'};
 4528: 	}
 4529: 
 4530: 	my $where = ($isTask ? "$version:resource.$interaction"
 4531: 		             : "$version:resource");
 4532: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4533: 	    '<td>'.$timestamp.'</td>';
 4534: 	if ($isCODE) {
 4535: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4536: 	}
 4537: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4538: 	my @displaySub = ();
 4539: 	foreach my $partid (@{$parts}) {
 4540: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4541: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4542: 	    
 4543: 
 4544: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4545: 	    my $display_part=&get_display_part($partid,$symb);
 4546: 	    foreach my $matchKey (@matchKey) {
 4547: 		if (exists($$record{$version.':'.$matchKey}) &&
 4548: 		    $$record{$version.':'.$matchKey} ne '') {
 4549: 
 4550: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4551: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4552:                     $displaySub[0].='<span class="LC_nobreak"';
 4553:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
 4554:                                    .' <span class="LC_internal_info">'
 4555:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
 4556:                                    .'</span>'
 4557:                                    .' <b>';
 4558: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4559: 			$displaySub[0].=&mt('Trial not counted');
 4560: 		    } else {
 4561: 			$displaySub[0].=&mt('Trial: [_1]',
 4562: 					    $$record{"$where.$partid.tries"});
 4563: 		    }
 4564: 		    my $responseType=($isTask ? 'Task'
 4565:                                               : $responseType->{$partid}->{$responseId});
 4566: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4567: 		    if (!exists($orders{$partid}->{$responseId})) {
 4568: 			$orders{$partid}->{$responseId}=
 4569: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4570:                                        $no_increment);
 4571: 		    }
 4572: 		    $displaySub[0].='</b></span>'; # /nobreak
 4573: 		    $displaySub[0].='&nbsp; '.
 4574: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4575: 		}
 4576: 	    }
 4577: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4578: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4579: 				    $$record{"$where.$partid.checkedin"},
 4580: 				    $$record{"$where.$partid.checkedin.slot"}).
 4581: 					'<br />';
 4582: 	    }
 4583: 	    if (exists $$record{"$where.$partid.award"}) {
 4584: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4585: 		    lc($$record{"$where.$partid.award"}).' '.
 4586: 		    $mark{$$record{"$where.$partid.solved"}}.
 4587: 		    '<br />';
 4588: 	    }
 4589: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4590: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4591: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4592: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4593: 		$displaySub[2].=
 4594: 		    $$record{"$version:resource.$partid.regrader"}.
 4595: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4596: 	    }
 4597: 	}
 4598: 	# needed because old essay regrader has not parts info
 4599: 	if (exists $$record{"$version:resource.regrader"}) {
 4600: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4601: 	}
 4602: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4603: 	if ($displaySub[2]) {
 4604: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4605: 	}
 4606: 	$studentTable.='&nbsp;</td>'.
 4607: 	    &Apache::loncommon::end_data_table_row();
 4608:     }
 4609:     $studentTable.=&Apache::loncommon::end_data_table();
 4610:     return $studentTable;
 4611: }
 4612: 
 4613: sub updateGradeByPage {
 4614:     my ($request) = shift;
 4615: 
 4616:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4617:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4618:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4619:     my $pageTitle = $env{'form.page'};
 4620:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4621:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4622:     my $usec=$classlist->{$env{'form.student'}}[5];
 4623:     if (!&canmodify($usec)) {
 4624: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4625: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4626: 	return;
 4627:     }
 4628:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4629:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4630: 	'</h3>'."\n";
 4631: 
 4632:     $request->print($result);
 4633: 
 4634: 
 4635:     my $navmap = Apache::lonnavmaps::navmap->new();
 4636:     unless (ref($navmap)) {
 4637:         $request->print(&navmap_errormsg());
 4638:         return;
 4639:     }
 4640:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4641:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4642:     if (!$map) {
 4643: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4644: 	my ($symb)=&get_symb($request);
 4645: 	$request->print(&show_grading_menu_form($symb));
 4646: 	return; 
 4647:     }
 4648:     my $iterator = $navmap->getIterator($map->map_start(),
 4649: 					$map->map_finish());
 4650: 
 4651:     my $studentTable=
 4652: 	&Apache::loncommon::start_data_table().
 4653: 	&Apache::loncommon::start_data_table_header_row().
 4654: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4655: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4656: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4657: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4658: 	&Apache::loncommon::end_data_table_header_row();
 4659: 
 4660:     $iterator->next(); # skip the first BEGIN_MAP
 4661:     my $curRes = $iterator->next(); # for "current resource"
 4662:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4663:     while ($depth > 0) {
 4664:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4665:         if($curRes == $iterator->END_MAP) { $depth--; }
 4666: 
 4667:         if (ref($curRes) && $curRes->is_problem()) {
 4668: 	    my $parts = $curRes->parts();
 4669:             my $title = $curRes->compTitle();
 4670: 	    my $symbx = $curRes->symb();
 4671: 	    $studentTable.=
 4672: 		&Apache::loncommon::start_data_table_row().
 4673: 		'<td align="center" valign="top" >'.$prob.
 4674: 		(scalar(@{$parts}) == 1 ? '' 
 4675:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4676: 		.')').'</td>';
 4677: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4678: 
 4679: 	    my %newrecord=();
 4680: 	    my @displayPts=();
 4681:             my %aggregate = ();
 4682:             my $aggregateflag = 0;
 4683: 	    foreach my $partid (@{$parts}) {
 4684: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4685: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4686: 
 4687: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4688: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4689: 		my $partial = $newpts/$wgt;
 4690: 		my $score;
 4691: 		if ($partial > 0) {
 4692: 		    $score = 'correct_by_override';
 4693: 		} elsif ($newpts ne '') { #empty is taken as 0
 4694: 		    $score = 'incorrect_by_override';
 4695: 		}
 4696: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4697: 		if ($dropMenu eq 'excused') {
 4698: 		    $partial = '';
 4699: 		    $score = 'excused';
 4700: 		} elsif ($dropMenu eq 'reset status'
 4701: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4702: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4703: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4704: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4705: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4706: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4707: 		    $changeflag++;
 4708: 		    $newpts = '';
 4709:                     
 4710:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4711:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4712:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4713:                     if ($aggtries > 0) {
 4714:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4715:                         $aggregateflag = 1;
 4716:                     }
 4717: 		}
 4718: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4719: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4720: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4721: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4722: 		    '&nbsp;<br />';
 4723: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4724: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4725: 		    '&nbsp;<br />';
 4726: 		$question++;
 4727: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4728: 
 4729: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4730: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4731: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4732: 		    if (scalar(keys(%newrecord)) > 0);
 4733: 
 4734: 		$changeflag++;
 4735: 	    }
 4736: 	    if (scalar(keys(%newrecord)) > 0) {
 4737: 		my %record = 
 4738: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4739: 					     $udom,$uname);
 4740: 
 4741: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4742: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4743: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4744: 		    $newrecord{'resource.CODE'} = '';
 4745: 		}
 4746: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4747: 					$udom,$uname);
 4748: 		%record = &Apache::lonnet::restore($symbx,
 4749: 						   $env{'request.course.id'},
 4750: 						   $udom,$uname);
 4751: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4752: 					     $cdom,$cnum,$udom,$uname);
 4753: 	    }
 4754: 	    
 4755:             if ($aggregateflag) {
 4756:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4757:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4758:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4759:             }
 4760: 
 4761: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4762: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4763: 		&Apache::loncommon::end_data_table_row();
 4764: 
 4765: 	    $prob++;
 4766: 	}
 4767:         $curRes = $iterator->next();
 4768:     }
 4769: 
 4770:     $studentTable.=&Apache::loncommon::end_data_table();
 4771:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4772:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4773: 		  &mt('The scores were changed for [quant,_1,problem].',
 4774: 		  $changeflag));
 4775:     $request->print($grademsg.$studentTable);
 4776: 
 4777:     return '';
 4778: }
 4779: 
 4780: #-------- end of section for handling grading by page/sequence ---------
 4781: #
 4782: #-------------------------------------------------------------------
 4783: 
 4784: #-------------------- Bubblesheet (Scantron) Grading -------------------
 4785: #
 4786: #------ start of section for handling grading by page/sequence ---------
 4787: 
 4788: =pod
 4789: 
 4790: =head1 Bubble sheet grading routines
 4791: 
 4792:   For this documentation:
 4793: 
 4794:    'scanline' refers to the full line of characters
 4795:    from the file that we are parsing that represents one entire sheet
 4796: 
 4797:    'bubble line' refers to the data
 4798:    representing the line of bubbles that are on the physical bubble sheet
 4799: 
 4800: 
 4801: The overall process is that a scanned in bubble sheet data is uploaded
 4802: into a course. When a user wants to grade, they select a
 4803: sequence/folder of resources, a file of bubble sheet info, and pick
 4804: one of the predefined configurations for what each scanline looks
 4805: like.
 4806: 
 4807: Next each scanline is checked for any errors of either 'missing
 4808: bubbles' (it's an error because it may have been mis-scanned
 4809: because too light bubbling), 'double bubble' (each bubble line should
 4810: have no more that one letter picked), invalid or duplicated CODE,
 4811: invalid student/employee ID
 4812: 
 4813: If the CODE option is used that determines the randomization of the
 4814: homework problems, either way the student/employee ID is looked up into a
 4815: username:domain.
 4816: 
 4817: During the validation phase the instructor can choose to skip scanlines. 
 4818: 
 4819: After the validation phase, there are now 3 bubble sheet files
 4820: 
 4821:   scantron_original_filename (unmodified original file)
 4822:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4823:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4824: 
 4825: Also there is a separate hash nohist_scantrondata that contains extra
 4826: correction information that isn't representable in the bubble sheet
 4827: file (see &scantron_getfile() for more information)
 4828: 
 4829: After all scanlines are either valid, marked as valid or skipped, then
 4830: foreach line foreach problem in the picked sequence, an ssi request is
 4831: made that simulates a user submitting their selected letter(s) against
 4832: the homework problem.
 4833: 
 4834: =over 4
 4835: 
 4836: 
 4837: 
 4838: =item defaultFormData
 4839: 
 4840:   Returns html hidden inputs used to hold context/default values.
 4841: 
 4842:  Arguments:
 4843:   $symb - $symb of the current resource 
 4844: 
 4845: =cut
 4846: 
 4847: sub defaultFormData {
 4848:     my ($symb)=@_;
 4849:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4850:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4851:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4852: }
 4853: 
 4854: 
 4855: =pod 
 4856: 
 4857: =item getSequenceDropDown
 4858: 
 4859:    Return html dropdown of possible sequences to grade
 4860:  
 4861:  Arguments:
 4862:    $symb - $symb of the current resource
 4863:    $map_error - ref to scalar which will container error if
 4864:                 $navmap object is unavailable in &getSymbMap().
 4865: 
 4866: =cut
 4867: 
 4868: sub getSequenceDropDown {
 4869:     my ($symb,$map_error)=@_;
 4870:     my $result='<select name="selectpage">'."\n";
 4871:     my ($titles,$symbx) = &getSymbMap($map_error);
 4872:     if (ref($map_error)) {
 4873:         return if ($$map_error);
 4874:     }
 4875:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4876:     my $ctr=0;
 4877:     foreach (@$titles) {
 4878: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4879: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4880: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4881: 	    '>'.$showtitle.'</option>'."\n";
 4882: 	$ctr++;
 4883:     }
 4884:     $result.= '</select>';
 4885:     return $result;
 4886: }
 4887: 
 4888: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4889:                                    # key is zero-based index - 0, 1, 2 ...
 4890: 
 4891: my %first_bubble_line;             # First bubble line no. for each bubble.
 4892: 
 4893: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4894:                                    # matchresponse or rankresponse, where 
 4895:                                    # an individual response can have multiple 
 4896:                                    # lines
 4897: 
 4898: my %responsetype_per_response;     # responsetype for each response
 4899: 
 4900: # Save and restore the bubble lines array to the form env.
 4901: 
 4902: 
 4903: sub save_bubble_lines {
 4904:     foreach my $line (keys(%bubble_lines_per_response)) {
 4905: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4906: 	$env{"form.scantron.first_bubble_line.$line"} =
 4907: 	    $first_bubble_line{$line};
 4908:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4909:             $subdivided_bubble_lines{$line};
 4910:         $env{"form.scantron.responsetype.$line"} =
 4911:             $responsetype_per_response{$line};
 4912:     }
 4913: }
 4914: 
 4915: 
 4916: sub restore_bubble_lines {
 4917:     my $line = 0;
 4918:     %bubble_lines_per_response = ();
 4919:     while ($env{"form.scantron.bubblelines.$line"}) {
 4920: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4921: 	$bubble_lines_per_response{$line} = $value;
 4922: 	$first_bubble_line{$line}  =
 4923: 	    $env{"form.scantron.first_bubble_line.$line"};
 4924:         $subdivided_bubble_lines{$line} =
 4925:             $env{"form.scantron.sub_bubblelines.$line"};
 4926:         $responsetype_per_response{$line} =
 4927:             $env{"form.scantron.responsetype.$line"};
 4928: 	$line++;
 4929:     }
 4930: }
 4931: 
 4932: #  Given the parsed scanline, get the response for 
 4933: #  'answer' number n:
 4934: 
 4935: sub get_response_bubbles {
 4936:     my ($parsed_line, $response)  = @_;
 4937: 
 4938:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4939:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4940:     
 4941:     my $selected = "";
 4942: 
 4943:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4944: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4945: 	$bubble_line++;
 4946:     }
 4947:     return $selected;
 4948: }
 4949: 
 4950: =pod 
 4951: 
 4952: =item scantron_filenames
 4953: 
 4954:    Returns a list of the scantron files in the current course 
 4955: 
 4956: =cut
 4957: 
 4958: sub scantron_filenames {
 4959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4960:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4961:     my $getpropath = 1;
 4962:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4963:                                        $getpropath);
 4964:     my @possiblenames;
 4965:     foreach my $filename (sort(@files)) {
 4966: 	($filename)=split(/&/,$filename);
 4967: 	if ($filename!~/^scantron_orig_/) { next ; }
 4968: 	$filename=~s/^scantron_orig_//;
 4969: 	push(@possiblenames,$filename);
 4970:     }
 4971:     return @possiblenames;
 4972: }
 4973: 
 4974: =pod 
 4975: 
 4976: =item scantron_uploads
 4977: 
 4978:    Returns  html drop-down list of scantron files in current course.
 4979: 
 4980:  Arguments:
 4981:    $file2grade - filename to set as selected in the dropdown
 4982: 
 4983: =cut
 4984: 
 4985: sub scantron_uploads {
 4986:     my ($file2grade) = @_;
 4987:     my $result=	'<select name="scantron_selectfile">';
 4988:     $result.="<option></option>";
 4989:     foreach my $filename (sort(&scantron_filenames())) {
 4990: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4991:     }
 4992:     $result.="</select>";
 4993:     return $result;
 4994: }
 4995: 
 4996: =pod 
 4997: 
 4998: =item scantron_scantab
 4999: 
 5000:   Returns html drop down of the scantron formats in the scantronformat.tab
 5001:   file.
 5002: 
 5003: =cut
 5004: 
 5005: sub scantron_scantab {
 5006:     my $result='<select name="scantron_format">'."\n";
 5007:     $result.='<option></option>'."\n";
 5008:     my @lines = &get_scantronformat_file();
 5009:     if (@lines > 0) {
 5010:         foreach my $line (@lines) {
 5011:             next if (($line =~ /^\#/) || ($line eq ''));
 5012: 	    my ($name,$descrip)=split(/:/,$line);
 5013: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5014:         }
 5015:     }
 5016:     $result.='</select>'."\n";
 5017:     return $result;
 5018: }
 5019: 
 5020: =pod
 5021: 
 5022: =item get_scantronformat_file
 5023: 
 5024:   Returns an array containing lines from the scantron format file for
 5025:   the domain of the course.
 5026: 
 5027:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5028:   lines are from this file.
 5029: 
 5030:   Otherwise, if a default.tab has been published in RES space by the 
 5031:   domainconfig user, lines are from this file.
 5032: 
 5033:   Otherwise, fall back to getting lines from the legacy file on the
 5034:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5035: 
 5036: =cut
 5037: 
 5038: sub get_scantronformat_file {
 5039:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5040:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5041:     my $gottab = 0;
 5042:     my @lines;
 5043:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5044:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5045:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5046:             if ($formatfile ne '-1') {
 5047:                 @lines = split("\n",$formatfile,-1);
 5048:                 $gottab = 1;
 5049:             }
 5050:         }
 5051:     }
 5052:     if (!$gottab) {
 5053:         my $confname = $cdom.'-domainconfig';
 5054:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5055:         my $formatfile =  &Apache::lonnet::getfile($default);
 5056:         if ($formatfile ne '-1') {
 5057:             @lines = split("\n",$formatfile,-1);
 5058:             $gottab = 1;
 5059:         }
 5060:     }
 5061:     if (!$gottab) {
 5062:         my @domains = &Apache::lonnet::current_machine_domains();
 5063:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5064:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5065:             @lines = <$fh>;
 5066:             close($fh);
 5067:         } else {
 5068:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5069:             @lines = <$fh>;
 5070:             close($fh);
 5071:         }
 5072:     }
 5073:     return @lines;
 5074: }
 5075: 
 5076: =pod 
 5077: 
 5078: =item scantron_CODElist
 5079: 
 5080:   Returns html drop down of the saved CODE lists from current course,
 5081:   generated from earlier printings.
 5082: 
 5083: =cut
 5084: 
 5085: sub scantron_CODElist {
 5086:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5087:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5088:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5089:     my $namechoice='<option></option>';
 5090:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5091: 	if ($name =~ /^error: 2 /) { next; }
 5092: 	if ($name =~ /^type\0/) { next; }
 5093: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5094:     }
 5095:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5096:     return $namechoice;
 5097: }
 5098: 
 5099: =pod 
 5100: 
 5101: =item scantron_CODEunique
 5102: 
 5103:   Returns the html for "Each CODE to be used once" radio.
 5104: 
 5105: =cut
 5106: 
 5107: sub scantron_CODEunique {
 5108:     my $result='<span class="LC_nobreak">
 5109:                  <label><input type="radio" name="scantron_CODEunique"
 5110:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5111:                 </span>
 5112:                 <span class="LC_nobreak">
 5113:                  <label><input type="radio" name="scantron_CODEunique"
 5114:                         value="no" />'.&mt('No').' </label>
 5115:                 </span>';
 5116:     return $result;
 5117: }
 5118: 
 5119: =pod 
 5120: 
 5121: =item scantron_selectphase
 5122: 
 5123:   Generates the initial screen to start the bubble sheet process.
 5124:   Allows for - starting a grading run.
 5125:              - downloading existing scan data (original, corrected
 5126:                                                 or skipped info)
 5127: 
 5128:              - uploading new scan data
 5129: 
 5130:  Arguments:
 5131:   $r          - The Apache request object
 5132:   $file2grade - name of the file that contain the scanned data to score
 5133: 
 5134: =cut
 5135: 
 5136: sub scantron_selectphase {
 5137:     my ($r,$file2grade) = @_;
 5138:     my ($symb)=&get_symb($r);
 5139:     if (!$symb) {return '';}
 5140:     my $map_error;
 5141:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5142:     if ($map_error) {
 5143:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5144:         return;
 5145:     }
 5146:     my $default_form_data=&defaultFormData($symb);
 5147:     my $grading_menu_button=&show_grading_menu_form($symb);
 5148:     my $file_selector=&scantron_uploads($file2grade);
 5149:     my $format_selector=&scantron_scantab();
 5150:     my $CODE_selector=&scantron_CODElist();
 5151:     my $CODE_unique=&scantron_CODEunique();
 5152:     my $result;
 5153: 
 5154:     $ssi_error = 0;
 5155: 
 5156:     # Chunk of form to prompt for a file to grade and how:
 5157: 
 5158:     $result.= '
 5159:     <br />
 5160:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5161:     <input type="hidden" name="command" value="scantron_warning" />
 5162:     '.$default_form_data.'
 5163:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5164:        '.&Apache::loncommon::start_data_table_header_row().'
 5165:             <th colspan="2">
 5166:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5167:             </th>
 5168:        '.&Apache::loncommon::end_data_table_header_row().'
 5169:        '.&Apache::loncommon::start_data_table_row().'
 5170:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5171:        '.&Apache::loncommon::end_data_table_row().'
 5172:        '.&Apache::loncommon::start_data_table_row().'
 5173:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5174:        '.&Apache::loncommon::end_data_table_row().'
 5175:        '.&Apache::loncommon::start_data_table_row().'
 5176:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5177:        '.&Apache::loncommon::end_data_table_row().'
 5178:        '.&Apache::loncommon::start_data_table_row().'
 5179:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5180:        '.&Apache::loncommon::end_data_table_row().'
 5181:        '.&Apache::loncommon::start_data_table_row().'
 5182:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5183:        '.&Apache::loncommon::end_data_table_row().'
 5184:        '.&Apache::loncommon::start_data_table_row().'
 5185: 	    <td> '.&mt('Options:').' </td>
 5186:             <td>
 5187: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5188:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5189:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5190: 	    </td>
 5191:        '.&Apache::loncommon::end_data_table_row().'
 5192:        '.&Apache::loncommon::start_data_table_row().'
 5193:             <td colspan="2">
 5194:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5195:             </td>
 5196:        '.&Apache::loncommon::end_data_table_row().'
 5197:     '.&Apache::loncommon::end_data_table().'
 5198:     </form>
 5199: ';
 5200:    
 5201:     $r->print($result);
 5202: 
 5203:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5204:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5205: 
 5206: 	# Chunk of form to prompt for a scantron file upload.
 5207: 
 5208:         $r->print('
 5209:     <br />
 5210:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5211:        '.&Apache::loncommon::start_data_table_header_row().'
 5212:             <th>
 5213:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5214:             </th>
 5215:        '.&Apache::loncommon::end_data_table_header_row().'
 5216:        '.&Apache::loncommon::start_data_table_row().'
 5217:             <td>
 5218: ');
 5219:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5220:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5221:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5222:     $r->print('
 5223:               <script type="text/javascript" language="javascript">
 5224:     function checkUpload(formname) {
 5225: 	if (formname.upfile.value == "") {
 5226: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5227: 	    return false;
 5228: 	}
 5229: 	formname.submit();
 5230:     }
 5231:               </script>
 5232: 
 5233:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5234:                 '.$default_form_data.'
 5235:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5236:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5237:                 <input name="command" value="scantronupload_save" type="hidden" />
 5238:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5239:                 <br />
 5240:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5241:               </form>
 5242: ');
 5243: 
 5244:         $r->print('
 5245:             </td>
 5246:        '.&Apache::loncommon::end_data_table_row().'
 5247:        '.&Apache::loncommon::end_data_table().'
 5248: ');
 5249:     }
 5250: 
 5251:     # Chunk of the form that prompts to view a scoring office file,
 5252:     # corrected file, skipped records in a file.
 5253: 
 5254:     $r->print('
 5255:    <br />
 5256:    <form action="/adm/grades" name="scantron_download">
 5257:      '.$default_form_data.'
 5258:      <input type="hidden" name="command" value="scantron_download" />
 5259:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5260:        '.&Apache::loncommon::start_data_table_header_row().'
 5261:               <th>
 5262:                 &nbsp;'.&mt('Download a scoring office file').'
 5263:               </th>
 5264:        '.&Apache::loncommon::end_data_table_header_row().'
 5265:        '.&Apache::loncommon::start_data_table_row().'
 5266:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5267:                 <br />
 5268:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5269:        '.&Apache::loncommon::end_data_table_row().'
 5270:      '.&Apache::loncommon::end_data_table().'
 5271:    </form>
 5272:    <br />
 5273: ');
 5274: 
 5275:     &Apache::lonpickcode::code_list($r,2);
 5276: 
 5277:     $r->print('<br /><form method="post" name="checkscantron">'.
 5278:              $default_form_data."\n".
 5279:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5280:              &Apache::loncommon::start_data_table_header_row()."\n".
 5281:              '<th colspan="2">
 5282:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5283:              '</th>'."\n".
 5284:               &Apache::loncommon::end_data_table_header_row()."\n".
 5285:               &Apache::loncommon::start_data_table_row()."\n".
 5286:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5287:               '<td> '.$sequence_selector.' </td>'.
 5288:               &Apache::loncommon::end_data_table_row()."\n".
 5289:               &Apache::loncommon::start_data_table_row()."\n".
 5290:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5291:               '<td> '.$file_selector.' </td>'."\n".
 5292:               &Apache::loncommon::end_data_table_row()."\n".
 5293:               &Apache::loncommon::start_data_table_row()."\n".
 5294:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5295:               '<td> '.$format_selector.' </td>'."\n".
 5296:               &Apache::loncommon::end_data_table_row()."\n".
 5297:               &Apache::loncommon::start_data_table_row()."\n".
 5298:               '<td> '.&mt('Options').' </td>'."\n".
 5299:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5300:               &Apache::loncommon::end_data_table_row()."\n".
 5301:               &Apache::loncommon::start_data_table_row()."\n".
 5302:               '<td colspan="2">'."\n".
 5303:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5304:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5305:               '</td>'."\n".
 5306:               &Apache::loncommon::end_data_table_row()."\n".
 5307:               &Apache::loncommon::end_data_table()."\n".
 5308:               '</form><br />');
 5309:     $r->print($grading_menu_button);
 5310:     return;
 5311: }
 5312: 
 5313: =pod
 5314: 
 5315: =item get_scantron_config
 5316: 
 5317:    Parse and return the scantron configuration line selected as a
 5318:    hash of configuration file fields.
 5319: 
 5320:  Arguments:
 5321:     which - the name of the configuration to parse from the file.
 5322: 
 5323: 
 5324:  Returns:
 5325:             If the named configuration is not in the file, an empty
 5326:             hash is returned.
 5327:     a hash with the fields
 5328:       name         - internal name for the this configuration setup
 5329:       description  - text to display to operator that describes this config
 5330:       CODElocation - if 0 or the string 'none'
 5331:                           - no CODE exists for this config
 5332:                      if -1 || the string 'letter'
 5333:                           - a CODE exists for this config and is
 5334:                             a string of letters
 5335:                      Unsupported value (but planned for future support)
 5336:                           if a positive integer
 5337:                                - The CODE exists as the first n items from
 5338:                                  the question section of the form
 5339:                           if the string 'number'
 5340:                                - The CODE exists for this config and is
 5341:                                  a string of numbers
 5342:       CODEstart   - (only matter if a CODE exists) column in the line where
 5343:                      the CODE starts
 5344:       CODElength  - length of the CODE
 5345:       IDstart     - column where the student/employee ID starts
 5346:       IDlength    - length of the student/employee ID info
 5347:       Qstart      - column where the information from the bubbled
 5348:                     'questions' start
 5349:       Qlength     - number of columns comprising a single bubble line from
 5350:                     the sheet. (usually either 1 or 10)
 5351:       Qon         - either a single character representing the character used
 5352:                     to signal a bubble was chosen in the positional setup, or
 5353:                     the string 'letter' if the letter of the chosen bubble is
 5354:                     in the final, or 'number' if a number representing the
 5355:                     chosen bubble is in the file (1->A 0->J)
 5356:       Qoff        - the character used to represent that a bubble was
 5357:                     left blank
 5358:       PaperID     - if the scanning process generates a unique number for each
 5359:                     sheet scanned the column that this ID number starts in
 5360:       PaperIDlength - number of columns that comprise the unique ID number
 5361:                       for the sheet of paper
 5362:       FirstName   - column that the first name starts in
 5363:       FirstNameLength - number of columns that the first name spans
 5364:  
 5365:       LastName    - column that the last name starts in
 5366:       LastNameLength - number of columns that the last name spans
 5367: 
 5368: =cut
 5369: 
 5370: sub get_scantron_config {
 5371:     my ($which) = @_;
 5372:     my @lines = &get_scantronformat_file();
 5373:     my %config;
 5374:     #FIXME probably should move to XML it has already gotten a bit much now
 5375:     foreach my $line (@lines) {
 5376: 	my ($name,$descrip)=split(/:/,$line);
 5377: 	if ($name ne $which ) { next; }
 5378: 	chomp($line);
 5379: 	my @config=split(/:/,$line);
 5380: 	$config{'name'}=$config[0];
 5381: 	$config{'description'}=$config[1];
 5382: 	$config{'CODElocation'}=$config[2];
 5383: 	$config{'CODEstart'}=$config[3];
 5384: 	$config{'CODElength'}=$config[4];
 5385: 	$config{'IDstart'}=$config[5];
 5386: 	$config{'IDlength'}=$config[6];
 5387: 	$config{'Qstart'}=$config[7];
 5388:  	$config{'Qlength'}=$config[8];
 5389: 	$config{'Qoff'}=$config[9];
 5390: 	$config{'Qon'}=$config[10];
 5391: 	$config{'PaperID'}=$config[11];
 5392: 	$config{'PaperIDlength'}=$config[12];
 5393: 	$config{'FirstName'}=$config[13];
 5394: 	$config{'FirstNamelength'}=$config[14];
 5395: 	$config{'LastName'}=$config[15];
 5396: 	$config{'LastNamelength'}=$config[16];
 5397: 	last;
 5398:     }
 5399:     return %config;
 5400: }
 5401: 
 5402: =pod 
 5403: 
 5404: =item username_to_idmap
 5405: 
 5406:     creates a hash keyed by student/employee ID with values of the corresponding
 5407:     student username:domain.
 5408: 
 5409:   Arguments:
 5410: 
 5411:     $classlist - reference to the class list hash. This is a hash
 5412:                  keyed by student name:domain  whose elements are references
 5413:                  to arrays containing various chunks of information
 5414:                  about the student. (See loncoursedata for more info).
 5415: 
 5416:   Returns
 5417:     %idmap - the constructed hash
 5418: 
 5419: =cut
 5420: 
 5421: sub username_to_idmap {
 5422:     my ($classlist)= @_;
 5423:     my %idmap;
 5424:     foreach my $student (keys(%$classlist)) {
 5425: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5426: 	    $student;
 5427:     }
 5428:     return %idmap;
 5429: }
 5430: 
 5431: =pod
 5432: 
 5433: =item scantron_fixup_scanline
 5434: 
 5435:    Process a requested correction to a scanline.
 5436: 
 5437:   Arguments:
 5438:     $scantron_config   - hash from &get_scantron_config()
 5439:     $scan_data         - hash of correction information 
 5440:                           (see &scantron_getfile())
 5441:     $line              - existing scanline
 5442:     $whichline         - line number of the passed in scanline
 5443:     $field             - type of change to process 
 5444:                          (either 
 5445:                           'ID'     -> correct the student/employee ID
 5446:                           'CODE'   -> correct the CODE
 5447:                           'answer' -> fixup the submitted answers)
 5448:     
 5449:    $args               - hash of additional info,
 5450:                           - 'ID' 
 5451:                                'newid' -> studentID to use in replacement
 5452:                                           of existing one
 5453:                           - 'CODE' 
 5454:                                'CODE_ignore_dup' - set to true if duplicates
 5455:                                                    should be ignored.
 5456: 	                       'CODE' - is new code or 'use_unfound'
 5457:                                         if the existing unfound code should
 5458:                                         be used as is
 5459:                           - 'answer'
 5460:                                'response' - new answer or 'none' if blank
 5461:                                'question' - the bubble line to change
 5462:                                'questionnum' - the question identifier,
 5463:                                                may include subquestion. 
 5464: 
 5465:   Returns:
 5466:     $line - the modified scanline
 5467: 
 5468:   Side effects: 
 5469:     $scan_data - may be updated
 5470: 
 5471: =cut
 5472: 
 5473: 
 5474: sub scantron_fixup_scanline {
 5475:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5476:     if ($field eq 'ID') {
 5477: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5478: 	    return ($line,1,'New value too large');
 5479: 	}
 5480: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5481: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5482: 				     $args->{'newid'});
 5483: 	}
 5484: 	substr($line,$$scantron_config{'IDstart'}-1,
 5485: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5486: 	if ($args->{'newid'}=~/^\s*$/) {
 5487: 	    &scan_data($scan_data,"$whichline.user",
 5488: 		       $args->{'username'}.':'.$args->{'domain'});
 5489: 	}
 5490:     } elsif ($field eq 'CODE') {
 5491: 	if ($args->{'CODE_ignore_dup'}) {
 5492: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5493: 	}
 5494: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5495: 	if ($args->{'CODE'} ne 'use_unfound') {
 5496: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5497: 		return ($line,1,'New CODE value too large');
 5498: 	    }
 5499: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5500: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5501: 	    }
 5502: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5503: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5504: 	}
 5505:     } elsif ($field eq 'answer') {
 5506: 	my $length=$scantron_config->{'Qlength'};
 5507: 	my $off=$scantron_config->{'Qoff'};
 5508: 	my $on=$scantron_config->{'Qon'};
 5509: 	my $answer=${off}x$length;
 5510: 	if ($args->{'response'} eq 'none') {
 5511: 	    &scan_data($scan_data,
 5512: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5513: 	} else {
 5514: 	    if ($on eq 'letter') {
 5515: 		my @alphabet=('A'..'Z');
 5516: 		$answer=$alphabet[$args->{'response'}];
 5517: 	    } elsif ($on eq 'number') {
 5518: 		$answer=$args->{'response'}+1;
 5519: 		if ($answer == 10) { $answer = '0'; }
 5520: 	    } else {
 5521: 		substr($answer,$args->{'response'},1)=$on;
 5522: 	    }
 5523: 	    &scan_data($scan_data,
 5524: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5525: 	}
 5526: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5527: 	substr($line,$where-1,$length)=$answer;
 5528:     }
 5529:     return $line;
 5530: }
 5531: 
 5532: =pod
 5533: 
 5534: =item scan_data
 5535: 
 5536:     Edit or look up  an item in the scan_data hash.
 5537: 
 5538:   Arguments:
 5539:     $scan_data  - The hash (see scantron_getfile)
 5540:     $key        - shorthand of the key to edit (actual key is
 5541:                   scantronfilename_key).
 5542:     $data        - New value of the hash entry.
 5543:     $delete      - If true, the entry is removed from the hash.
 5544: 
 5545:   Returns:
 5546:     The new value of the hash table field (undefined if deleted).
 5547: 
 5548: =cut
 5549: 
 5550: 
 5551: sub scan_data {
 5552:     my ($scan_data,$key,$value,$delete)=@_;
 5553:     my $filename=$env{'form.scantron_selectfile'};
 5554:     if (defined($value)) {
 5555: 	$scan_data->{$filename.'_'.$key} = $value;
 5556:     }
 5557:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5558:     return $scan_data->{$filename.'_'.$key};
 5559: }
 5560: 
 5561: # ----- These first few routines are general use routines.----
 5562: 
 5563: # Return the number of occurences of a pattern in a string.
 5564: 
 5565: sub occurence_count {
 5566:     my ($string, $pattern) = @_;
 5567: 
 5568:     my @matches = ($string =~ /$pattern/g);
 5569: 
 5570:     return scalar(@matches);
 5571: }
 5572: 
 5573: 
 5574: # Take a string known to have digits and convert all the
 5575: # digits into letters in the range J,A..I.
 5576: 
 5577: sub digits_to_letters {
 5578:     my ($input) = @_;
 5579: 
 5580:     my @alphabet = ('J', 'A'..'I');
 5581: 
 5582:     my @input    = split(//, $input);
 5583:     my $output ='';
 5584:     for (my $i = 0; $i < scalar(@input); $i++) {
 5585: 	if ($input[$i] =~ /\d/) {
 5586: 	    $output .= $alphabet[$input[$i]];
 5587: 	} else {
 5588: 	    $output .= $input[$i];
 5589: 	}
 5590:     }
 5591:     return $output;
 5592: }
 5593: 
 5594: =pod 
 5595: 
 5596: =item scantron_parse_scanline
 5597: 
 5598:   Decodes a scanline from the selected scantron file
 5599: 
 5600:  Arguments:
 5601:     line             - The text of the scantron file line to process
 5602:     whichline        - Line number
 5603:     scantron_config  - Hash describing the format of the scantron lines.
 5604:     scan_data        - Hash of extra information about the scanline
 5605:                        (see scantron_getfile for more information)
 5606:     just_header      - True if should not process question answers but only
 5607:                        the stuff to the left of the answers.
 5608:  Returns:
 5609:    Hash containing the result of parsing the scanline
 5610: 
 5611:    Keys are all proceeded by the string 'scantron.'
 5612: 
 5613:        CODE    - the CODE in use for this scanline
 5614:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5615:                  by the operator
 5616:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5617:                             CODEs were selected, but the usage has been
 5618:                             forced by the operator
 5619:        ID  - student/employee ID
 5620:        PaperID - if used, the ID number printed on the sheet when the 
 5621:                  paper was scanned
 5622:        FirstName - first name from the sheet
 5623:        LastName  - last name from the sheet
 5624: 
 5625:      if just_header was not true these key may also exist
 5626: 
 5627:        missingerror - a list of bubble ranges that are considered to be answers
 5628:                       to a single question that don't have any bubbles filled in.
 5629:                       Of the form questionnumber:firstbubblenumber:count.
 5630:        doubleerror  - a list of bubble ranges that are considered to be answers
 5631:                       to a single question that have more than one bubble filled in.
 5632:                       Of the form questionnumber::firstbubblenumber:count
 5633:    
 5634:                 In the above, count is the number of bubble responses in the
 5635:                 input line needed to represent the possible answers to the question.
 5636:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5637:                 per line would have count = 2.
 5638: 
 5639:        maxquest     - the number of the last bubble line that was parsed
 5640: 
 5641:        (<number> starts at 1)
 5642:        <number>.answer - zero or more letters representing the selected
 5643:                          letters from the scanline for the bubble line 
 5644:                          <number>.
 5645:                          if blank there was either no bubble or there where
 5646:                          multiple bubbles, (consult the keys missingerror and
 5647:                          doubleerror if this is an error condition)
 5648: 
 5649: =cut
 5650: 
 5651: sub scantron_parse_scanline {
 5652:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5653: 
 5654:     my %record;
 5655:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5656:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5657:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5658:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5659: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5660: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5661: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5662: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5663: 	    $record{'scantron.CODE'}=substr($data,
 5664: 					    $$scantron_config{'CODEstart'}-1,
 5665: 					    $$scantron_config{'CODElength'});
 5666: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5667: 		$record{'scantron.useCODE'}=1;
 5668: 	    }
 5669: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5670: 		$record{'scantron.CODE_ignore_dup'}=1;
 5671: 	    }
 5672: 	} else {
 5673: 	    #FIXME interpret first N questions
 5674: 	}
 5675:     }
 5676:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5677: 				  $$scantron_config{'IDlength'});
 5678:     $record{'scantron.PaperID'}=
 5679: 	substr($data,$$scantron_config{'PaperID'}-1,
 5680: 	       $$scantron_config{'PaperIDlength'});
 5681:     $record{'scantron.FirstName'}=
 5682: 	substr($data,$$scantron_config{'FirstName'}-1,
 5683: 	       $$scantron_config{'FirstNamelength'});
 5684:     $record{'scantron.LastName'}=
 5685: 	substr($data,$$scantron_config{'LastName'}-1,
 5686: 	       $$scantron_config{'LastNamelength'});
 5687:     if ($just_header) { return \%record; }
 5688: 
 5689:     my @alphabet=('A'..'Z');
 5690:     my $questnum=0;
 5691:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5692: 
 5693:     chomp($questions);		# Get rid of any trailing \n.
 5694:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5695:     while (length($questions)) {
 5696: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5697:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5698:                              || 1;
 5699:         $questnum++;
 5700:         my $quest_id = $questnum;
 5701:         my $currentquest = substr($questions,0,$answer_length);
 5702:         $questions       = substr($questions,$answer_length);
 5703:         if (length($currentquest) < $answer_length) { next; }
 5704: 
 5705:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5706:             my $subquestnum = 1;
 5707:             my $subquestions = $currentquest;
 5708:             my @subanswers_needed = 
 5709:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5710:             foreach my $subans (@subanswers_needed) {
 5711:                 my $subans_length =
 5712:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5713:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5714:                 $subquestions   = substr($subquestions,$subans_length);
 5715:                 $quest_id = "$questnum.$subquestnum";
 5716:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5717:                     ($$scantron_config{'Qon'} eq 'number')) {
 5718:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5719:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5720:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5721:                 } else {
 5722:                     $ansnum = &scantron_validator_positional($ansnum,
 5723:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5724:                 }
 5725:                 $subquestnum ++;
 5726:             }
 5727:         } else {
 5728:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5729:                 ($$scantron_config{'Qon'} eq 'number')) {
 5730:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5731:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5732:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5733:             } else {
 5734:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5735:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5736:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5737:             }
 5738:         }
 5739:     }
 5740:     $record{'scantron.maxquest'}=$questnum;
 5741:     return \%record;
 5742: }
 5743: 
 5744: sub scantron_validator_lettnum {
 5745:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5746:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5747: 
 5748:     # Qon 'letter' implies for each slot in currquest we have:
 5749:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5750:     #    about anything else (esp. a value of Qoff) for missing
 5751:     #    bubbles.
 5752:     #
 5753:     # Qon 'number' implies each slot gives a digit that indexes the
 5754:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5755:     #    and * or ? for double bubbles on a single line.
 5756:     #
 5757: 
 5758:     my $matchon;
 5759:     if ($$scantron_config{'Qon'} eq 'letter') {
 5760:         $matchon = '[A-Z]';
 5761:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5762:         $matchon = '\d';
 5763:     }
 5764:     my $occurrences = 0;
 5765:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5766:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5767:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5768:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5769:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5770:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5771:         my @singlelines = split('',$currquest);
 5772:         foreach my $entry (@singlelines) {
 5773:             $occurrences = &occurence_count($entry,$matchon);
 5774:             if ($occurrences > 1) {
 5775:                 last;
 5776:             }
 5777:         } 
 5778:     } else {
 5779:         $occurrences = &occurence_count($currquest,$matchon); 
 5780:     }
 5781:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5782:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5783:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5784:             my $bubble = substr($currquest,$ans,1);
 5785:             if ($bubble =~ /$matchon/ ) {
 5786:                 if ($$scantron_config{'Qon'} eq 'number') {
 5787:                     if ($bubble == 0) {
 5788:                         $bubble = 10; 
 5789:                     }
 5790:                     $record->{"scantron.$ansnum.answer"} = 
 5791:                         $alphabet->[$bubble-1];
 5792:                 } else {
 5793:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5794:                 }
 5795:             } else {
 5796:                 $record->{"scantron.$ansnum.answer"}='';
 5797:             }
 5798:             $ansnum++;
 5799:         }
 5800:     } elsif (!defined($currquest)
 5801:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5802:             || (&occurence_count($currquest,$matchon) == 0)) {
 5803:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5804:             $record->{"scantron.$ansnum.answer"}='';
 5805:             $ansnum++;
 5806:         }
 5807:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5808:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5809:         }
 5810:     } else {
 5811:         if ($$scantron_config{'Qon'} eq 'number') {
 5812:             $currquest = &digits_to_letters($currquest);            
 5813:         }
 5814:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5815:             my $bubble = substr($currquest,$ans,1);
 5816:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5817:             $ansnum++;
 5818:         }
 5819:     }
 5820:     return $ansnum;
 5821: }
 5822: 
 5823: sub scantron_validator_positional {
 5824:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5825:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5826: 
 5827:     # Otherwise there's a positional notation;
 5828:     # each bubble line requires Qlength items, and there are filled in
 5829:     # bubbles for each case where there 'Qon' characters.
 5830:     #
 5831: 
 5832:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5833: 
 5834:     # If the split only gives us one element.. the full length of the
 5835:     # answer string, no bubbles are filled in:
 5836: 
 5837:     if ($answers_needed eq '') {
 5838:         return;
 5839:     }
 5840: 
 5841:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5842:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5843:             $record->{"scantron.$ansnum.answer"}='';
 5844:             $ansnum++;
 5845:         }
 5846:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5847:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5848:         }
 5849:     } elsif (scalar(@array) == 2) {
 5850:         my $location = length($array[0]);
 5851:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5852:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5853:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5854:             if ($ans eq $line_num) {
 5855:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5856:             } else {
 5857:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5858:             }
 5859:             $ansnum++;
 5860:          }
 5861:     } else {
 5862:         #  If there's more than one instance of a bubble character
 5863:         #  That's a double bubble; with positional notation we can
 5864:         #  record all the bubbles filled in as well as the
 5865:         #  fact this response consists of multiple bubbles.
 5866:         #
 5867:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5868:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5869:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5870:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5871:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5872:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5873:             my $doubleerror = 0;
 5874:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5875:                    (!$doubleerror)) {
 5876:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5877:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5878:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5879:                if (length(@currarray) > 2) {
 5880:                    $doubleerror = 1;
 5881:                } 
 5882:             }
 5883:             if ($doubleerror) {
 5884:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5885:             }
 5886:         } else {
 5887:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5888:         }
 5889:         my $item = $ansnum;
 5890:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5891:             $record->{"scantron.$item.answer"} = '';
 5892:             $item ++;
 5893:         }
 5894: 
 5895:         my @ans=@array;
 5896:         my $i=0;
 5897:         my $increment = 0;
 5898:         while ($#ans) {
 5899:             $i+=length($ans[0]) + $increment;
 5900:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5901:             my $bubble = $i%$$scantron_config{'Qlength'};
 5902:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5903:             shift(@ans);
 5904:             $increment = 1;
 5905:         }
 5906:         $ansnum += $answers_needed;
 5907:     }
 5908:     return $ansnum;
 5909: }
 5910: 
 5911: =pod
 5912: 
 5913: =item scantron_add_delay
 5914: 
 5915:    Adds an error message that occurred during the grading phase to a
 5916:    queue of messages to be shown after grading pass is complete
 5917: 
 5918:  Arguments:
 5919:    $delayqueue  - arrary ref of hash ref of error messages
 5920:    $scanline    - the scanline that caused the error
 5921:    $errormesage - the error message
 5922:    $errorcode   - a numeric code for the error
 5923: 
 5924:  Side Effects:
 5925:    updates the $delayqueue to have a new hash ref of the error
 5926: 
 5927: =cut
 5928: 
 5929: sub scantron_add_delay {
 5930:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5931:     push(@$delayqueue,
 5932: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5933: 	  'ecode' => $errorcode }
 5934: 	 );
 5935: }
 5936: 
 5937: =pod
 5938: 
 5939: =item scantron_find_student
 5940: 
 5941:    Finds the username for the current scanline
 5942: 
 5943:   Arguments:
 5944:    $scantron_record - hash result from scantron_parse_scanline
 5945:    $scan_data       - hash of correction information 
 5946:                       (see &scantron_getfile() form more information)
 5947:    $idmap           - hash from &username_to_idmap()
 5948:    $line            - number of current scanline
 5949:  
 5950:   Returns:
 5951:    Either 'username:domain' or undef if unknown
 5952: 
 5953: =cut
 5954: 
 5955: sub scantron_find_student {
 5956:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5957:     my $scanID=$$scantron_record{'scantron.ID'};
 5958:     if ($scanID =~ /^\s*$/) {
 5959:  	return &scan_data($scan_data,"$line.user");
 5960:     }
 5961:     foreach my $id (keys(%$idmap)) {
 5962:  	if (lc($id) eq lc($scanID)) {
 5963:  	    return $$idmap{$id};
 5964:  	}
 5965:     }
 5966:     return undef;
 5967: }
 5968: 
 5969: =pod
 5970: 
 5971: =item scantron_filter
 5972: 
 5973:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5974:    hidden resources was selected
 5975: 
 5976: =cut
 5977: 
 5978: sub scantron_filter {
 5979:     my ($curres)=@_;
 5980: 
 5981:     if (ref($curres) && $curres->is_problem()) {
 5982: 	# if the user has asked to not have either hidden
 5983: 	# or 'randomout' controlled resources to be graded
 5984: 	# don't include them
 5985: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5986: 	    && $curres->randomout) {
 5987: 	    return 0;
 5988: 	}
 5989: 	return 1;
 5990:     }
 5991:     return 0;
 5992: }
 5993: 
 5994: =pod
 5995: 
 5996: =item scantron_process_corrections
 5997: 
 5998:    Gets correction information out of submitted form data and corrects
 5999:    the scanline
 6000: 
 6001: =cut
 6002: 
 6003: sub scantron_process_corrections {
 6004:     my ($r) = @_;
 6005:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6006:     my ($scanlines,$scan_data)=&scantron_getfile();
 6007:     my $classlist=&Apache::loncoursedata::get_classlist();
 6008:     my $which=$env{'form.scantron_line'};
 6009:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6010:     my ($skip,$err,$errmsg);
 6011:     if ($env{'form.scantron_skip_record'}) {
 6012: 	$skip=1;
 6013:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6014: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6015: 	    $env{'form.scantron_domain'};
 6016: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6017: 	($line,$err,$errmsg)=
 6018: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6019: 				     'ID',{'newid'=>$newid,
 6020: 				    'username'=>$env{'form.scantron_username'},
 6021: 				    'domain'=>$env{'form.scantron_domain'}});
 6022:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6023: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6024: 	my $newCODE;
 6025: 	my %args;
 6026: 	if      ($resolution eq 'use_unfound') {
 6027: 	    $newCODE='use_unfound';
 6028: 	} elsif ($resolution eq 'use_found') {
 6029: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6030: 	} elsif ($resolution eq 'use_typed') {
 6031: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6032: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6033: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6034: 	}
 6035: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6036: 	    $args{'CODE_ignore_dup'}=1;
 6037: 	}
 6038: 	$args{'CODE'}=$newCODE;
 6039: 	($line,$err,$errmsg)=
 6040: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6041: 				     'CODE',\%args);
 6042:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6043: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6044: 	    ($line,$err,$errmsg)=
 6045: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6046: 					 $which,'answer',
 6047: 					 { 'question'=>$question,
 6048: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6049:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6050: 	    if ($err) { last; }
 6051: 	}
 6052:     }
 6053:     if ($err) {
 6054: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6055:     } else {
 6056: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6057: 	&scantron_putfile($scanlines,$scan_data);
 6058:     }
 6059: }
 6060: 
 6061: =pod
 6062: 
 6063: =item reset_skipping_status
 6064: 
 6065:    Forgets the current set of remember skipped scanlines (and thus
 6066:    reverts back to considering all lines in the
 6067:    scantron_skipped_<filename> file)
 6068: 
 6069: =cut
 6070: 
 6071: sub reset_skipping_status {
 6072:     my ($scanlines,$scan_data)=&scantron_getfile();
 6073:     &scan_data($scan_data,'remember_skipping',undef,1);
 6074:     &scantron_putfile(undef,$scan_data);
 6075: }
 6076: 
 6077: =pod
 6078: 
 6079: =item start_skipping
 6080: 
 6081:    Marks a scanline to be skipped. 
 6082: 
 6083: =cut
 6084: 
 6085: sub start_skipping {
 6086:     my ($scan_data,$i)=@_;
 6087:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6088:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6089: 	$remembered{$i}=2;
 6090:     } else {
 6091: 	$remembered{$i}=1;
 6092:     }
 6093:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6094: }
 6095: 
 6096: =pod
 6097: 
 6098: =item should_be_skipped
 6099: 
 6100:    Checks whether a scanline should be skipped.
 6101: 
 6102: =cut
 6103: 
 6104: sub should_be_skipped {
 6105:     my ($scanlines,$scan_data,$i)=@_;
 6106:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6107: 	# not redoing old skips
 6108: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6109: 	return 0;
 6110:     }
 6111:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6112: 
 6113:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6114: 	return 0;
 6115:     }
 6116:     return 1;
 6117: }
 6118: 
 6119: =pod
 6120: 
 6121: =item remember_current_skipped
 6122: 
 6123:    Discovers what scanlines are in the scantron_skipped_<filename>
 6124:    file and remembers them into scan_data for later use.
 6125: 
 6126: =cut
 6127: 
 6128: sub remember_current_skipped {
 6129:     my ($scanlines,$scan_data)=&scantron_getfile();
 6130:     my %to_remember;
 6131:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6132: 	if ($scanlines->{'skipped'}[$i]) {
 6133: 	    $to_remember{$i}=1;
 6134: 	}
 6135:     }
 6136: 
 6137:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6138:     &scantron_putfile(undef,$scan_data);
 6139: }
 6140: 
 6141: =pod
 6142: 
 6143: =item check_for_error
 6144: 
 6145:     Checks if there was an error when attempting to remove a specific
 6146:     scantron_.. bubble sheet data file. Prints out an error if
 6147:     something went wrong.
 6148: 
 6149: =cut
 6150: 
 6151: sub check_for_error {
 6152:     my ($r,$result)=@_;
 6153:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6154: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6155:     }
 6156: }
 6157: 
 6158: =pod
 6159: 
 6160: =item scantron_warning_screen
 6161: 
 6162:    Interstitial screen to make sure the operator has selected the
 6163:    correct options before we start the validation phase.
 6164: 
 6165: =cut
 6166: 
 6167: sub scantron_warning_screen {
 6168:     my ($button_text)=@_;
 6169:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6170:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6171:     my $CODElist;
 6172:     if ($scantron_config{'CODElocation'} &&
 6173: 	$scantron_config{'CODEstart'} &&
 6174: 	$scantron_config{'CODElength'}) {
 6175: 	$CODElist=$env{'form.scantron_CODElist'};
 6176: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6177: 	$CODElist=
 6178: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6179: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6180:     }
 6181:     return ('
 6182: <p>
 6183: <span class="LC_warning">
 6184: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6185: </p>
 6186: <table>
 6187: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6188: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6189: '.$CODElist.'
 6190: </table>
 6191: <br />
 6192: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6193: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6194: 
 6195: <br />
 6196: ');
 6197: }
 6198: 
 6199: =pod
 6200: 
 6201: =item scantron_do_warning
 6202: 
 6203:    Check if the operator has picked something for all required
 6204:    fields. Error out if something is missing.
 6205: 
 6206: =cut
 6207: 
 6208: sub scantron_do_warning {
 6209:     my ($r)=@_;
 6210:     my ($symb)=&get_symb($r);
 6211:     if (!$symb) {return '';}
 6212:     my $default_form_data=&defaultFormData($symb);
 6213:     $r->print(&scantron_form_start().$default_form_data);
 6214:     if ( $env{'form.selectpage'} eq '' ||
 6215: 	 $env{'form.scantron_selectfile'} eq '' ||
 6216: 	 $env{'form.scantron_format'} eq '' ) {
 6217: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6218: 	if ( $env{'form.selectpage'} eq '') {
 6219: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6220: 	} 
 6221: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6222: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6223: 	} 
 6224: 	if ( $env{'form.scantron_format'} eq '') {
 6225: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6226: 	} 
 6227:     } else {
 6228: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6229: 	$r->print('
 6230: '.$warning.'
 6231: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6232: <input type="hidden" name="command" value="scantron_validate" />
 6233: ');
 6234:     }
 6235:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6236:     return '';
 6237: }
 6238: 
 6239: =pod
 6240: 
 6241: =item scantron_form_start
 6242: 
 6243:     html hidden input for remembering all selected grading options
 6244: 
 6245: =cut
 6246: 
 6247: sub scantron_form_start {
 6248:     my ($max_bubble)=@_;
 6249:     my $result= <<SCANTRONFORM;
 6250: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6251:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6252:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6253:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6254:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6255:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6256:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6257:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6258:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6259:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6260: SCANTRONFORM
 6261: 
 6262:   my $line = 0;
 6263:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6264:        my $chunk =
 6265: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6266:        $chunk .=
 6267: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6268:        $chunk .= 
 6269:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6270:        $chunk .=
 6271:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6272:        $result .= $chunk;
 6273:        $line++;
 6274:    }
 6275:     return $result;
 6276: }
 6277: 
 6278: =pod
 6279: 
 6280: =item scantron_validate_file
 6281: 
 6282:     Dispatch routine for doing validation of a bubble sheet data file.
 6283: 
 6284:     Also processes any necessary information resets that need to
 6285:     occur before validation begins (ignore previous corrections,
 6286:     restarting the skipped records processing)
 6287: 
 6288: =cut
 6289: 
 6290: sub scantron_validate_file {
 6291:     my ($r) = @_;
 6292:     my ($symb)=&get_symb($r);
 6293:     if (!$symb) {return '';}
 6294:     my $default_form_data=&defaultFormData($symb);
 6295:     
 6296:     # do the detection of only doing skipped records first befroe we delete
 6297:     # them when doing the corrections reset
 6298:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6299: 	&reset_skipping_status();
 6300:     }
 6301:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6302: 	&remember_current_skipped();
 6303: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6304:     }
 6305: 
 6306:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6307: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6308: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6309: 	&check_for_error($r,&scantron_remove_scan_data());
 6310: 	$env{'form.scantron_options_ignore'}='done';
 6311:     }
 6312: 
 6313:     if ($env{'form.scantron_corrections'}) {
 6314: 	&scantron_process_corrections($r);
 6315:     }
 6316:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6317:     #get the student pick code ready
 6318:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6319:     my $nav_error;
 6320:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6321:     if ($nav_error) {
 6322:         $r->print(&navmap_errormsg());
 6323:         return '';
 6324:     }
 6325:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6326:     $r->print($result);
 6327:     
 6328:     my @validate_phases=( 'sequence',
 6329: 			  'ID',
 6330: 			  'CODE',
 6331: 			  'doublebubble',
 6332: 			  'missingbubbles');
 6333:     if (!$env{'form.validatepass'}) {
 6334: 	$env{'form.validatepass'} = 0;
 6335:     }
 6336:     my $currentphase=$env{'form.validatepass'};
 6337: 
 6338: 
 6339:     my $stop=0;
 6340:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6341: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6342: 	$r->rflush();
 6343: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6344: 	{
 6345: 	    no strict 'refs';
 6346: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6347: 	}
 6348:     }
 6349:     if (!$stop) {
 6350: 	my $warning=&scantron_warning_screen('Start Grading');
 6351: 	$r->print(&mt('Validation process complete.').'<br />'.
 6352:                   $warning.
 6353:                   &mt('Perform verification for each student after storage of submissions?').
 6354:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6355:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6356:                   ('&nbsp;'x3).'<label>'.
 6357:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6358:                   '</label></span><br />'.
 6359:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6360:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6361:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6362:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6363:     } else {
 6364: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6365: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6366:     }
 6367:     if ($stop) {
 6368: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6369: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6370: 	    $r->print(' '.&mt('this error').' <br />');
 6371: 
 6372: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6373: 	} else {
 6374:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6375: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6376:             } else {
 6377:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6378:             }
 6379: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6380: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6381: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6382: 	}
 6383:     }
 6384:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6385:     return '';
 6386: }
 6387: 
 6388: 
 6389: =pod
 6390: 
 6391: =item scantron_remove_file
 6392: 
 6393:    Removes the requested bubble sheet data file, makes sure that
 6394:    scantron_original_<filename> is never removed
 6395: 
 6396: 
 6397: =cut
 6398: 
 6399: sub scantron_remove_file {
 6400:     my ($which)=@_;
 6401:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6402:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6403:     my $file='scantron_';
 6404:     if ($which eq 'corrected' || $which eq 'skipped') {
 6405: 	$file.=$which.'_';
 6406:     } else {
 6407: 	return 'refused';
 6408:     }
 6409:     $file.=$env{'form.scantron_selectfile'};
 6410:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6411: }
 6412: 
 6413: 
 6414: =pod
 6415: 
 6416: =item scantron_remove_scan_data
 6417: 
 6418:    Removes all scan_data correction for the requested bubble sheet
 6419:    data file.  (In the case that both the are doing skipped records we need
 6420:    to remember the old skipped lines for the time being so that element
 6421:    persists for a while.)
 6422: 
 6423: =cut
 6424: 
 6425: sub scantron_remove_scan_data {
 6426:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6427:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6428:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6429:     my @todelete;
 6430:     my $filename=$env{'form.scantron_selectfile'};
 6431:     foreach my $key (@keys) {
 6432: 	if ($key=~/^\Q$filename\E_/) {
 6433: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6434: 		$key=~/remember_skipping/) {
 6435: 		next;
 6436: 	    }
 6437: 	    push(@todelete,$key);
 6438: 	}
 6439:     }
 6440:     my $result;
 6441:     if (@todelete) {
 6442: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6443: 				       \@todelete,$cdom,$cname);
 6444:     } else {
 6445: 	$result = 'ok';
 6446:     }
 6447:     return $result;
 6448: }
 6449: 
 6450: 
 6451: =pod
 6452: 
 6453: =item scantron_getfile
 6454: 
 6455:     Fetches the requested bubble sheet data file (all 3 versions), and
 6456:     the scan_data hash
 6457:   
 6458:   Arguments:
 6459:     None
 6460: 
 6461:   Returns:
 6462:     2 hash references
 6463: 
 6464:      - first one has 
 6465:          orig      -
 6466:          corrected -
 6467:          skipped   -  each of which points to an array ref of the specified
 6468:                       file broken up into individual lines
 6469:          count     - number of scanlines
 6470:  
 6471:      - second is the scan_data hash possible keys are
 6472:        ($number refers to scanline numbered $number and thus the key affects
 6473:         only that scanline
 6474:         $bubline refers to the specific bubble line element and the aspects
 6475:         refers to that specific bubble line element)
 6476: 
 6477:        $number.user - username:domain to use
 6478:        $number.CODE_ignore_dup 
 6479:                     - ignore the duplicate CODE error 
 6480:        $number.useCODE
 6481:                     - use the CODE in the scanline as is
 6482:        $number.no_bubble.$bubline
 6483:                     - it is valid that there is no bubbled in bubble
 6484:                       at $number $bubline
 6485:        remember_skipping
 6486:                     - a frozen hash containing keys of $number and values
 6487:                       of either 
 6488:                         1 - we are on a 'do skipped records pass' and plan
 6489:                             on processing this line
 6490:                         2 - we are on a 'do skipped records pass' and this
 6491:                             scanline has been marked to skip yet again
 6492: 
 6493: =cut
 6494: 
 6495: sub scantron_getfile {
 6496:     #FIXME really would prefer a scantron directory
 6497:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6498:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6499:     my $lines;
 6500:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6501: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6502:     my %scanlines;
 6503:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6504:     my $temp=$scanlines{'orig'};
 6505:     $scanlines{'count'}=$#$temp;
 6506: 
 6507:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6508: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6509:     if ($lines eq '-1') {
 6510: 	$scanlines{'corrected'}=[];
 6511:     } else {
 6512: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6513:     }
 6514:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6515: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6516:     if ($lines eq '-1') {
 6517: 	$scanlines{'skipped'}=[];
 6518:     } else {
 6519: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6520:     }
 6521:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6522:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6523:     my %scan_data = @tmp;
 6524:     return (\%scanlines,\%scan_data);
 6525: }
 6526: 
 6527: =pod
 6528: 
 6529: =item lonnet_putfile
 6530: 
 6531:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6532: 
 6533:  Arguments:
 6534:    $contents - data to store
 6535:    $filename - filename to store $contents into
 6536: 
 6537:  Returns:
 6538:    result value from &Apache::lonnet::finishuserfileupload
 6539: 
 6540: =cut
 6541: 
 6542: sub lonnet_putfile {
 6543:     my ($contents,$filename)=@_;
 6544:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6545:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6546:     $env{'form.sillywaytopassafilearound'}=$contents;
 6547:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6548: 
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item scantron_putfile
 6554: 
 6555:     Stores the current version of the bubble sheet data files, and the
 6556:     scan_data hash. (Does not modify the original version only the
 6557:     corrected and skipped versions.
 6558: 
 6559:  Arguments:
 6560:     $scanlines - hash ref that looks like the first return value from
 6561:                  &scantron_getfile()
 6562:     $scan_data - hash ref that looks like the second return value from
 6563:                  &scantron_getfile()
 6564: 
 6565: =cut
 6566: 
 6567: sub scantron_putfile {
 6568:     my ($scanlines,$scan_data) = @_;
 6569:     #FIXME really would prefer a scantron directory
 6570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6572:     if ($scanlines) {
 6573: 	my $prefix='scantron_';
 6574: # no need to update orig, shouldn't change
 6575: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6576: #		    $env{'form.scantron_selectfile'});
 6577: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6578: 			$prefix.'corrected_'.
 6579: 			$env{'form.scantron_selectfile'});
 6580: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6581: 			$prefix.'skipped_'.
 6582: 			$env{'form.scantron_selectfile'});
 6583:     }
 6584:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6585: }
 6586: 
 6587: =pod
 6588: 
 6589: =item scantron_get_line
 6590: 
 6591:    Returns the correct version of the scanline
 6592: 
 6593:  Arguments:
 6594:     $scanlines - hash ref that looks like the first return value from
 6595:                  &scantron_getfile()
 6596:     $scan_data - hash ref that looks like the second return value from
 6597:                  &scantron_getfile()
 6598:     $i         - number of the requested line (starts at 0)
 6599: 
 6600:  Returns:
 6601:    A scanline, (either the original or the corrected one if it
 6602:    exists), or undef if the requested scanline should be
 6603:    skipped. (Either because it's an skipped scanline, or it's an
 6604:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6605:    pass.
 6606: 
 6607: =cut
 6608: 
 6609: sub scantron_get_line {
 6610:     my ($scanlines,$scan_data,$i)=@_;
 6611:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6612:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6613:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6614:     return $scanlines->{'orig'}[$i]; 
 6615: }
 6616: 
 6617: =pod
 6618: 
 6619: =item scantron_todo_count
 6620: 
 6621:     Counts the number of scanlines that need processing.
 6622: 
 6623:  Arguments:
 6624:     $scanlines - hash ref that looks like the first return value from
 6625:                  &scantron_getfile()
 6626:     $scan_data - hash ref that looks like the second return value from
 6627:                  &scantron_getfile()
 6628: 
 6629:  Returns:
 6630:     $count - number of scanlines to process
 6631: 
 6632: =cut
 6633: 
 6634: sub get_todo_count {
 6635:     my ($scanlines,$scan_data)=@_;
 6636:     my $count=0;
 6637:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6638: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6639: 	if ($line=~/^[\s\cz]*$/) { next; }
 6640: 	$count++;
 6641:     }
 6642:     return $count;
 6643: }
 6644: 
 6645: =pod
 6646: 
 6647: =item scantron_put_line
 6648: 
 6649:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6650:     data file.
 6651: 
 6652:  Arguments:
 6653:     $scanlines - hash ref that looks like the first return value from
 6654:                  &scantron_getfile()
 6655:     $scan_data - hash ref that looks like the second return value from
 6656:                  &scantron_getfile()
 6657:     $i         - line number to update
 6658:     $newline   - contents of the updated scanline
 6659:     $skip      - if true make the line for skipping and update the
 6660:                  'skipped' file
 6661: 
 6662: =cut
 6663: 
 6664: sub scantron_put_line {
 6665:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6666:     if ($skip) {
 6667: 	$scanlines->{'skipped'}[$i]=$newline;
 6668: 	&start_skipping($scan_data,$i);
 6669: 	return;
 6670:     }
 6671:     $scanlines->{'corrected'}[$i]=$newline;
 6672: }
 6673: 
 6674: =pod
 6675: 
 6676: =item scantron_clear_skip
 6677: 
 6678:    Remove a line from the 'skipped' file
 6679: 
 6680:  Arguments:
 6681:     $scanlines - hash ref that looks like the first return value from
 6682:                  &scantron_getfile()
 6683:     $scan_data - hash ref that looks like the second return value from
 6684:                  &scantron_getfile()
 6685:     $i         - line number to update
 6686: 
 6687: =cut
 6688: 
 6689: sub scantron_clear_skip {
 6690:     my ($scanlines,$scan_data,$i)=@_;
 6691:     if (exists($scanlines->{'skipped'}[$i])) {
 6692: 	undef($scanlines->{'skipped'}[$i]);
 6693: 	return 1;
 6694:     }
 6695:     return 0;
 6696: }
 6697: 
 6698: =pod
 6699: 
 6700: =item scantron_filter_not_exam
 6701: 
 6702:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6703:    filter out resources that are not marked as 'exam' mode
 6704: 
 6705: =cut
 6706: 
 6707: sub scantron_filter_not_exam {
 6708:     my ($curres)=@_;
 6709:     
 6710:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6711: 	# if the user has asked to not have either hidden
 6712: 	# or 'randomout' controlled resources to be graded
 6713: 	# don't include them
 6714: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6715: 	    && $curres->randomout) {
 6716: 	    return 0;
 6717: 	}
 6718: 	return 1;
 6719:     }
 6720:     return 0;
 6721: }
 6722: 
 6723: =pod
 6724: 
 6725: =item scantron_validate_sequence
 6726: 
 6727:     Validates the selected sequence, checking for resource that are
 6728:     not set to exam mode.
 6729: 
 6730: =cut
 6731: 
 6732: sub scantron_validate_sequence {
 6733:     my ($r,$currentphase) = @_;
 6734: 
 6735:     my $navmap=Apache::lonnavmaps::navmap->new();
 6736:     unless (ref($navmap)) {
 6737:         $r->print(&navmap_errormsg());
 6738:         return (1,$currentphase);
 6739:     }
 6740:     my (undef,undef,$sequence)=
 6741: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6742: 
 6743:     my $map=$navmap->getResourceByUrl($sequence);
 6744: 
 6745:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6746:                                     value="ignore" />');
 6747:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6748: 	my @resources=
 6749: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6750: 	if (@resources) {
 6751: 	    $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>");
 6752: 	    return (1,$currentphase);
 6753: 	}
 6754:     }
 6755: 
 6756:     return (0,$currentphase+1);
 6757: }
 6758: 
 6759: 
 6760: 
 6761: sub scantron_validate_ID {
 6762:     my ($r,$currentphase) = @_;
 6763:     
 6764:     #get student info
 6765:     my $classlist=&Apache::loncoursedata::get_classlist();
 6766:     my %idmap=&username_to_idmap($classlist);
 6767: 
 6768:     #get scantron line setup
 6769:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6770:     my ($scanlines,$scan_data)=&scantron_getfile();
 6771: 
 6772:     my $nav_error;
 6773:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6774:     if ($nav_error) {
 6775:         $r->print(&navmap_errormsg());
 6776:         return(1,$currentphase);
 6777:     }
 6778: 
 6779:     my %found=('ids'=>{},'usernames'=>{});
 6780:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6781: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6782: 	if ($line=~/^[\s\cz]*$/) { next; }
 6783: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6784: 						 $scan_data);
 6785: 	my $id=$$scan_record{'scantron.ID'};
 6786: 	my $found;
 6787: 	foreach my $checkid (keys(%idmap)) {
 6788: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6789: 	}
 6790: 	if ($found) {
 6791: 	    my $username=$idmap{$found};
 6792: 	    if ($found{'ids'}{$found}) {
 6793: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6794: 					 $line,'duplicateID',$found);
 6795: 		return(1,$currentphase);
 6796: 	    } elsif ($found{'usernames'}{$username}) {
 6797: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6798: 					 $line,'duplicateID',$username);
 6799: 		return(1,$currentphase);
 6800: 	    }
 6801: 	    #FIXME store away line we previously saw the ID on to use above
 6802: 	    $found{'ids'}{$found}++;
 6803: 	    $found{'usernames'}{$username}++;
 6804: 	} else {
 6805: 	    if ($id =~ /^\s*$/) {
 6806: 		my $username=&scan_data($scan_data,"$i.user");
 6807: 		if (defined($username) && $found{'usernames'}{$username}) {
 6808: 		    &scantron_get_correction($r,$i,$scan_record,
 6809: 					     \%scantron_config,
 6810: 					     $line,'duplicateID',$username);
 6811: 		    return(1,$currentphase);
 6812: 		} elsif (!defined($username)) {
 6813: 		    &scantron_get_correction($r,$i,$scan_record,
 6814: 					     \%scantron_config,
 6815: 					     $line,'incorrectID');
 6816: 		    return(1,$currentphase);
 6817: 		}
 6818: 		$found{'usernames'}{$username}++;
 6819: 	    } else {
 6820: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6821: 					 $line,'incorrectID');
 6822: 		return(1,$currentphase);
 6823: 	    }
 6824: 	}
 6825:     }
 6826: 
 6827:     return (0,$currentphase+1);
 6828: }
 6829: 
 6830: 
 6831: sub scantron_get_correction {
 6832:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6833: #FIXME in the case of a duplicated ID the previous line, probably need
 6834: #to show both the current line and the previous one and allow skipping
 6835: #the previous one or the current one
 6836: 
 6837:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6838: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6839: 			    " for PaperID <tt>[_1]</tt>",
 6840: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6841:     } else {
 6842: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6843: 			    " in scanline [_1] <pre>[_2]</pre>",
 6844: 			    $i,$line)."</p> \n");
 6845:     }
 6846:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6847: 			  "The name on the paper is [_2],[_3]",
 6848: 			  $$scan_record{'scantron.ID'},
 6849: 			  $$scan_record{'scantron.LastName'},
 6850: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6851: 
 6852:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6853:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6854:                            # Array populated for doublebubble or
 6855:     my @lines_to_correct;  # missingbubble errors to build javascript
 6856:                            # to validate radio button checking   
 6857: 
 6858:     if ($error =~ /ID$/) {
 6859: 	if ($error eq 'incorrectID') {
 6860: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6861: 		      "</p>\n");
 6862: 	} elsif ($error eq 'duplicateID') {
 6863: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6864: 	}
 6865: 	$r->print($message);
 6866: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6867: 	$r->print("\n<ul><li> ");
 6868: 	#FIXME it would be nice if this sent back the user ID and
 6869: 	#could do partial userID matches
 6870: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6871: 				       'scantron_username','scantron_domain'));
 6872: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6873: 	$r->print("\n@".
 6874: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6875: 
 6876: 	$r->print('</li>');
 6877:     } elsif ($error =~ /CODE$/) {
 6878: 	if ($error eq 'incorrectCODE') {
 6879: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6880: 	} elsif ($error eq 'duplicateCODE') {
 6881: 	    $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");
 6882: 	}
 6883: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6884: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6885: 	$r->print($message);
 6886: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6887: 	$r->print("\n<br /> ");
 6888: 	my $i=0;
 6889: 	if ($error eq 'incorrectCODE' 
 6890: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6891: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6892: 	    if ($closest > 0) {
 6893: 		foreach my $testcode (@{$closest}) {
 6894: 		    my $checked='';
 6895: 		    if (!$i) { $checked=' checked="checked"'; }
 6896: 		    $r->print("
 6897:    <label>
 6898:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6899:        ".&mt("Use the similar CODE [_1] instead.",
 6900: 	    "<b><tt>".$testcode."</tt></b>")."
 6901:     </label>
 6902:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6903: 		    $r->print("\n<br />");
 6904: 		    $i++;
 6905: 		}
 6906: 	    }
 6907: 	}
 6908: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6909: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6910: 	    $r->print("
 6911:     <label>
 6912:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6913:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6914: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6915:     </label>");
 6916: 	    $r->print("\n<br />");
 6917: 	}
 6918: 
 6919: 	$r->print(<<ENDSCRIPT);
 6920: <script type="text/javascript">
 6921: function change_radio(field) {
 6922:     var slct=document.scantronupload.scantron_CODE_resolution;
 6923:     var i;
 6924:     for (i=0;i<slct.length;i++) {
 6925:         if (slct[i].value==field) { slct[i].checked=true; }
 6926:     }
 6927: }
 6928: </script>
 6929: ENDSCRIPT
 6930: 	my $href="/adm/pickcode?".
 6931: 	   "form=".&escape("scantronupload").
 6932: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6933: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6934: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6935: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6936: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6937: 	    $r->print("
 6938:     <label>
 6939:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6940:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6941: 	     "<a target='_blank' href='$href'>","</a>")."
 6942:     </label> 
 6943:     ".&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\')" />'));
 6944: 	    $r->print("\n<br />");
 6945: 	}
 6946: 	$r->print("
 6947:     <label>
 6948:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6949:        ".&mt("Use [_1] as the CODE.",
 6950: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6951: 	$r->print("\n<br /><br />");
 6952:     } elsif ($error eq 'doublebubble') {
 6953: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6954: 
 6955: 	# The form field scantron_questions is acutally a list of line numbers.
 6956: 	# represented by this form so:
 6957: 
 6958: 	my $line_list = &questions_to_line_list($arg);
 6959: 
 6960: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6961: 		  $line_list.'" />');
 6962: 	$r->print($message);
 6963: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6964: 	foreach my $question (@{$arg}) {
 6965: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6966:                                                    $scan_record, $error);
 6967:             push(@lines_to_correct,@linenums);
 6968: 	}
 6969:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6970:     } elsif ($error eq 'missingbubble') {
 6971: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6972: 	$r->print($message);
 6973: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6974: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6975: 
 6976: 	# The form field scantron_questions is actually a list of line numbers not
 6977: 	# a list of question numbers. Therefore:
 6978: 	#
 6979: 	
 6980: 	my $line_list = &questions_to_line_list($arg);
 6981: 
 6982: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6983: 		  $line_list.'" />');
 6984: 	foreach my $question (@{$arg}) {
 6985: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6986:                                                    $scan_record, $error);
 6987:             push(@lines_to_correct,@linenums);
 6988: 	}
 6989:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6990:     } else {
 6991: 	$r->print("\n<ul>");
 6992:     }
 6993:     $r->print("\n</li></ul>");
 6994: }
 6995: 
 6996: sub verify_bubbles_checked {
 6997:     my (@ansnums) = @_;
 6998:     my $ansnumstr = join('","',@ansnums);
 6999:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 7000:     my $output = (<<ENDSCRIPT);
 7001: <script type="text/javascript">
 7002: function verify_bubble_radio(form) {
 7003:     var ansnumArray = new Array ("$ansnumstr");
 7004:     var need_bubble_count = 0;
 7005:     for (var i=0; i<ansnumArray.length; i++) {
 7006:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 7007:             var bubble_picked = 0; 
 7008:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7009:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7010:                     bubble_picked = 1;
 7011:                 }
 7012:             }
 7013:             if (bubble_picked == 0) {
 7014:                 need_bubble_count ++;
 7015:             }
 7016:         }
 7017:     }
 7018:     if (need_bubble_count) {
 7019:         alert("$warning");
 7020:         return;
 7021:     }
 7022:     form.submit(); 
 7023: }
 7024: </script>
 7025: ENDSCRIPT
 7026:     return $output;
 7027: }
 7028: 
 7029: =pod
 7030: 
 7031: =item  questions_to_line_list
 7032: 
 7033: Converts a list of questions into a string of comma separated
 7034: line numbers in the answer sheet used by the questions.  This is
 7035: used to fill in the scantron_questions form field.
 7036: 
 7037:   Arguments:
 7038:      questions    - Reference to an array of questions.
 7039: 
 7040: =cut
 7041: 
 7042: 
 7043: sub questions_to_line_list {
 7044:     my ($questions) = @_;
 7045:     my @lines;
 7046: 
 7047:     foreach my $item (@{$questions}) {
 7048:         my $question = $item;
 7049:         my ($first,$count,$last);
 7050:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7051:             $question = $1;
 7052:             my $subquestion = $2;
 7053:             $first = $first_bubble_line{$question-1} + 1;
 7054:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7055:             my $subcount = 1;
 7056:             while ($subcount<$subquestion) {
 7057:                 $first += $subans[$subcount-1];
 7058:                 $subcount ++;
 7059:             }
 7060:             $count = $subans[$subquestion-1];
 7061:         } else {
 7062: 	    $first   = $first_bubble_line{$question-1} + 1;
 7063: 	    $count   = $bubble_lines_per_response{$question-1};
 7064:         }
 7065:         $last = $first+$count-1;
 7066:         push(@lines, ($first..$last));
 7067:     }
 7068:     return join(',', @lines);
 7069: }
 7070: 
 7071: =pod 
 7072: 
 7073: =item prompt_for_corrections
 7074: 
 7075: Prompts for a potentially multiline correction to the
 7076: user's bubbling (factors out common code from scantron_get_correction
 7077: for multi and missing bubble cases).
 7078: 
 7079:  Arguments:
 7080:    $r           - Apache request object.
 7081:    $question    - The question number to prompt for.
 7082:    $scan_config - The scantron file configuration hash.
 7083:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7084:    $error       - Type of error
 7085: 
 7086:  Implicit inputs:
 7087:    %bubble_lines_per_response   - Starting line numbers for each question.
 7088:                                   Numbered from 0 (but question numbers are from
 7089:                                   1.
 7090:    %first_bubble_line           - Starting bubble line for each question.
 7091:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7092:                                   type problems render as separate sub-questions, 
 7093:                                   in exam mode. This hash contains a 
 7094:                                   comma-separated list of the lines per 
 7095:                                   sub-question.
 7096:    %responsetype_per_response   - essayresponse, formularesponse,
 7097:                                   stringresponse, imageresponse, reactionresponse,
 7098:                                   and organicresponse type problem parts can have
 7099:                                   multiple lines per response if the weight
 7100:                                   assigned exceeds 10.  In this case, only
 7101:                                   one bubble per line is permitted, but more 
 7102:                                   than one line might contain bubbles, e.g.
 7103:                                   bubbling of: line 1 - J, line 2 - J, 
 7104:                                   line 3 - B would assign 22 points.  
 7105: 
 7106: =cut
 7107: 
 7108: sub prompt_for_corrections {
 7109:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7110:     my ($current_line,$lines);
 7111:     my @linenums;
 7112:     my $questionnum = $question;
 7113:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7114:         $question = $1;
 7115:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7116:         my $subquestion = $2;
 7117:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7118:         my $subcount = 1;
 7119:         while ($subcount<$subquestion) {
 7120:             $current_line += $subans[$subcount-1];
 7121:             $subcount ++;
 7122:         }
 7123:         $lines = $subans[$subquestion-1];
 7124:     } else {
 7125:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7126:         $lines        = $bubble_lines_per_response{$question-1};
 7127:     }
 7128:     if ($lines > 1) {
 7129:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7130:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7131:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7132:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7133:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7134:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7135:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7136:             $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 />');
 7137:         } else {
 7138:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7139:         }
 7140:     }
 7141:     for (my $i =0; $i < $lines; $i++) {
 7142:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7143: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7144: 	        		  $questionnum,$error,split('', $selected));
 7145:         push(@linenums,$current_line);
 7146: 	$current_line++;
 7147:     }
 7148:     if ($lines > 1) {
 7149: 	$r->print("<hr /><br />");
 7150:     }
 7151:     return @linenums;
 7152: }
 7153: 
 7154: =pod
 7155: 
 7156: =item scantron_bubble_selector
 7157:   
 7158:    Generates the html radiobuttons to correct a single bubble line
 7159:    possibly showing the existing the selected bubbles if known
 7160: 
 7161:  Arguments:
 7162:     $r           - Apache request object
 7163:     $scan_config - hash from &get_scantron_config()
 7164:     $line        - Number of the line being displayed.
 7165:     $questionnum - Question number (may include subquestion)
 7166:     $error       - Type of error.
 7167:     @selected    - Array of bubbles picked on this line.
 7168: 
 7169: =cut
 7170: 
 7171: sub scantron_bubble_selector {
 7172:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7173:     my $max=$$scan_config{'Qlength'};
 7174: 
 7175:     my $scmode=$$scan_config{'Qon'};
 7176:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7177: 
 7178:     my @alphabet=('A'..'Z');
 7179:     $r->print(&Apache::loncommon::start_data_table().
 7180:               &Apache::loncommon::start_data_table_row());
 7181:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7182:     for (my $i=0;$i<$max+1;$i++) {
 7183: 	$r->print("\n".'<td align="center">');
 7184: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7185: 	else { $r->print('&nbsp;'); }
 7186: 	$r->print('</td>');
 7187:     }
 7188:     $r->print(&Apache::loncommon::end_data_table_row().
 7189:               &Apache::loncommon::start_data_table_row());
 7190:     for (my $i=0;$i<$max;$i++) {
 7191: 	$r->print("\n".
 7192: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7193: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7194:     }
 7195:     my $nobub_checked = ' ';
 7196:     if ($error eq 'missingbubble') {
 7197:         $nobub_checked = ' checked = "checked" ';
 7198:     }
 7199:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7200: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7201:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7202:               $line.'" value="'.$questionnum.'" /></td>');
 7203:     $r->print(&Apache::loncommon::end_data_table_row().
 7204:               &Apache::loncommon::end_data_table());
 7205: }
 7206: 
 7207: =pod
 7208: 
 7209: =item num_matches
 7210: 
 7211:    Counts the number of characters that are the same between the two arguments.
 7212: 
 7213:  Arguments:
 7214:    $orig - CODE from the scanline
 7215:    $code - CODE to match against
 7216: 
 7217:  Returns:
 7218:    $count - integer count of the number of same characters between the
 7219:             two arguments
 7220: 
 7221: =cut
 7222: 
 7223: sub num_matches {
 7224:     my ($orig,$code) = @_;
 7225:     my @code=split(//,$code);
 7226:     my @orig=split(//,$orig);
 7227:     my $same=0;
 7228:     for (my $i=0;$i<scalar(@code);$i++) {
 7229: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7230:     }
 7231:     return $same;
 7232: }
 7233: 
 7234: =pod
 7235: 
 7236: =item scantron_get_closely_matching_CODEs
 7237: 
 7238:    Cycles through all CODEs and finds the set that has the greatest
 7239:    number of same characters as the provided CODE
 7240: 
 7241:  Arguments:
 7242:    $allcodes - hash ref returned by &get_codes()
 7243:    $CODE     - CODE from the current scanline
 7244: 
 7245:  Returns:
 7246:    2 element list
 7247:     - first elements is number of how closely matching the best fit is 
 7248:       (5 means best set has 5 matching characters)
 7249:     - second element is an arrary ref containing the set of valid CODEs
 7250:       that best fit the passed in CODE
 7251: 
 7252: =cut
 7253: 
 7254: sub scantron_get_closely_matching_CODEs {
 7255:     my ($allcodes,$CODE)=@_;
 7256:     my @CODEs;
 7257:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7258: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7259:     }
 7260: 
 7261:     return ($#CODEs,$CODEs[-1]);
 7262: }
 7263: 
 7264: =pod
 7265: 
 7266: =item get_codes
 7267: 
 7268:    Builds a hash which has keys of all of the valid CODEs from the selected
 7269:    set of remembered CODEs.
 7270: 
 7271:  Arguments:
 7272:   $old_name - name of the set of remembered CODEs
 7273:   $cdom     - domain of the course
 7274:   $cnum     - internal course name
 7275: 
 7276:  Returns:
 7277:   %allcodes - keys are the valid CODEs, values are all 1
 7278: 
 7279: =cut
 7280: 
 7281: sub get_codes {
 7282:     my ($old_name, $cdom, $cnum) = @_;
 7283:     if (!$old_name) {
 7284: 	$old_name=$env{'form.scantron_CODElist'};
 7285:     }
 7286:     if (!$cdom) {
 7287: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7288:     }
 7289:     if (!$cnum) {
 7290: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7291:     }
 7292:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7293: 				    $cdom,$cnum);
 7294:     my %allcodes;
 7295:     if ($result{"type\0$old_name"} eq 'number') {
 7296: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7297:     } else {
 7298: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7299:     }
 7300:     return %allcodes;
 7301: }
 7302: 
 7303: =pod
 7304: 
 7305: =item scantron_validate_CODE
 7306: 
 7307:    Validates all scanlines in the selected file to not have any
 7308:    invalid or underspecified CODEs and that none of the codes are
 7309:    duplicated if this was requested.
 7310: 
 7311: =cut
 7312: 
 7313: sub scantron_validate_CODE {
 7314:     my ($r,$currentphase) = @_;
 7315:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7316:     if ($scantron_config{'CODElocation'} &&
 7317: 	$scantron_config{'CODEstart'} &&
 7318: 	$scantron_config{'CODElength'}) {
 7319: 	if (!defined($env{'form.scantron_CODElist'})) {
 7320: 	    &FIXME_blow_up()
 7321: 	}
 7322:     } else {
 7323: 	return (0,$currentphase+1);
 7324:     }
 7325:     
 7326:     my %usedCODEs;
 7327: 
 7328:     my %allcodes=&get_codes();
 7329: 
 7330:     my $nav_error;
 7331:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7332:     if ($nav_error) {
 7333:         $r->print(&navmap_errormsg());
 7334:         return(1,$currentphase);
 7335:     }
 7336: 
 7337:     my ($scanlines,$scan_data)=&scantron_getfile();
 7338:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7339: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7340: 	if ($line=~/^[\s\cz]*$/) { next; }
 7341: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7342: 						 $scan_data);
 7343: 	my $CODE=$$scan_record{'scantron.CODE'};
 7344: 	my $error=0;
 7345: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7346: 	    &scantron_get_correction($r,$i,$scan_record,
 7347: 				     \%scantron_config,
 7348: 				     $line,'incorrectCODE',\%allcodes);
 7349: 	    return(1,$currentphase);
 7350: 	}
 7351: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7352: 	    && !$$scan_record{'scantron.useCODE'}) {
 7353: 	    &scantron_get_correction($r,$i,$scan_record,
 7354: 				     \%scantron_config,
 7355: 				     $line,'incorrectCODE',\%allcodes);
 7356: 	    return(1,$currentphase);
 7357: 	}
 7358: 	if (exists($usedCODEs{$CODE}) 
 7359: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7360: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7361: 	    &scantron_get_correction($r,$i,$scan_record,
 7362: 				     \%scantron_config,
 7363: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7364: 	    return(1,$currentphase);
 7365: 	}
 7366: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7367:     }
 7368:     return (0,$currentphase+1);
 7369: }
 7370: 
 7371: =pod
 7372: 
 7373: =item scantron_validate_doublebubble
 7374: 
 7375:    Validates all scanlines in the selected file to not have any
 7376:    bubble lines with multiple bubbles marked.
 7377: 
 7378: =cut
 7379: 
 7380: sub scantron_validate_doublebubble {
 7381:     my ($r,$currentphase) = @_;
 7382:     #get student info
 7383:     my $classlist=&Apache::loncoursedata::get_classlist();
 7384:     my %idmap=&username_to_idmap($classlist);
 7385: 
 7386:     #get scantron line setup
 7387:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7388:     my ($scanlines,$scan_data)=&scantron_getfile();
 7389:     my $nav_error;
 7390:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7391:     if ($nav_error) {
 7392:         $r->print(&navmap_errormsg());
 7393:         return(1,$currentphase);
 7394:     }
 7395: 
 7396:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7397: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7398: 	if ($line=~/^[\s\cz]*$/) { next; }
 7399: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7400: 						 $scan_data);
 7401: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7402: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7403: 				 'doublebubble',
 7404: 				 $$scan_record{'scantron.doubleerror'});
 7405:     	return (1,$currentphase);
 7406:     }
 7407:     return (0,$currentphase+1);
 7408: }
 7409: 
 7410: 
 7411: sub scantron_get_maxbubble {
 7412:     my ($nav_error) = @_;
 7413:     if (defined($env{'form.scantron_maxbubble'}) &&
 7414: 	$env{'form.scantron_maxbubble'}) {
 7415: 	&restore_bubble_lines();
 7416: 	return $env{'form.scantron_maxbubble'};
 7417:     }
 7418: 
 7419:     my (undef, undef, $sequence) =
 7420: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7421: 
 7422:     my $navmap=Apache::lonnavmaps::navmap->new();
 7423:     unless (ref($navmap)) {
 7424:         if (ref($nav_error)) {
 7425:             $$nav_error = 1;
 7426:         }
 7427:     }
 7428:     my $map=$navmap->getResourceByUrl($sequence);
 7429:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7430: 
 7431:     &Apache::lonxml::clear_problem_counter();
 7432: 
 7433:     my $uname       = $env{'user.name'};
 7434:     my $udom        = $env{'user.domain'};
 7435:     my $cid         = $env{'request.course.id'};
 7436:     my $total_lines = 0;
 7437:     %bubble_lines_per_response = ();
 7438:     %first_bubble_line         = ();
 7439:     %subdivided_bubble_lines   = ();
 7440:     %responsetype_per_response = ();
 7441: 
 7442:     my $response_number = 0;
 7443:     my $bubble_line     = 0;
 7444:     foreach my $resource (@resources) {
 7445:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7446:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7447: 	    foreach my $part_id (@{$parts}) {
 7448:                 my $lines;
 7449: 
 7450: 	        # TODO - make this a persistent hash not an array.
 7451: 
 7452:                 # optionresponse, matchresponse and rankresponse type items 
 7453:                 # render as separate sub-questions in exam mode.
 7454:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7455:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7456:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7457:                     my ($numbub,$numshown);
 7458:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7459:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7460:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7461:                         }
 7462:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7463:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7464:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7465:                         }
 7466:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7467:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7468:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7469:                         }
 7470:                     }
 7471:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7472:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7473:                     }
 7474:                     my $bubbles_per_line = 10;
 7475:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7476:                     if (($numbub % $bubbles_per_line) != 0) {
 7477:                         $inner_bubble_lines++;
 7478:                     }
 7479:                     for (my $i=0; $i<$numshown; $i++) {
 7480:                         $subdivided_bubble_lines{$response_number} .= 
 7481:                             $inner_bubble_lines.',';
 7482:                     }
 7483:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7484:                     $lines = $numshown * $inner_bubble_lines;
 7485:                 } else {
 7486:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7487:                 } 
 7488: 
 7489:                 $first_bubble_line{$response_number} = $bubble_line;
 7490: 	        $bubble_lines_per_response{$response_number} = $lines;
 7491:                 $responsetype_per_response{$response_number} = 
 7492:                     $analysis->{$part_id.'.type'};
 7493: 	        $response_number++;
 7494: 
 7495: 	        $bubble_line +=  $lines;
 7496: 	        $total_lines +=  $lines;
 7497: 	    }
 7498:         }
 7499:     }
 7500:     &Apache::lonnet::delenv('scantron.');
 7501: 
 7502:     &save_bubble_lines();
 7503:     $env{'form.scantron_maxbubble'} =
 7504: 	$total_lines;
 7505:     return $env{'form.scantron_maxbubble'};
 7506: }
 7507: 
 7508: sub scantron_validate_missingbubbles {
 7509:     my ($r,$currentphase) = @_;
 7510:     #get student info
 7511:     my $classlist=&Apache::loncoursedata::get_classlist();
 7512:     my %idmap=&username_to_idmap($classlist);
 7513: 
 7514:     #get scantron line setup
 7515:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7516:     my ($scanlines,$scan_data)=&scantron_getfile();
 7517:     my $nav_error;
 7518:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7519:     if ($nav_error) {
 7520:         return(1,$currentphase);
 7521:     }
 7522:     if (!$max_bubble) { $max_bubble=2**31; }
 7523:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7524: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7525: 	if ($line=~/^[\s\cz]*$/) { next; }
 7526: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7527: 						 $scan_data);
 7528: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7529: 	my @to_correct;
 7530: 	
 7531: 	# Probably here's where the error is...
 7532: 
 7533: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7534:             my $lastbubble;
 7535:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7536:                my $question = $1;
 7537:                my $subquestion = $2;
 7538:                if (!defined($first_bubble_line{$question -1})) { next; }
 7539:                my $first = $first_bubble_line{$question-1};
 7540:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7541:                my $subcount = 1;
 7542:                while ($subcount<$subquestion) {
 7543:                    $first += $subans[$subcount-1];
 7544:                    $subcount ++;
 7545:                }
 7546:                my $count = $subans[$subquestion-1];
 7547:                $lastbubble = $first + $count;
 7548:             } else {
 7549:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7550:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7551:             }
 7552:             if ($lastbubble > $max_bubble) { next; }
 7553: 	    push(@to_correct,$missing);
 7554: 	}
 7555: 	if (@to_correct) {
 7556: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7557: 				     $line,'missingbubble',\@to_correct);
 7558: 	    return (1,$currentphase);
 7559: 	}
 7560: 
 7561:     }
 7562:     return (0,$currentphase+1);
 7563: }
 7564: 
 7565: 
 7566: sub scantron_process_students {
 7567:     my ($r) = @_;
 7568: 
 7569:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7570:     my ($symb)=&get_symb($r);
 7571:     if (!$symb) {
 7572: 	return '';
 7573:     }
 7574:     my $default_form_data=&defaultFormData($symb);
 7575: 
 7576:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7577:     my ($scanlines,$scan_data)=&scantron_getfile();
 7578:     my $classlist=&Apache::loncoursedata::get_classlist();
 7579:     my %idmap=&username_to_idmap($classlist);
 7580:     my $navmap=Apache::lonnavmaps::navmap->new();
 7581:     unless (ref($navmap)) {
 7582:         $r->print(&navmap_errormsg());
 7583:         return '';
 7584:     }  
 7585:     my $map=$navmap->getResourceByUrl($sequence);
 7586:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7587:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7588:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7589:                             \%grader_randomlists_by_symb);
 7590:     foreach my $resource (@resources) {
 7591:         my $ressymb = $resource->symb();
 7592:         my ($analysis,$parts) =
 7593:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7594:                                       $env{'user.name'},$env{'user.domain'},1);
 7595:         $grader_partids_by_symb{$ressymb} = $parts;
 7596:         if (ref($analysis) eq 'HASH') {
 7597:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7598:                 $grader_randomlists_by_symb{$ressymb} = 
 7599:                     $analysis->{'parts_withrandomlist'};
 7600:             }
 7601:         }
 7602:     }
 7603: 
 7604:     my ($uname,$udom);
 7605:     my $result= <<SCANTRONFORM;
 7606: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7607:   <input type="hidden" name="command" value="scantron_configphase" />
 7608:   $default_form_data
 7609: SCANTRONFORM
 7610:     $r->print($result);
 7611: 
 7612:     my @delayqueue;
 7613:     my (%completedstudents,%scandata);
 7614:     
 7615:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7616:     my $count=&get_todo_count($scanlines,$scan_data);
 7617:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7618:  				    'Bubblesheet Progress',$count,
 7619: 				    'inline',undef,'scantronupload');
 7620:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7621: 					  'Processing first student');
 7622:     $r->print('<br />');
 7623:     my $start=&Time::HiRes::time();
 7624:     my $i=-1;
 7625:     my $started;
 7626: 
 7627:     my $nav_error;
 7628:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7629:     if ($nav_error) {
 7630:         $r->print(&navmap_errormsg());
 7631:         return '';
 7632:     }
 7633: 
 7634:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7635:     # the user and return.
 7636: 
 7637:     if ($ssi_error) {
 7638: 	$r->print("</form>");
 7639: 	&ssi_print_error($r);
 7640: 	$r->print(&show_grading_menu_form($symb));
 7641:         &Apache::lonnet::remove_lock($lock);
 7642: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7643:     }
 7644: 
 7645:     my %lettdig = &letter_to_digits();
 7646:     my $numletts = scalar(keys(%lettdig));
 7647: 
 7648:     while ($i<$scanlines->{'count'}) {
 7649:  	($uname,$udom)=('','');
 7650:  	$i++;
 7651:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7652:  	if ($line=~/^[\s\cz]*$/) { next; }
 7653: 	if ($started) {
 7654: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7655: 						     'last student');
 7656: 	}
 7657: 	$started=1;
 7658:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7659:  						 $scan_data);
 7660:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7661:  					      \%idmap,$i)) {
 7662:   	    &scantron_add_delay(\@delayqueue,$line,
 7663:  				'Unable to find a student that matches',1);
 7664:  	    next;
 7665:   	}
 7666:  	if (exists $completedstudents{$uname}) {
 7667:  	    &scantron_add_delay(\@delayqueue,$line,
 7668:  				'Student '.$uname.' has multiple sheets',2);
 7669:  	    next;
 7670:  	}
 7671:   	($uname,$udom)=split(/:/,$uname);
 7672: 
 7673:         my %partids_by_symb;
 7674:         foreach my $resource (@resources) {
 7675:             my $ressymb = $resource->symb();
 7676:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7677:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7678:                 my ($analysis,$parts) =
 7679:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7680:                 $partids_by_symb{$ressymb} = $parts;
 7681:             } else {
 7682:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7683:             }
 7684:         }
 7685: 
 7686: 	&Apache::lonxml::clear_problem_counter();
 7687:   	&Apache::lonnet::appenv($scan_record);
 7688: 
 7689: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7690: 	    &scantron_putfile($scanlines,$scan_data);
 7691: 	}
 7692: 	
 7693:         my $scancode;
 7694:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7695:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7696:             $scancode = $scan_record->{'scantron.CODE'};
 7697:         } else {
 7698:             $scancode = '';
 7699:         }
 7700: 
 7701:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7702:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7703:             $ssi_error = 0; # So end of handler error message does not trigger.
 7704:             $r->print("</form>");
 7705:             &ssi_print_error($r);
 7706:             $r->print(&show_grading_menu_form($symb));
 7707:             &Apache::lonnet::remove_lock($lock);
 7708:             return '';      # Why return ''?  Beats me.
 7709:         }
 7710: 
 7711: 	$completedstudents{$uname}={'line'=>$line};
 7712:         if ($env{'form.verifyrecord'}) {
 7713:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7714:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7715:             chomp($studentdata);
 7716:             $studentdata =~ s/\r$//;
 7717:             my $studentrecord = '';
 7718:             my $counter = -1;
 7719:             foreach my $resource (@resources) {
 7720:                 my $ressymb = $resource->symb();
 7721:                 ($counter,my $recording) =
 7722:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7723:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7724:                                              \%scantron_config,\%lettdig,$numletts);
 7725:                 $studentrecord .= $recording;
 7726:             }
 7727:             if ($studentrecord ne $studentdata) {
 7728:                 &Apache::lonxml::clear_problem_counter();
 7729:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7730:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7731:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7732:                     $r->print("</form>");
 7733:                     &ssi_print_error($r);
 7734:                     $r->print(&show_grading_menu_form($symb));
 7735:                     &Apache::lonnet::remove_lock($lock);
 7736:                     delete($completedstudents{$uname});
 7737:                     return '';
 7738:                 }
 7739:                 $counter = -1;
 7740:                 $studentrecord = '';
 7741:                 foreach my $resource (@resources) {
 7742:                     my $ressymb = $resource->symb();
 7743:                     ($counter,my $recording) =
 7744:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7745:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7746:                                                  \%scantron_config,\%lettdig,$numletts);
 7747:                     $studentrecord .= $recording;
 7748:                 }
 7749:                 if ($studentrecord ne $studentdata) {
 7750:                     $r->print('<p><span class="LC_error">');
 7751:                     if ($scancode eq '') {
 7752:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7753:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7754:                     } else {
 7755:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7756:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7757:                     }
 7758:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7759:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7760:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7761:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7762:                               &Apache::loncommon::start_data_table_row().
 7763:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7764:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7765:                               &Apache::loncommon::end_data_table_row().
 7766:                               &Apache::loncommon::start_data_table_row().
 7767:                               '<td>Stored submissions</td>'.
 7768:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7769:                               &Apache::loncommon::end_data_table_row().
 7770:                               &Apache::loncommon::end_data_table().'</p>');
 7771:                 } else {
 7772:                     $r->print('<br /><span class="LC_warning">'.
 7773:                              &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 />'.
 7774:                              &mt("As a consequence, this user's submission history records two tries.").
 7775:                                  '</span><br />');
 7776:                 }
 7777:             }
 7778:         }
 7779:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7780:     } continue {
 7781: 	&Apache::lonxml::clear_problem_counter();
 7782: 	&Apache::lonnet::delenv('scantron.');
 7783:     }
 7784:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7785:     &Apache::lonnet::remove_lock($lock);
 7786: #    my $lasttime = &Time::HiRes::time()-$start;
 7787: #    $r->print("<p>took $lasttime</p>");
 7788: 
 7789:     $r->print("</form>");
 7790:     $r->print(&show_grading_menu_form($symb));
 7791:     return '';
 7792: }
 7793: 
 7794: sub graders_resources_pass {
 7795:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7796:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7797:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7798:         foreach my $resource (@{$resources}) {
 7799:             my $ressymb = $resource->symb();
 7800:             my ($analysis,$parts) =
 7801:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7802:                                           $env{'user.name'},$env{'user.domain'},1);
 7803:             $grader_partids_by_symb->{$ressymb} = $parts;
 7804:             if (ref($analysis) eq 'HASH') {
 7805:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7806:                     $grader_randomlists_by_symb->{$ressymb} =
 7807:                         $analysis->{'parts_withrandomlist'};
 7808:                 }
 7809:             }
 7810:         }
 7811:     }
 7812:     return;
 7813: }
 7814: 
 7815: sub grade_student_bubbles {
 7816:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7817:     if (ref($resources) eq 'ARRAY') {
 7818:         my $count = 0;
 7819:         foreach my $resource (@{$resources}) {
 7820:             my $ressymb = $resource->symb();
 7821:             my %form = ('submitted'      => 'scantron',
 7822:                         'grade_target'   => 'grade',
 7823:                         'grade_username' => $uname,
 7824:                         'grade_domain'   => $udom,
 7825:                         'grade_courseid' => $env{'request.course.id'},
 7826:                         'grade_symb'     => $ressymb,
 7827:                         'CODE'           => $scancode
 7828:                        );
 7829:             if (ref($parts) eq 'HASH') {
 7830:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7831:                     foreach my $part (@{$parts->{$ressymb}}) {
 7832:                         $form{'scantron_questnum_start.'.$part} =
 7833:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7834:                         $count++;
 7835:                     }
 7836:                 }
 7837:             }
 7838:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7839:             return 'ssi_error' if ($ssi_error);
 7840:             last if (&Apache::loncommon::connection_aborted($r));
 7841:         }
 7842:     }
 7843:     return;
 7844: }
 7845: 
 7846: sub scantron_upload_scantron_data {
 7847:     my ($r)=@_;
 7848:     my $dom = $env{'request.role.domain'};
 7849:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7850:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7851:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7852: 							  'domainid',
 7853: 							  'coursename',$dom);
 7854:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7855:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7856:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7857:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7858:     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.");
 7859:     $r->print('
 7860: <script type="text/javascript" language="javascript">
 7861:     function checkUpload(formname) {
 7862: 	if (formname.upfile.value == "") {
 7863: 	    alert("'.$nofile_alert.'");
 7864: 	    return false;
 7865: 	}
 7866:         if (formname.courseid.value == "") {
 7867:             alert("'.$nocourseid_alert.'");
 7868:             return false;
 7869:         }
 7870: 	formname.submit();
 7871:     }
 7872: 
 7873:     function ToSyllabus() {
 7874:         var cdom = '."'$dom'".';
 7875:         var cnum = document.rules.courseid.value;
 7876:         if (cdom == "" || cdom == null) {
 7877:             return;
 7878:         }
 7879:         if (cnum == "" || cnum == null) {
 7880:            return;
 7881:         }
 7882:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7883:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7884:         return;
 7885:     }
 7886: 
 7887: </script>
 7888: 
 7889: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7890: 
 7891: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7892: '.$default_form_data.
 7893:   &Apache::lonhtmlcommon::start_pick_box().
 7894:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7895:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7896:   &Apache::lonhtmlcommon::row_closure().
 7897:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7898:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7899:   &Apache::lonhtmlcommon::row_closure().
 7900:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7901:   '<input name="domainid" type="hidden" />'.$domdesc.
 7902:   &Apache::lonhtmlcommon::row_closure().
 7903:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7904:   '<input type="file" name="upfile" size="50" />'.
 7905:   &Apache::lonhtmlcommon::row_closure(1).
 7906:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7907: 
 7908: <input name="command" value="scantronupload_save" type="hidden" />
 7909: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7910: </form>
 7911: ');
 7912:     return '';
 7913: }
 7914: 
 7915: 
 7916: sub scantron_upload_scantron_data_save {
 7917:     my($r)=@_;
 7918:     my ($symb)=&get_symb($r,1);
 7919:     my $doanotherupload=
 7920: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7921: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7922: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7923: 	'</form>'."\n";
 7924:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7925: 	!&Apache::lonnet::allowed('usc',
 7926: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7927: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7928: 	if ($symb) {
 7929: 	    $r->print(&show_grading_menu_form($symb));
 7930: 	} else {
 7931: 	    $r->print($doanotherupload);
 7932: 	}
 7933: 	return '';
 7934:     }
 7935:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7936:     my $uploadedfile;
 7937:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7938:     if (length($env{'form.upfile'}) < 2) {
 7939:         $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>'));
 7940:     } else {
 7941:         my $result = 
 7942:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7943:                                             $env{'form.courseid'},$env{'form.domainid'});
 7944: 	if ($result =~ m{^/uploaded/}) {
 7945: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7946:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7947: 			  '<span class="LC_filename">'.$result.'</span>'));
 7948:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7949:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7950:                                                        $env{'form.courseid'},$uploadedfile));
 7951: 	} else {
 7952: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7953:                           '<span class="LC_error">','</span>',$result,
 7954: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7955: 	}
 7956:     }
 7957:     if ($symb) {
 7958: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7959:     } else {
 7960: 	$r->print($doanotherupload);
 7961:     }
 7962:     return '';
 7963: }
 7964: 
 7965: sub validate_uploaded_scantron_file {
 7966:     my ($cdom,$cname,$fname) = @_;
 7967:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7968:     my @lines;
 7969:     if ($scanlines ne '-1') {
 7970:         @lines=split("\n",$scanlines,-1);
 7971:     }
 7972:     my $output;
 7973:     if (@lines) {
 7974:         my (%counts,$max_match_format);
 7975:         my ($max_match_count,$max_match_pct) = (0,0);
 7976:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7977:         my %idmap = &username_to_idmap($classlist);
 7978:         foreach my $key (keys(%idmap)) {
 7979:             my $lckey = lc($key);
 7980:             $idmap{$lckey} = $idmap{$key};
 7981:         }
 7982:         my %unique_formats;
 7983:         my @formatlines = &get_scantronformat_file();
 7984:         foreach my $line (@formatlines) {
 7985:             chomp($line);
 7986:             my @config = split(/:/,$line);
 7987:             my $idstart = $config[5];
 7988:             my $idlength = $config[6];
 7989:             if (($idstart ne '') && ($idlength > 0)) {
 7990:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 7991:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 7992:                 } else {
 7993:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 7994:                 }
 7995:             }
 7996:         }
 7997:         foreach my $key (keys(%unique_formats)) {
 7998:             my ($idstart,$idlength) = split(':',$key);
 7999:             %{$counts{$key}} = (
 8000:                                'found'   => 0,
 8001:                                'total'   => 0,
 8002:                               );
 8003:             foreach my $line (@lines) {
 8004:                 next if ($line =~ /^#/);
 8005:                 next if ($line =~ /^[\s\cz]*$/);
 8006:                 my $id = substr($line,$idstart-1,$idlength);
 8007:                 $id = lc($id);
 8008:                 if (exists($idmap{$id})) {
 8009:                     $counts{$key}{'found'} ++;
 8010:                 }
 8011:                 $counts{$key}{'total'} ++;
 8012:             }
 8013:             if ($counts{$key}{'total'}) {
 8014:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8015:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8016:                     $max_match_pct = $percent_match;
 8017:                     $max_match_format = $key;
 8018:                     $max_match_count = $counts{$key}{'total'};
 8019:                 }
 8020:             }
 8021:         }
 8022:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8023:             my $format_descs;
 8024:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8025:             for (my $i=0; $i<$numwithformat; $i++) {
 8026:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8027:                 if ($i<$numwithformat-2) {
 8028:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8029:                 } elsif ($i==$numwithformat-2) {
 8030:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8031:                 } elsif ($i==$numwithformat-1) {
 8032:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8033:                 }
 8034:             }
 8035:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8036:             $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).
 8037:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8038:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8039:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8040:                                   '<i>'.$cdom.'</i>').'</li>'.
 8041:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8042:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8043:                        '</ul>';
 8044:         }
 8045:     } else {
 8046:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8047:     }
 8048:     return $output;
 8049: }
 8050: 
 8051: sub valid_file {
 8052:     my ($requested_file)=@_;
 8053:     foreach my $filename (sort(&scantron_filenames())) {
 8054: 	if ($requested_file eq $filename) { return 1; }
 8055:     }
 8056:     return 0;
 8057: }
 8058: 
 8059: sub scantron_download_scantron_data {
 8060:     my ($r)=@_;
 8061:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8062:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8064:     my $file=$env{'form.scantron_selectfile'};
 8065:     if (! &valid_file($file)) {
 8066: 	$r->print('
 8067: 	<p>
 8068: 	    '.&mt('The requested file name was invalid.').'
 8069:         </p>
 8070: ');
 8071: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8072: 	return;
 8073:     }
 8074:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8075:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8076:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8077:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8078:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8079:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8080:     $r->print('
 8081:     <p>
 8082: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8083: 	      '<a href="'.$orig.'">','</a>').'
 8084:     </p>
 8085:     <p>
 8086: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8087: 	      '<a href="'.$corrected.'">','</a>').'
 8088:     </p>
 8089:     <p>
 8090: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8091: 	      '<a href="'.$skipped.'">','</a>').'
 8092:     </p>
 8093: ');
 8094:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8095:     return '';
 8096: }
 8097: 
 8098: sub checkscantron_results {
 8099:     my ($r) = @_;
 8100:     my ($symb)=&get_symb($r);
 8101:     if (!$symb) {return '';}
 8102:     my $grading_menu_button=&show_grading_menu_form($symb);
 8103:     my $cid = $env{'request.course.id'};
 8104:     my %lettdig = &letter_to_digits();
 8105:     my $numletts = scalar(keys(%lettdig));
 8106:     my $cnum = $env{'course.'.$cid.'.num'};
 8107:     my $cdom = $env{'course.'.$cid.'.domain'};
 8108:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8109:     my %record;
 8110:     my %scantron_config =
 8111:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8112:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8113:     my $classlist=&Apache::loncoursedata::get_classlist();
 8114:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8115:     my $navmap=Apache::lonnavmaps::navmap->new();
 8116:     unless (ref($navmap)) {
 8117:         $r->print(&navmap_errormsg());
 8118:         return '';
 8119:     }
 8120:     my $map=$navmap->getResourceByUrl($sequence);
 8121:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8122:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8123:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8124: 
 8125:     my ($uname,$udom);
 8126:     my (%scandata,%lastname,%bylast);
 8127:     $r->print('
 8128: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8129: 
 8130:     my @delayqueue;
 8131:     my %completedstudents;
 8132: 
 8133:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8134:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8135:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8136:                                     'inline',undef,'checkscantron');
 8137:     my ($username,$domain,$started);
 8138:     my $nav_error;
 8139:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8140:     if ($nav_error) {
 8141:         $r->print(&navmap_errormsg());
 8142:         return '';
 8143:     }
 8144: 
 8145:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8146:                                           'Processing first student');
 8147:     my $start=&Time::HiRes::time();
 8148:     my $i=-1;
 8149: 
 8150:     while ($i<$scanlines->{'count'}) {
 8151:         ($username,$domain,$uname)=('','','');
 8152:         $i++;
 8153:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8154:         if ($line=~/^[\s\cz]*$/) { next; }
 8155:         if ($started) {
 8156:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8157:                                                      'last student');
 8158:         }
 8159:         $started=1;
 8160:         my $scan_record=
 8161:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8162:                                                      $scan_data);
 8163:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8164:                                                               \%idmap,$i)) {
 8165:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8166:                                 'Unable to find a student that matches',1);
 8167:             next;
 8168:         }
 8169:         if (exists $completedstudents{$uname}) {
 8170:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8171:                                 'Student '.$uname.' has multiple sheets',2);
 8172:             next;
 8173:         }
 8174:         my $pid = $scan_record->{'scantron.ID'};
 8175:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8176:         push(@{$bylast{$lastname{$pid}}},$pid);
 8177:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8178:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8179:         chomp($scandata{$pid});
 8180:         $scandata{$pid} =~ s/\r$//;
 8181:         ($username,$domain)=split(/:/,$uname);
 8182:         my $counter = -1;
 8183:         foreach my $resource (@resources) {
 8184:             my $parts;
 8185:             my $ressymb = $resource->symb();
 8186:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8187:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8188:                 (my $analysis,$parts) =
 8189:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8190:             } else {
 8191:                 $parts = $grader_partids_by_symb{$ressymb};
 8192:             }
 8193:             ($counter,my $recording) =
 8194:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8195:                                          $scandata{$pid},$parts,
 8196:                                          \%scantron_config,\%lettdig,$numletts);
 8197:             $record{$pid} .= $recording;
 8198:         }
 8199:     }
 8200:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8201:     $r->print('<br />');
 8202:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8203:     $passed = 0;
 8204:     $failed = 0;
 8205:     $numstudents = 0;
 8206:     foreach my $last (sort(keys(%bylast))) {
 8207:         if (ref($bylast{$last}) eq 'ARRAY') {
 8208:             foreach my $pid (sort(@{$bylast{$last}})) {
 8209:                 my $showscandata = $scandata{$pid};
 8210:                 my $showrecord = $record{$pid};
 8211:                 $showscandata =~ s/\s/&nbsp;/g;
 8212:                 $showrecord =~ s/\s/&nbsp;/g;
 8213:                 if ($scandata{$pid} eq $record{$pid}) {
 8214:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8215:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8216: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8217: '</tr>'."\n".
 8218: '<tr class="'.$css_class.'">'."\n".
 8219: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8220:                     $passed ++;
 8221:                 } else {
 8222:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8223:                     $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".
 8224: '</tr>'."\n".
 8225: '<tr class="'.$css_class.'">'."\n".
 8226: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8227: '</tr>'."\n";
 8228:                     $failed ++;
 8229:                 }
 8230:                 $numstudents ++;
 8231:             }
 8232:         }
 8233:     }
 8234:     $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>');
 8235:     $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>');
 8236:     if ($passed) {
 8237:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8238:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8239:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8240:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8241:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8242:                  $okstudents."\n".
 8243:                  &Apache::loncommon::end_data_table().'<br />');
 8244:     }
 8245:     if ($failed) {
 8246:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8247:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8248:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8249:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8250:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8251:                  $badstudents."\n".
 8252:                  &Apache::loncommon::end_data_table()).'<br />'.
 8253:                  &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.');  
 8254:     }
 8255:     $r->print('</form><br />'.$grading_menu_button);
 8256:     return;
 8257: }
 8258: 
 8259: sub verify_scantron_grading {
 8260:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8261:         $scantron_config,$lettdig,$numletts) = @_;
 8262:     my ($record,%expected,%startpos);
 8263:     return ($counter,$record) if (!ref($resource));
 8264:     return ($counter,$record) if (!$resource->is_problem());
 8265:     my $symb = $resource->symb();
 8266:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8267:     foreach my $part_id (@{$partids}) {
 8268:         $counter ++;
 8269:         $expected{$part_id} = 0;
 8270:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8271:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8272:             foreach my $item (@sub_lines) {
 8273:                 $expected{$part_id} += $item;
 8274:             }
 8275:         } else {
 8276:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8277:         }
 8278:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8279:     }
 8280:     if ($symb) {
 8281:         my %recorded;
 8282:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8283:         if ($returnhash{'version'}) {
 8284:             my %lasthash=();
 8285:             my $version;
 8286:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8287:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8288:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8289:                 }
 8290:             }
 8291:             foreach my $key (keys(%lasthash)) {
 8292:                 if ($key =~ /\.scantron$/) {
 8293:                     my $value = &unescape($lasthash{$key});
 8294:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8295:                     if ($value eq '') {
 8296:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8297:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8298:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8299:                             }
 8300:                         }
 8301:                     } else {
 8302:                         my @tocheck;
 8303:                         my @items = split(//,$value);
 8304:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8305:                             ($scantron_config->{'Qon'} eq 'number')) {
 8306:                             if (@items < $expected{$part_id}) {
 8307:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8308:                                 my @singles = split(//,$fragment);
 8309:                                 foreach my $pos (@singles) {
 8310:                                     if ($pos eq ' ') {
 8311:                                         push(@tocheck,$pos);
 8312:                                     } else {
 8313:                                         my $next = shift(@items);
 8314:                                         push(@tocheck,$next);
 8315:                                     }
 8316:                                 }
 8317:                             } else {
 8318:                                 @tocheck = @items;
 8319:                             }
 8320:                             foreach my $letter (@tocheck) {
 8321:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8322:                                     if ($letter !~ /^[A-J]$/) {
 8323:                                         $letter = $scantron_config->{'Qoff'};
 8324:                                     }
 8325:                                     $recorded{$part_id} .= $letter;
 8326:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8327:                                     my $digit;
 8328:                                     if ($letter !~ /^[A-J]$/) {
 8329:                                         $digit = $scantron_config->{'Qoff'};
 8330:                                     } else {
 8331:                                         $digit = $lettdig->{$letter};
 8332:                                     }
 8333:                                     $recorded{$part_id} .= $digit;
 8334:                                 }
 8335:                             }
 8336:                         } else {
 8337:                             @tocheck = @items;
 8338:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8339:                                 my $curr_sub = shift(@tocheck);
 8340:                                 my $digit;
 8341:                                 if ($curr_sub =~ /^[A-J]$/) {
 8342:                                     $digit = $lettdig->{$curr_sub}-1;
 8343:                                 }
 8344:                                 if ($curr_sub eq 'J') {
 8345:                                     $digit += scalar($numletts);
 8346:                                 }
 8347:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8348:                                     if ($j == $digit) {
 8349:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8350:                                     } else {
 8351:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8352:                                     }
 8353:                                 }
 8354:                             }
 8355:                         }
 8356:                     }
 8357:                 }
 8358:             }
 8359:         }
 8360:         foreach my $part_id (@{$partids}) {
 8361:             if ($recorded{$part_id} eq '') {
 8362:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8363:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8364:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8365:                     }
 8366:                 }
 8367:             }
 8368:             $record .= $recorded{$part_id};
 8369:         }
 8370:     }
 8371:     return ($counter,$record);
 8372: }
 8373: 
 8374: sub letter_to_digits { 
 8375:     my %lettdig = (
 8376:                     A => 1,
 8377:                     B => 2,
 8378:                     C => 3,
 8379:                     D => 4,
 8380:                     E => 5,
 8381:                     F => 6,
 8382:                     G => 7,
 8383:                     H => 8,
 8384:                     I => 9,
 8385:                     J => 0,
 8386:                   );
 8387:     return %lettdig;
 8388: }
 8389: 
 8390: 
 8391: #-------- end of section for handling grading scantron forms -------
 8392: #
 8393: #-------------------------------------------------------------------
 8394: 
 8395: #-------------------------- Menu interface -------------------------
 8396: #
 8397: #--- Show a Grading Menu button - Calls the next routine ---
 8398: sub show_grading_menu_form {
 8399:     my ($symb)=@_;
 8400:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8401: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8402: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8403: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8404: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8405: 	'</form>'."\n";
 8406:     return $result;
 8407: }
 8408: 
 8409: # -- Retrieve choices for grading form
 8410: sub savedState {
 8411:     my %savedState = ();
 8412:     if ($env{'form.saveState'}) {
 8413: 	foreach (split(/:/,$env{'form.saveState'})) {
 8414: 	    my ($key,$value) = split(/=/,$_,2);
 8415: 	    $savedState{$key} = $value;
 8416: 	}
 8417:     }
 8418:     return \%savedState;
 8419: }
 8420: 
 8421: sub grading_menu {
 8422:     my ($request) = @_;
 8423:     my ($symb)=&get_symb($request);
 8424:     if (!$symb) {return '';}
 8425:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8426:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8427: 
 8428:     $request->print($table);
 8429:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8430:                   'handgrade'=>$hdgrade,
 8431:                   'probTitle'=>$probTitle,
 8432:                   'command'=>'submit_options',
 8433:                   'saveState'=>"",
 8434:                   'gradingMenu'=>1,
 8435:                   'showgrading'=>"yes");
 8436:     
 8437:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8438:     
 8439:     $fields{'command'} = 'csvform';
 8440:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8441:     
 8442:     $fields{'command'} = 'processclicker';
 8443:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8444:     
 8445:     $fields{'command'} = 'scantron_selectphase';
 8446:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8447:     
 8448:     my @menu = ({	categorytitle=>'Course Grading',
 8449:             items =>[
 8450:                         {	linktext => 'Manual Grading/View Submissions',
 8451:                     		url => $url1,
 8452:                     		permission => 'F',
 8453:                     		icon => 'edit-find-replace.png',
 8454:                     		linktitle => 'Start the process of hand grading submissions.'
 8455:                         },
 8456:                 	    {	linktext => 'Upload Scores',
 8457:                     		url => $url2,
 8458:                     		permission => 'F',
 8459:                     		icon => 'uploadscores.png',
 8460:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8461:                 	    },
 8462:                 	    {	linktext => 'Process Clicker',
 8463:                     		url => $url3,
 8464:                     		permission => 'F',
 8465:                     		icon => 'addClickerInfoFile.png',
 8466:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8467:                 	    },
 8468:                 	    {	linktext => 'Grade/Manage/Review Bubblesheet Forms',
 8469:                     		url => $url4,
 8470:                     		permission => 'F',
 8471:                     		icon => 'stat.png',
 8472:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8473:                 	    }
 8474:                     ]
 8475:             });
 8476: 
 8477:     #$fields{'command'} = 'verify';
 8478:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8479:     #
 8480:     # Create the menu
 8481:     my $Str;
 8482:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8483:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8484:     $Str .= '<input type="hidden" name="command" value="" />'.
 8485:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8486: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8487: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8488: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8489: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8490: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8491: 
 8492:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8493:     #$menudata->{'jscript'}
 8494:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8495:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8496:         ' /> '.
 8497:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8498:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8499: 
 8500:     $Str .="</form>\n";
 8501:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8502:     $request->print(<<GRADINGMENUJS);
 8503: <script type="text/javascript" language="javascript">
 8504:     function checkChoice(formname,val,cmdx) {
 8505: 	if (val <= 2) {
 8506: 	    var cmd = radioSelection(formname.radioChoice);
 8507: 	    var cmdsave = cmd;
 8508: 	} else {
 8509: 	    cmd = cmdx;
 8510: 	    cmdsave = 'submission';
 8511: 	}
 8512: 	formname.command.value = cmd;
 8513: 	if (val < 5) formname.submit();
 8514: 	if (val == 5) {
 8515: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8516: 	        return false;
 8517: 	    } else {
 8518: 	        formname.submit();
 8519: 	    }
 8520: 	}
 8521:     }
 8522: 
 8523:     function checkReceiptNo(formname,nospace) {
 8524: 	var receiptNo = formname.receipt.value;
 8525: 	var checkOpt = false;
 8526: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8527: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8528: 	if (checkOpt) {
 8529: 	    alert("$receiptalert");
 8530: 	    formname.receipt.value = "";
 8531: 	    formname.receipt.focus();
 8532: 	    return false;
 8533: 	}
 8534: 	return true;
 8535:     }
 8536: </script>
 8537: GRADINGMENUJS
 8538:     &commonJSfunctions($request);
 8539:     return $Str;    
 8540: }
 8541: 
 8542: 
 8543: #--- Displays the submissions first page -------
 8544: sub submit_options {
 8545:     my ($request) = @_;
 8546:     my ($symb)=&get_symb($request);
 8547:     if (!$symb) {return '';}
 8548:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8549: 
 8550:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8551:     $request->print(<<GRADINGMENUJS);
 8552: <script type="text/javascript" language="javascript">
 8553:     function checkChoice(formname,val,cmdx) {
 8554: 	if (val <= 2) {
 8555: 	    var cmd = radioSelection(formname.radioChoice);
 8556: 	    var cmdsave = cmd;
 8557: 	} else {
 8558: 	    cmd = cmdx;
 8559: 	    cmdsave = 'submission';
 8560: 	}
 8561: 	formname.command.value = cmd;
 8562: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8563: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8564: 	if (val < 5) formname.submit();
 8565: 	if (val == 5) {
 8566: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8567: 	    formname.submit();
 8568: 	}
 8569: 	if (val < 7) formname.submit();
 8570:     }
 8571: 
 8572:     function checkReceiptNo(formname,nospace) {
 8573: 	var receiptNo = formname.receipt.value;
 8574: 	var checkOpt = false;
 8575: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8576: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8577: 	if (checkOpt) {
 8578: 	    alert("$receiptalert");
 8579: 	    formname.receipt.value = "";
 8580: 	    formname.receipt.focus();
 8581: 	    return false;
 8582: 	}
 8583: 	return true;
 8584:     }
 8585: </script>
 8586: GRADINGMENUJS
 8587:     &commonJSfunctions($request);
 8588:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8589:     my $result;
 8590:     my (undef,$sections) = &getclasslist('all','0');
 8591:     my $savedState = &savedState();
 8592:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8593:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8594:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8595:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8596: 
 8597:     # Preselect sections
 8598:     my $selsec="";
 8599:     if (ref($sections)) {
 8600:         foreach my $section (sort(@$sections)) {
 8601:             $selsec.='<option value="'.$section.'" '.
 8602:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8603:         }
 8604:     }
 8605: 
 8606:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8607: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8608: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8609: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8610: 	'<input type="hidden" name="command"     value="" />'."\n".
 8611: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8612: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8613: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8614: 
 8615:     $result.='
 8616: <h2>
 8617:   '.&mt('Grade Current Resource').'
 8618: </h2>
 8619: <div>
 8620:   '.$table.'
 8621: </div>
 8622: 
 8623: <div class="LC_columnSection">
 8624:   
 8625:     <fieldset>
 8626:       <legend>
 8627:        '.&mt('Sections').'
 8628:       </legend>
 8629:       <select name="section" multiple="multiple" size="5">'."\n";
 8630:     $result.= $selsec;
 8631:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8632:     $result.='
 8633:     </fieldset>
 8634:   
 8635:     <fieldset>
 8636:       <legend>
 8637:         '.&mt('Groups').'
 8638:       </legend>
 8639:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8640:     </fieldset>
 8641:   
 8642:     <fieldset>
 8643:       <legend>
 8644:         '.&mt('Access Status').'
 8645:       </legend>
 8646:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8647:     </fieldset>
 8648:   
 8649:     <fieldset>
 8650:       <legend>
 8651:         '.&mt('Submission Status').'
 8652:       </legend>
 8653:       <select name="submitonly" size="5">
 8654: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8655: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8656: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8657: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8658:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8659:       </select>
 8660:     </fieldset>
 8661:   
 8662: </div>
 8663: 
 8664: <br />
 8665:           <div>
 8666:             <div>
 8667:               <label>
 8668:                 <input type="radio" name="radioChoice" value="submission" '.
 8669:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8670:              &mt('Select individual students to grade and view submissions.').'
 8671: 	      </label> 
 8672:             </div>
 8673:             <div>
 8674: 	      <label>
 8675:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8676:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8677:                     &mt('Grade all selected students in a grading table.').'
 8678:               </label>
 8679:             </div>
 8680:             <div>
 8681: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8682:             </div>
 8683:           </div>
 8684: 
 8685: 
 8686:         <h2>
 8687:          '.&mt('Grade Complete Folder for One Student').'
 8688:         </h2>
 8689:         <div>
 8690:             <div>
 8691:               <label>
 8692:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8693: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8694:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8695:               </label>
 8696:             </div>
 8697:             <div>
 8698: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8699:             </div>
 8700:         </div>
 8701:   </form>';
 8702:     $result .= &show_grading_menu_form($symb);
 8703:     return $result;
 8704: }
 8705: 
 8706: sub reset_perm {
 8707:     undef(%perm);
 8708: }
 8709: 
 8710: sub init_perm {
 8711:     &reset_perm();
 8712:     foreach my $test_perm ('vgr','mgr','opa') {
 8713: 
 8714: 	my $scope = $env{'request.course.id'};
 8715: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8716: 
 8717: 	    $scope .= '/'.$env{'request.course.sec'};
 8718: 	    if ( $perm{$test_perm}=
 8719: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8720: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8721: 	    } else {
 8722: 		delete($perm{$test_perm});
 8723: 	    }
 8724: 	}
 8725:     }
 8726: }
 8727: 
 8728: sub gather_clicker_ids {
 8729:     my %clicker_ids;
 8730: 
 8731:     my $classlist = &Apache::loncoursedata::get_classlist();
 8732: 
 8733:     # Set up a couple variables.
 8734:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8735:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8736:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8737: 
 8738:     foreach my $student (keys(%$classlist)) {
 8739:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8740:         my $username = $classlist->{$student}->[$username_idx];
 8741:         my $domain   = $classlist->{$student}->[$domain_idx];
 8742:         my $clickers =
 8743: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8744:         foreach my $id (split(/\,/,$clickers)) {
 8745:             $id=~s/^[\#0]+//;
 8746:             $id=~s/[\-\:]//g;
 8747:             if (exists($clicker_ids{$id})) {
 8748: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8749:             } else {
 8750: 		$clicker_ids{$id}=$username.':'.$domain;
 8751:             }
 8752:         }
 8753:     }
 8754:     return %clicker_ids;
 8755: }
 8756: 
 8757: sub gather_adv_clicker_ids {
 8758:     my %clicker_ids;
 8759:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8760:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8761:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8762:     foreach my $element (sort(keys(%coursepersonnel))) {
 8763:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8764:             my ($puname,$pudom)=split(/\:/,$person);
 8765:             my $clickers =
 8766: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8767:             foreach my $id (split(/\,/,$clickers)) {
 8768: 		$id=~s/^[\#0]+//;
 8769:                 $id=~s/[\-\:]//g;
 8770: 		if (exists($clicker_ids{$id})) {
 8771: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8772: 		} else {
 8773: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8774: 		}
 8775:             }
 8776:         }
 8777:     }
 8778:     return %clicker_ids;
 8779: }
 8780: 
 8781: sub clicker_grading_parameters {
 8782:     return ('gradingmechanism' => 'scalar',
 8783:             'upfiletype' => 'scalar',
 8784:             'specificid' => 'scalar',
 8785:             'pcorrect' => 'scalar',
 8786:             'pincorrect' => 'scalar');
 8787: }
 8788: 
 8789: sub process_clicker {
 8790:     my ($r)=@_;
 8791:     my ($symb)=&get_symb($r);
 8792:     if (!$symb) {return '';}
 8793:     my $result=&checkforfile_js();
 8794:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8795:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8796:     $result.=$table;
 8797:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8798:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8799:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8800:         '</b></td></tr>'."\n";
 8801:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8802: # Attempt to restore parameters from last session, set defaults if not present
 8803:     my %Saveable_Parameters=&clicker_grading_parameters();
 8804:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8805:                                                  \%Saveable_Parameters);
 8806:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8807:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8808:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8809:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8810: 
 8811:     my %checked;
 8812:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8813:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8814:           $checked{$gradingmechanism}=' checked="checked"';
 8815:        }
 8816:     }
 8817: 
 8818:     my $upload=&mt("Upload File");
 8819:     my $type=&mt("Type");
 8820:     my $attendance=&mt("Award points just for participation");
 8821:     my $personnel=&mt("Correctness determined from response by course personnel");
 8822:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8823:     my $given=&mt("Correctness determined from given list of answers").' '.
 8824:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8825:     my $pcorrect=&mt("Percentage points for correct solution");
 8826:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8827:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8828: 						   ('iclicker' => 'i>clicker',
 8829:                                                     'interwrite' => 'interwrite PRS'));
 8830:     $symb = &Apache::lonenc::check_encrypt($symb);
 8831:     $result.=<<ENDUPFORM;
 8832: <script type="text/javascript">
 8833: function sanitycheck() {
 8834: // Accept only integer percentages
 8835:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8836:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8837: // Find out grading choice
 8838:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8839:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8840:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8841:       }
 8842:    }
 8843: // By default, new choice equals user selection
 8844:    newgradingchoice=gradingchoice;
 8845: // Not good to give more points for false answers than correct ones
 8846:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8847:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8848:    }
 8849: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8850:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8851:       document.forms.gradesupload.pcorrect.value=100;
 8852:       document.forms.gradesupload.pincorrect.value=100;
 8853:    }
 8854: // If the values are different, cannot be attendance only
 8855:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8856:        (gradingchoice=='attendance')) {
 8857:        newgradingchoice='personnel';
 8858:    }
 8859: // Change grading choice to new one
 8860:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8861:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8862:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8863:       } else {
 8864:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8865:       }
 8866:    }
 8867: // Remember the old state
 8868:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8869: }
 8870: </script>
 8871: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8872: <input type="hidden" name="symb" value="$symb" />
 8873: <input type="hidden" name="command" value="processclickerfile" />
 8874: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8875: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8876: <input type="file" name="upfile" size="50" />
 8877: <br /><label>$type: $selectform</label>
 8878: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8879: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8880: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8881: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8882: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8883: <br />&nbsp;&nbsp;&nbsp;
 8884: <input type="text" name="givenanswer" size="50" />
 8885: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8886: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8887: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8888: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8889: </form>
 8890: ENDUPFORM
 8891:     $result.='</td></tr></table>'."\n".
 8892:              '</td></tr></table><br /><br />'."\n";
 8893:     $result.=&show_grading_menu_form($symb);
 8894:     return $result;
 8895: }
 8896: 
 8897: sub process_clicker_file {
 8898:     my ($r)=@_;
 8899:     my ($symb)=&get_symb($r);
 8900:     if (!$symb) {return '';}
 8901: 
 8902:     my %Saveable_Parameters=&clicker_grading_parameters();
 8903:     &Apache::loncommon::store_course_settings('grades_clicker',
 8904:                                               \%Saveable_Parameters);
 8905: 
 8906:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8907:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8908: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8909: 	return $result.&show_grading_menu_form($symb);
 8910:     }
 8911:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8912:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8913:         return $result.&show_grading_menu_form($symb);
 8914:     }
 8915:     my $foundgiven=0;
 8916:     if ($env{'form.gradingmechanism'} eq 'given') {
 8917:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8918:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8919:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8920:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8921:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8922:         $foundgiven=$#answers+1;
 8923:     }
 8924:     my %clicker_ids=&gather_clicker_ids();
 8925:     my %correct_ids;
 8926:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8927: 	%correct_ids=&gather_adv_clicker_ids();
 8928:     }
 8929:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8930: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8931: 	   $correct_id=~tr/a-z/A-Z/;
 8932: 	   $correct_id=~s/\s//gs;
 8933: 	   $correct_id=~s/^[\#0]+//;
 8934:            $correct_id=~s/[\-\:]//g;
 8935:            if ($correct_id) {
 8936: 	      $correct_ids{$correct_id}='specified';
 8937:            }
 8938:         }
 8939:     }
 8940:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8941: 	$result.=&mt('Score based on attendance only');
 8942:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8943:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8944:     } else {
 8945: 	my $number=0;
 8946: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8947: 	foreach my $id (sort(keys(%correct_ids))) {
 8948: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8949: 	    if ($correct_ids{$id} eq 'specified') {
 8950: 		$result.=&mt('specified');
 8951: 	    } else {
 8952: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8953: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8954: 	    }
 8955: 	    $number++;
 8956: 	}
 8957:         $result.="</p>\n";
 8958: 	if ($number==0) {
 8959: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8960: 	    return $result.&show_grading_menu_form($symb);
 8961: 	}
 8962:     }
 8963:     if (length($env{'form.upfile'}) < 2) {
 8964:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8965: 		     '<span class="LC_error">',
 8966: 		     '</span>',
 8967: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8968:         return $result.&show_grading_menu_form($symb);
 8969:     }
 8970: 
 8971: # Were able to get all the info needed, now analyze the file
 8972: 
 8973:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8974:     $symb = &Apache::lonenc::check_encrypt($symb);
 8975:     my $heading=&mt('Scanning clicker file');
 8976:     $result.=(<<ENDHEADER);
 8977: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8978: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8979: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8980: <form method="post" action="/adm/grades" name="clickeranalysis">
 8981: <input type="hidden" name="symb" value="$symb" />
 8982: <input type="hidden" name="command" value="assignclickergrades" />
 8983: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8984: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8985: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8986: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8987: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8988: ENDHEADER
 8989:     if ($env{'form.gradingmechanism'} eq 'given') {
 8990:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8991:     } 
 8992:     my %responses;
 8993:     my @questiontitles;
 8994:     my $errormsg='';
 8995:     my $number=0;
 8996:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8997: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8998:     }
 8999:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9000:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9001:     }
 9002:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9003:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9004:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9005:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9006:              '<br />';
 9007:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9008:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9009:        return $result.&show_grading_menu_form($symb);
 9010:     } 
 9011: # Remember Question Titles
 9012: # FIXME: Possibly need delimiter other than ":"
 9013:     for (my $i=0;$i<$number;$i++) {
 9014:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9015:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9016:     }
 9017:     my $correct_count=0;
 9018:     my $student_count=0;
 9019:     my $unknown_count=0;
 9020: # Match answers with usernames
 9021: # FIXME: Possibly need delimiter other than ":"
 9022:     foreach my $id (keys(%responses)) {
 9023:        if ($correct_ids{$id}) {
 9024:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9025:           $correct_count++;
 9026:        } elsif ($clicker_ids{$id}) {
 9027:           if ($clicker_ids{$id}=~/\,/) {
 9028: # More than one user with the same clicker!
 9029:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9030:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9031:                            "<select name='multi".$id."'>";
 9032:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9033:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9034:              }
 9035:              $result.='</select>';
 9036:              $unknown_count++;
 9037:           } else {
 9038: # Good: found one and only one user with the right clicker
 9039:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9040:              $student_count++;
 9041:           }
 9042:        } else {
 9043:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9044:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9045:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9046:                    "\n".&mt("Domain").": ".
 9047:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9048:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9049:           $unknown_count++;
 9050:        }
 9051:     }
 9052:     $result.='<hr />'.
 9053:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9054:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9055:        if ($correct_count==0) {
 9056:           $errormsg.="Found no correct answers answers for grading!";
 9057:        } elsif ($correct_count>1) {
 9058:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9059:        }
 9060:     }
 9061:     if ($number<1) {
 9062:        $errormsg.="Found no questions.";
 9063:     }
 9064:     if ($errormsg) {
 9065:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9066:     } else {
 9067:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9068:     }
 9069:     $result.='</form></td></tr></table>'."\n".
 9070:              '</td></tr></table><br /><br />'."\n";
 9071:     return $result.&show_grading_menu_form($symb);
 9072: }
 9073: 
 9074: sub iclicker_eval {
 9075:     my ($questiontitles,$responses)=@_;
 9076:     my $number=0;
 9077:     my $errormsg='';
 9078:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9079:         my %components=&Apache::loncommon::record_sep($line);
 9080:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9081: 	if ($entries[0] eq 'Question') {
 9082: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9083: 		$$questiontitles[$number]=$entries[$i];
 9084: 		$number++;
 9085: 	    }
 9086: 	}
 9087: 	if ($entries[0]=~/^\#/) {
 9088: 	    my $id=$entries[0];
 9089: 	    my @idresponses;
 9090: 	    $id=~s/^[\#0]+//;
 9091: 	    for (my $i=0;$i<$number;$i++) {
 9092: 		my $idx=3+$i*6;
 9093: 		push(@idresponses,$entries[$idx]);
 9094: 	    }
 9095: 	    $$responses{$id}=join(',',@idresponses);
 9096: 	}
 9097:     }
 9098:     return ($errormsg,$number);
 9099: }
 9100: 
 9101: sub interwrite_eval {
 9102:     my ($questiontitles,$responses)=@_;
 9103:     my $number=0;
 9104:     my $errormsg='';
 9105:     my $skipline=1;
 9106:     my $questionnumber=0;
 9107:     my %idresponses=();
 9108:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9109:         my %components=&Apache::loncommon::record_sep($line);
 9110:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9111:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9112:         if ($entries[1] eq 'Response') { $skipline=1; }
 9113:         next if $skipline;
 9114:         if ($entries[0]!=$questionnumber) {
 9115:            $questionnumber=$entries[0];
 9116:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9117:            $number++;
 9118:         }
 9119:         my $id=$entries[4];
 9120:         $id=~s/^[\#0]+//;
 9121:         $id=~s/^v\d*\://i;
 9122:         $id=~s/[\-\:]//g;
 9123:         $idresponses{$id}[$number]=$entries[6];
 9124:     }
 9125:     foreach my $id (keys(%idresponses)) {
 9126:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9127:        $$responses{$id}=~s/^\s*\,//;
 9128:     }
 9129:     return ($errormsg,$number);
 9130: }
 9131: 
 9132: sub assign_clicker_grades {
 9133:     my ($r)=@_;
 9134:     my ($symb)=&get_symb($r);
 9135:     if (!$symb) {return '';}
 9136: # See which part we are saving to
 9137:     my $res_error;
 9138:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9139:     if ($res_error) {
 9140:         return &navmap_errormsg();
 9141:     }
 9142: # FIXME: This should probably look for the first handgradeable part
 9143:     my $part=$$partlist[0];
 9144: # Start screen output
 9145:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9146: 
 9147:     my $heading=&mt('Assigning grades based on clicker file');
 9148:     $result.=(<<ENDHEADER);
 9149: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9150: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9151: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9152: ENDHEADER
 9153: # Get correct result
 9154: # FIXME: Possibly need delimiter other than ":"
 9155:     my @correct=();
 9156:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9157:     my $number=$env{'form.number'};
 9158:     if ($gradingmechanism ne 'attendance') {
 9159:        foreach my $key (keys(%env)) {
 9160:           if ($key=~/^form\.correct\:/) {
 9161:              my @input=split(/\,/,$env{$key});
 9162:              for (my $i=0;$i<=$#input;$i++) {
 9163:                  if (($correct[$i]) && ($input[$i]) &&
 9164:                      ($correct[$i] ne $input[$i])) {
 9165:                     $result.='<br /><span class="LC_warning">'.
 9166:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9167:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9168:                  } elsif ($input[$i]) {
 9169:                     $correct[$i]=$input[$i];
 9170:                  }
 9171:              }
 9172:           }
 9173:        }
 9174:        for (my $i=0;$i<$number;$i++) {
 9175:           if (!$correct[$i]) {
 9176:              $result.='<br /><span class="LC_error">'.
 9177:                       &mt('No correct result given for question "[_1]"!',
 9178:                           $env{'form.question:'.$i}).'</span>';
 9179:           }
 9180:        }
 9181:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9182:     }
 9183: # Start grading
 9184:     my $pcorrect=$env{'form.pcorrect'};
 9185:     my $pincorrect=$env{'form.pincorrect'};
 9186:     my $storecount=0;
 9187:     foreach my $key (keys(%env)) {
 9188:        my $user='';
 9189:        if ($key=~/^form\.student\:(.*)$/) {
 9190:           $user=$1;
 9191:        }
 9192:        if ($key=~/^form\.unknown\:(.*)$/) {
 9193:           my $id=$1;
 9194:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9195:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9196:           } elsif ($env{'form.multi'.$id}) {
 9197:              $user=$env{'form.multi'.$id};
 9198:           }
 9199:        }
 9200:        if ($user) { 
 9201:           my @answer=split(/\,/,$env{$key});
 9202:           my $sum=0;
 9203:           my $realnumber=$number;
 9204:           for (my $i=0;$i<$number;$i++) {
 9205:              if  ($correct[$i] eq '-') {
 9206:                 $realnumber--;
 9207:              } elsif ($answer[$i]) {
 9208:                 if ($gradingmechanism eq 'attendance') {
 9209:                    $sum+=$pcorrect;
 9210:                 } elsif ($correct[$i] eq '*') {
 9211:                    $sum+=$pcorrect;
 9212:                 } else {
 9213:                    if ($answer[$i] eq $correct[$i]) {
 9214:                       $sum+=$pcorrect;
 9215:                    } else {
 9216:                       $sum+=$pincorrect;
 9217:                    }
 9218:                 }
 9219:              }
 9220:           }
 9221:           my $ave=$sum/(100*$realnumber);
 9222: # Store
 9223:           my ($username,$domain)=split(/\:/,$user);
 9224:           my %grades=();
 9225:           $grades{"resource.$part.solved"}='correct_by_override';
 9226:           $grades{"resource.$part.awarded"}=$ave;
 9227:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9228:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9229:                                                  $env{'request.course.id'},
 9230:                                                  $domain,$username);
 9231:           if ($returncode ne 'ok') {
 9232:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9233:           } else {
 9234:              $storecount++;
 9235:           }
 9236:        }
 9237:     }
 9238: # We are done
 9239:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9240:              '</td></tr></table>'."\n".
 9241:              '</td></tr></table><br /><br />'."\n";
 9242:     return $result.&show_grading_menu_form($symb);
 9243: }
 9244: 
 9245: sub navmap_errormsg {
 9246:     return '<div class="LC_error">'.
 9247:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9248:            &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>').
 9249:            '</div>';
 9250: }
 9251: 
 9252: sub handler {
 9253:     my $request=$_[0];
 9254:     &reset_caches();
 9255:     if ($env{'browser.mathml'}) {
 9256: 	&Apache::loncommon::content_type($request,'text/xml');
 9257:     } else {
 9258: 	&Apache::loncommon::content_type($request,'text/html');
 9259:     }
 9260:     $request->send_http_header;
 9261:     return '' if $request->header_only;
 9262:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9263:     my $symb=&get_symb($request,1);
 9264:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9265:     my $command=$commands[0];
 9266: 
 9267:     if ($#commands > 0) {
 9268: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9269:     }
 9270: 
 9271:     $ssi_error = 0;
 9272:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9273:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9274:                                           {'bread_crumbs' => $brcrum}));
 9275:     if ($symb eq '' && $command eq '') {
 9276: 	if ($env{'user.adv'}) {
 9277: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9278: 		($env{'form.codethree'})) {
 9279: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9280: 		    $env{'form.codethree'};
 9281: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9282: 		    &Apache::lonnet::checkin($token);
 9283: 		if ($tsymb) {
 9284: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9285: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9286: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9287: 					  ('grade_username' => $tuname,
 9288: 					   'grade_domain' => $tudom,
 9289: 					   'grade_courseid' => $tcrsid,
 9290: 					   'grade_symb' => $tsymb)));
 9291: 		    } else {
 9292: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9293: 		    }
 9294: 		} else {
 9295: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9296: 		}
 9297: 	    } else {
 9298: 		$request->print(&Apache::lonxml::tokeninputfield());
 9299: 	    }
 9300: 	}
 9301:     } else {
 9302: 	&init_perm();
 9303: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9304: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9305: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9306: 	    &pickStudentPage($request);
 9307: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9308: 	    &displayPage($request);
 9309: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9310: 	    &updateGradeByPage($request);
 9311: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9312: 	    &processGroup($request);
 9313: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9314: 	    $request->print(&grading_menu($request));
 9315: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9316: 	    $request->print(&submit_options($request));
 9317: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9318: 	    $request->print(&viewgrades($request));
 9319: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9320: 	    $request->print(&processHandGrade($request));
 9321: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9322: 	    $request->print(&editgrades($request));
 9323: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9324: 	    $request->print(&verifyreceipt($request));
 9325:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9326:             $request->print(&process_clicker($request));
 9327:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9328:             $request->print(&process_clicker_file($request));
 9329:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9330:             $request->print(&assign_clicker_grades($request));
 9331: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9332: 	    $request->print(&upcsvScores_form($request));
 9333: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9334: 	    $request->print(&csvupload($request));
 9335: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9336: 	    $request->print(&csvuploadmap($request));
 9337: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9338: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9339: 		$request->print(&csvuploadoptions($request));
 9340: 	    } else {
 9341: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9342: 		    $env{'form.upfile_associate'} = 'reverse';
 9343: 		} else {
 9344: 		    $env{'form.upfile_associate'} = 'forward';
 9345: 		}
 9346: 		$request->print(&csvuploadmap($request));
 9347: 	    }
 9348: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9349: 	    $request->print(&csvuploadassign($request));
 9350: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9351: 	    $request->print(&scantron_selectphase($request));
 9352:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9353:  	    $request->print(&scantron_do_warning($request));
 9354: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9355: 	    $request->print(&scantron_validate_file($request));
 9356: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9357: 	    $request->print(&scantron_process_students($request));
 9358:  	} elsif ($command eq 'scantronupload' && 
 9359:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9360: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9361:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9362:  	} elsif ($command eq 'scantronupload_save' &&
 9363:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9364: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9365:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9366:  	} elsif ($command eq 'scantron_download' &&
 9367: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9368:  	    $request->print(&scantron_download_scantron_data($request));
 9369:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9370:             $request->print(&checkscantron_results($request));     
 9371: 	} elsif ($command) {
 9372: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9373: 	}
 9374:     }
 9375:     if ($ssi_error) {
 9376: 	&ssi_print_error($request);
 9377:     }
 9378:     $request->print(&Apache::loncommon::end_page());
 9379:     &reset_caches();
 9380:     return '';
 9381: }
 9382: 
 9383: 1;
 9384: 
 9385: __END__;
 9386: 
 9387: 
 9388: =head1 NAME
 9389: 
 9390: Apache::grades
 9391: 
 9392: =head1 SYNOPSIS
 9393: 
 9394: Handles the viewing of grades.
 9395: 
 9396: This is part of the LearningOnline Network with CAPA project
 9397: described at http://www.lon-capa.org.
 9398: 
 9399: =head1 OVERVIEW
 9400: 
 9401: Do an ssi with retries:
 9402: While I'd love to factor out this with the vesrion in lonprintout,
 9403: 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
 9404: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9405: 
 9406: At least the logic that drives this has been pulled out into loncommon.
 9407: 
 9408: 
 9409: 
 9410: ssi_with_retries - Does the server side include of a resource.
 9411:                      if the ssi call returns an error we'll retry it up to
 9412:                      the number of times requested by the caller.
 9413:                      If we still have a proble, no text is appended to the
 9414:                      output and we set some global variables.
 9415:                      to indicate to the caller an SSI error occurred.  
 9416:                      All of this is supposed to deal with the issues described
 9417:                      in LonCAPA BZ 5631 see:
 9418:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9419:                      by informing the user that this happened.
 9420: 
 9421: Parameters:
 9422:   resource   - The resource to include.  This is passed directly, without
 9423:                interpretation to lonnet::ssi.
 9424:   form       - The form hash parameters that guide the interpretation of the resource
 9425:                
 9426:   retries    - Number of retries allowed before giving up completely.
 9427: Returns:
 9428:   On success, returns the rendered resource identified by the resource parameter.
 9429: Side Effects:
 9430:   The following global variables can be set:
 9431:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9432:                               It is up to the caller to initialize this to false
 9433:                               if desired.
 9434:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9435:                               of the resource that could not be rendered by the ssi
 9436:                               call.
 9437:    ssi_error_message   - The error string fetched from the ssi response
 9438:                               in the event of an error.
 9439: 
 9440: 
 9441: =head1 HANDLER SUBROUTINE
 9442: 
 9443: ssi_with_retries()
 9444: 
 9445: =head1 SUBROUTINES
 9446: 
 9447: =over
 9448: 
 9449: =item scantron_get_correction() : 
 9450: 
 9451:    Builds the interface screen to interact with the operator to fix a
 9452:    specific error condition in a specific scanline
 9453: 
 9454:  Arguments:
 9455:     $r           - Apache request object
 9456:     $i           - number of the current scanline
 9457:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9458:     $scan_config - hash ref as returned from &get_scantron_config()
 9459:     $line        - full contents of the current scanline
 9460:     $error       - error condition, valid values are
 9461:                    'incorrectCODE', 'duplicateCODE',
 9462:                    'doublebubble', 'missingbubble',
 9463:                    'duplicateID', 'incorrectID'
 9464:     $arg         - extra information needed
 9465:        For errors:
 9466:          - duplicateID   - paper number that this studentID was seen before on
 9467:          - duplicateCODE - array ref of the paper numbers this CODE was
 9468:                            seen on before
 9469:          - incorrectCODE - current incorrect CODE 
 9470:          - doublebubble  - array ref of the bubble lines that have double
 9471:                            bubble errors
 9472:          - missingbubble - array ref of the bubble lines that have missing
 9473:                            bubble errors
 9474: 
 9475: =item  scantron_get_maxbubble() : 
 9476: 
 9477:    Arguments:
 9478:        $nav_error  - Reference to scalar which is a flag to indicate a
 9479:                       failure to retrieve a navmap object.
 9480:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9481:        calling routine should trap the error condition and display the warning
 9482:        found in &navmap_errormsg().
 9483: 
 9484:    Returns the maximum number of bubble lines that are expected to
 9485:    occur. Does this by walking the selected sequence rendering the
 9486:    resource and then checking &Apache::lonxml::get_problem_counter()
 9487:    for what the current value of the problem counter is.
 9488: 
 9489:    Caches the results to $env{'form.scantron_maxbubble'},
 9490:    $env{'form.scantron.bubble_lines.n'}, 
 9491:    $env{'form.scantron.first_bubble_line.n'} and
 9492:    $env{"form.scantron.sub_bubblelines.n"}
 9493:    which are the total number of bubble, lines, the number of bubble
 9494:    lines for response n and number of the first bubble line for response n,
 9495:    and a comma separated list of numbers of bubble lines for sub-questions
 9496:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9497: 
 9498: 
 9499: =item  scantron_validate_missingbubbles() : 
 9500: 
 9501:    Validates all scanlines in the selected file to not have any
 9502:     answers that don't have bubbles that have not been verified
 9503:     to be bubble free.
 9504: 
 9505: =item  scantron_process_students() : 
 9506: 
 9507:    Routine that does the actual grading of the bubble sheet information.
 9508: 
 9509:    The parsed scanline hash is added to %env 
 9510: 
 9511:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9512:    foreach resource , with the form data of
 9513: 
 9514: 	'submitted'     =>'scantron' 
 9515: 	'grade_target'  =>'grade',
 9516: 	'grade_username'=> username of student
 9517: 	'grade_domain'  => domain of student
 9518: 	'grade_courseid'=> of course
 9519: 	'grade_symb'    => symb of resource to grade
 9520: 
 9521:     This triggers a grading pass. The problem grading code takes care
 9522:     of converting the bubbled letter information (now in %env) into a
 9523:     valid submission.
 9524: 
 9525: =item  scantron_upload_scantron_data() :
 9526: 
 9527:     Creates the screen for adding a new bubble sheet data file to a course.
 9528: 
 9529: =item  scantron_upload_scantron_data_save() : 
 9530: 
 9531:    Adds a provided bubble information data file to the course if user
 9532:    has the correct privileges to do so. 
 9533: 
 9534: =item  valid_file() :
 9535: 
 9536:    Validates that the requested bubble data file exists in the course.
 9537: 
 9538: =item  scantron_download_scantron_data() : 
 9539: 
 9540:    Shows a list of the three internal files (original, corrected,
 9541:    skipped) for a specific bubble sheet data file that exists in the
 9542:    course.
 9543: 
 9544: =item  scantron_validate_ID() : 
 9545: 
 9546:    Validates all scanlines in the selected file to not have any
 9547:    invalid or underspecified student/employee IDs
 9548: 
 9549: =item navmap_errormsg() :
 9550: 
 9551:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9552:    Should be called whenever the request to instantiate a navmap object fails.  
 9553: 
 9554: =back
 9555: 
 9556: =cut

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