File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.574.2.11: download - view: text, annotated - select for diffs
Wed Apr 14 16:34:54 2010 UTC (14 years ago) by raeburn
Branches: version_2_9_X
CVS tags: version_2_8_99_1
- scantron -> bubblesheet in text displayed to users.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.574.2.11 2010/04/14 16:34:54 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\">id $partID</span>)";
  199:     } else {
  200: 	$display=$partID;
  201:     }
  202:     return $display;
  203: }
  204: 
  205: #--- Show resource title
  206: #--- and parts and response type
  207: sub showResourceInfo {
  208:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
  209:     my $col=3;
  210:     if ($checkboxes) { $col=4; }
  211:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  212:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
  213:     if (ref($res_error)) {
  214:         if ($$res_error) {
  215:             return;
  216:         }
  217:     }
  218:     $result .='<table border="0">';
  219:     my %resptype = ();
  220:     my $hdgrade='no';
  221:     my %partsseen;
  222:     foreach my $partID (sort(keys(%$responseType))) {
  223: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  224: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  225: 	    my $responsetype = $responseType->{$partID}->{$resID};
  226: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  227: 	    $result.='<tr>';
  228: 	    if ($checkboxes) {
  229: 		if (exists($partsseen{$partID})) {
  230: 		    $result.="<td>&nbsp;</td>";
  231: 		} else {
  232: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  233: 		}
  234: 		$partsseen{$partID}=1;
  235: 	    }
  236: 	    my $display_part=&get_display_part($partID,$symb);
  237: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  238:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  239: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  240: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  241: 	}
  242:     }
  243:     $result.='</table>'."\n";
  244:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  245: }
  246: 
  247: sub reset_caches {
  248:     &reset_analyze_cache();
  249:     &reset_perm();
  250: }
  251: 
  252: {
  253:     my %analyze_cache;
  254:     my %analyze_cache_formkeys;
  255: 
  256:     sub reset_analyze_cache {
  257: 	undef(%analyze_cache);
  258:         undef(%analyze_cache_formkeys);
  259:     }
  260: 
  261:     sub get_analyze {
  262: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
  263: 	my $key = "$symb\0$uname\0$udom";
  264: 	if (exists($analyze_cache{$key})) {
  265:             my $getupdate = 0;
  266:             if (ref($add_to_hash) eq 'HASH') {
  267:                 foreach my $item (keys(%{$add_to_hash})) {
  268:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
  269:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
  270:                             $getupdate = 1;
  271:                             last;
  272:                         }
  273:                     } else {
  274:                         $getupdate = 1;
  275:                     }
  276:                 }
  277:             }
  278:             if (!$getupdate) {
  279:                 return $analyze_cache{$key};
  280:             }
  281:         }
  282: 
  283: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  284: 	$url=&Apache::lonnet::clutter($url);
  285:         my %form = ('grade_target'      => 'analyze',
  286:                     'grade_domain'      => $udom,
  287:                     'grade_symb'        => $symb,
  288:                     'grade_courseid'    =>  $env{'request.course.id'},
  289:                     'grade_username'    => $uname,
  290:                     'grade_noincrement' => $no_increment);
  291:         if (ref($add_to_hash)) {
  292:             %form = (%form,%{$add_to_hash});
  293:         } 
  294: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  297:         if (ref($add_to_hash) eq 'HASH') {
  298:             $analyze_cache_formkeys{$key} = $add_to_hash;
  299:         } else {
  300:             $analyze_cache_formkeys{$key} = {};
  301:         }
  302: 	return $analyze_cache{$key} = \%analyze;
  303:     }
  304: 
  305:     sub get_order {
  306: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  307: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  308: 	return $analyze->{"$partid.$respid.shown"};
  309:     }
  310: 
  311:     sub get_radiobutton_correct_foil {
  312: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  313: 	my $analyze = &get_analyze($symb,$uname,$udom);
  314:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  315:         if (ref($foils) eq 'ARRAY') {
  316: 	    foreach my $foil (@{$foils}) {
  317: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  318: 		    return $foil;
  319: 	        }
  320: 	    }
  321: 	}
  322:     }
  323: 
  324:     sub scantron_partids_tograde {
  325:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
  326:         my (%analysis,@parts);
  327:         if (ref($resource)) {
  328:             my $symb = $resource->symb();
  329:             my $add_to_form;
  330:             if ($check_for_randomlist) {
  331:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
  332:             }
  333:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
  334:             if (ref($analyze) eq 'HASH') {
  335:                 %analysis = %{$analyze};
  336:             }
  337:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  338:                 foreach my $part (@{$analysis{'parts'}}) {
  339:                     my ($id,$respid) = split(/\./,$part);
  340:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  341:                         push(@parts,$part);
  342:                     }
  343:                 }
  344:             }
  345:         }
  346:         return (\%analysis,\@parts);
  347:     }
  348: 
  349: }
  350: 
  351: #--- Clean response type for display
  352: #--- Currently filters option/rank/radiobutton/match/essay/Task
  353: #        response types only.
  354: sub cleanRecord {
  355:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  356: 	$uname,$udom) = @_;
  357:     my $grayFont = '<span class="LC_internal_info">';
  358:     if ($response =~ /^(option|rank)$/) {
  359: 	my %answer=&Apache::lonnet::str2hash($answer);
  360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  361: 	my ($toprow,$bottomrow);
  362: 	foreach my $foil (@$order) {
  363: 	    if ($grading{$foil} == 1) {
  364: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  365: 	    } else {
  366: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  367: 	    }
  368: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  369: 	}
  370: 	return '<blockquote><table border="1">'.
  371: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  372: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  373: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  374:     } elsif ($response eq 'match') {
  375: 	my %answer=&Apache::lonnet::str2hash($answer);
  376: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  377: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  378: 	my ($toprow,$middlerow,$bottomrow);
  379: 	foreach my $foil (@$order) {
  380: 	    my $item=shift(@items);
  381: 	    if ($grading{$foil} == 1) {
  382: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  383: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  384: 	    } else {
  385: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  386: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  387: 	    }
  388: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  389: 	}
  390: 	return '<blockquote><table border="1">'.
  391: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  392: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  393: 	    $middlerow.'</tr>'.
  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  395: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  396:     } elsif ($response eq 'radiobutton') {
  397: 	my %answer=&Apache::lonnet::str2hash($answer);
  398: 	my ($toprow,$bottomrow);
  399: 	my $correct = 
  400: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  401: 	foreach my $foil (@$order) {
  402: 	    if (exists($answer{$foil})) {
  403: 		if ($foil eq $correct) {
  404: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  405: 		} else {
  406: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  407: 		}
  408: 	    } else {
  409: 		$toprow.='<td>'.&mt('false').'</td>';
  410: 	    }
  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  412: 	}
  413: 	return '<blockquote><table border="1">'.
  414: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  415: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  416: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  417:     } elsif ($response eq 'essay') {
  418: 	if (! exists ($env{'form.'.$symb})) {
  419: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  420: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  421: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  422: 
  423: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  424: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  425: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  426: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  427: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  428: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  429: 	}
  430: 	$answer =~ s-\n-<br />-g;
  431: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  432:     } elsif ( $response eq 'organic') {
  433: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  434: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  435: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  436: 	return $result;
  437:     } elsif ( $response eq 'Task') {
  438: 	if ( $answer eq 'SUBMITTED') {
  439: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  440: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  441: 	    return $result;
  442: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  443: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  444: 			       keys(%{$record}));
  445: 	    return join('<br />',($version,@matches));
  446: 			       
  447: 			       
  448: 	} else {
  449: 	    my $result =
  450: 		'<p>'
  451: 		.&mt('Overall result: [_1]',
  452: 		     $record->{$version."resource.$respid.$partid.status"})
  453: 		.'</p>';
  454: 	    
  455: 	    $result .= '<ul>';
  456: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  457: 			     keys(%{$record}));
  458: 	    foreach my $grade (sort(@grade)) {
  459: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  460: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  461: 				     $dim, $record->{$grade}).
  462: 			  '</li>';
  463: 	    }
  464: 	    $result.='</ul>';
  465: 	    return $result;
  466: 	}
  467:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  468: 	$answer = 
  469: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  470: 							      $answer);
  471:     }
  472:     return $answer;
  473: }
  474: 
  475: #-- A couple of common js functions
  476: sub commonJSfunctions {
  477:     my $request = shift;
  478:     $request->print(<<COMMONJSFUNCTIONS);
  479: <script type="text/javascript" language="javascript">
  480:     function radioSelection(radioButton) {
  481: 	var selection=null;
  482: 	if (radioButton.length > 1) {
  483: 	    for (var i=0; i<radioButton.length; i++) {
  484: 		if (radioButton[i].checked) {
  485: 		    return radioButton[i].value;
  486: 		}
  487: 	    }
  488: 	} else {
  489: 	    if (radioButton.checked) return radioButton.value;
  490: 	}
  491: 	return selection;
  492:     }
  493: 
  494:     function pullDownSelection(selectOne) {
  495: 	var selection="";
  496: 	if (selectOne.length > 1) {
  497: 	    for (var i=0; i<selectOne.length; i++) {
  498: 		if (selectOne[i].selected) {
  499: 		    return selectOne[i].value;
  500: 		}
  501: 	    }
  502: 	} else {
  503:             // only one value it must be the selected one
  504: 	    return selectOne.value;
  505: 	}
  506:     }
  507: </script>
  508: COMMONJSFUNCTIONS
  509: }
  510: 
  511: #--- Dumps the class list with usernames,list of sections,
  512: #--- section, ids and fullnames for each user.
  513: sub getclasslist {
  514:     my ($getsec,$filterlist,$getgroup) = @_;
  515:     my @getsec;
  516:     my @getgroup;
  517:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  518:     if (!ref($getsec)) {
  519: 	if ($getsec ne '' && $getsec ne 'all') {
  520: 	    @getsec=($getsec);
  521: 	}
  522:     } else {
  523: 	@getsec=@{$getsec};
  524:     }
  525:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  526:     if (!ref($getgroup)) {
  527: 	if ($getgroup ne '' && $getgroup ne 'all') {
  528: 	    @getgroup=($getgroup);
  529: 	}
  530:     } else {
  531: 	@getgroup=@{$getgroup};
  532:     }
  533:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  534: 
  535:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  536:     # Bail out if we were unable to get the classlist
  537:     return if (! defined($classlist));
  538:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  539:     #
  540:     my %sections;
  541:     my %fullnames;
  542:     foreach my $student (keys(%$classlist)) {
  543:         my $end      = 
  544:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  545:         my $start    = 
  546:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  547:         my $id       = 
  548:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  549:         my $section  = 
  550:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  551:         my $fullname = 
  552:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  553:         my $status   = 
  554:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  555:         my $group   = 
  556:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  557: 	# filter students according to status selected
  558: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  559: 	    if (!($stu_status =~ $status)) {
  560: 		delete($classlist->{$student});
  561: 		next;
  562: 	    }
  563: 	}
  564: 	# filter students according to groups selected
  565: 	my @stu_groups = split(/,/,$group);
  566: 	if (@getgroup) {
  567: 	    my $exclude = 1;
  568: 	    foreach my $grp (@getgroup) {
  569: 	        foreach my $stu_group (@stu_groups) {
  570: 	            if ($stu_group eq $grp) {
  571: 	                $exclude = 0;
  572:     	            } 
  573: 	        }
  574:     	        if (($grp eq 'none') && !$group) {
  575:         	        $exclude = 0;
  576:         	}
  577: 	    }
  578: 	    if ($exclude) {
  579: 	        delete($classlist->{$student});
  580: 	    }
  581: 	}
  582: 	$section = ($section ne '' ? $section : 'none');
  583: 	if (&canview($section)) {
  584: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  585: 		$sections{$section}++;
  586: 		if ($classlist->{$student}) {
  587: 		    $fullnames{$student}=$fullname;
  588: 		}
  589: 	    } else {
  590: 		delete($classlist->{$student});
  591: 	    }
  592: 	} else {
  593: 	    delete($classlist->{$student});
  594: 	}
  595:     }
  596:     my %seen = ();
  597:     my @sections = sort(keys(%sections));
  598:     return ($classlist,\@sections,\%fullnames);
  599: }
  600: 
  601: sub canmodify {
  602:     my ($sec)=@_;
  603:     if ($perm{'mgr'}) {
  604: 	if (!defined($perm{'mgr_section'})) {
  605: 	    # can modify whole class
  606: 	    return 1;
  607: 	} else {
  608: 	    if ($sec eq $perm{'mgr_section'}) {
  609: 		#can modify the requested section
  610: 		return 1;
  611: 	    } else {
  612: 		# can't modify the request section
  613: 		return 0;
  614: 	    }
  615: 	}
  616:     }
  617:     #can't modify
  618:     return 0;
  619: }
  620: 
  621: sub canview {
  622:     my ($sec)=@_;
  623:     if ($perm{'vgr'}) {
  624: 	if (!defined($perm{'vgr_section'})) {
  625: 	    # can modify whole class
  626: 	    return 1;
  627: 	} else {
  628: 	    if ($sec eq $perm{'vgr_section'}) {
  629: 		#can modify the requested section
  630: 		return 1;
  631: 	    } else {
  632: 		# can't modify the request section
  633: 		return 0;
  634: 	    }
  635: 	}
  636:     }
  637:     #can't modify
  638:     return 0;
  639: }
  640: 
  641: #--- Retrieve the grade status of a student for all the parts
  642: sub student_gradeStatus {
  643:     my ($symb,$udom,$uname,$partlist) = @_;
  644:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  645:     my %partstatus = ();
  646:     foreach (@$partlist) {
  647: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  648: 	$status              = 'nothing' if ($status eq '');
  649: 	$partstatus{$_}      = $status;
  650: 	my $subkey           = "resource.$_.submitted_by";
  651: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  652:     }
  653:     return %partstatus;
  654: }
  655: 
  656: # hidden form and javascript that calls the form
  657: # Use by verifyscript and viewgrades
  658: # Shows a student's view of problem and submission
  659: sub jscriptNform {
  660:     my ($symb) = @_;
  661:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  662:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  663: 	'    function viewOneStudent(user,domain) {'."\n".
  664: 	'	document.onestudent.student.value = user;'."\n".
  665: 	'	document.onestudent.userdom.value = domain;'."\n".
  666: 	'	document.onestudent.submit();'."\n".
  667: 	'    }'."\n".
  668: 	'</script>'."\n";
  669:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  670: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  671: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  672: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  673: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  674: 	'<input type="hidden" name="command" value="submission" />'."\n".
  675: 	'<input type="hidden" name="student" value="" />'."\n".
  676: 	'<input type="hidden" name="userdom" value="" />'."\n".
  677: 	'</form>'."\n";
  678:     return $jscript;
  679: }
  680: 
  681: 
  682: 
  683: # Given the score (as a number [0-1] and the weight) what is the final
  684: # point value? This function will round to the nearest tenth, third,
  685: # or quarter if one of those is within the tolerance of .00001.
  686: sub compute_points {
  687:     my ($score, $weight) = @_;
  688:     
  689:     my $tolerance = .00001;
  690:     my $points = $score * $weight;
  691: 
  692:     # Check for nearness to 1/x.
  693:     my $check_for_nearness = sub {
  694:         my ($factor) = @_;
  695:         my $num = ($points * $factor) + $tolerance;
  696:         my $floored_num = floor($num);
  697:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  698:             return $floored_num / $factor;
  699:         }
  700:         return $points;
  701:     };
  702: 
  703:     $points = $check_for_nearness->(10);
  704:     $points = $check_for_nearness->(3);
  705:     $points = $check_for_nearness->(4);
  706:     
  707:     return $points;
  708: }
  709: 
  710: #------------------ End of general use routines --------------------
  711: 
  712: #
  713: # Find most similar essay
  714: #
  715: 
  716: sub most_similar {
  717:     my ($uname,$udom,$uessay,$old_essays)=@_;
  718: 
  719: # ignore spaces and punctuation
  720: 
  721:     $uessay=~s/\W+/ /gs;
  722: 
  723: # ignore empty submissions (occuring when only files are sent)
  724: 
  725:     unless ($uessay=~/\w+/) { return ''; }
  726: 
  727: # these will be returned. Do not care if not at least 50 percent similar
  728:     my $limit=0.6;
  729:     my $sname='';
  730:     my $sdom='';
  731:     my $scrsid='';
  732:     my $sessay='';
  733: # go through all essays ...
  734:     foreach my $tkey (keys(%$old_essays)) {
  735: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  736: # ... except the same student
  737:         next if (($tname eq $uname) && ($tdom eq $udom));
  738: 	my $tessay=$old_essays->{$tkey};
  739: 	$tessay=~s/\W+/ /gs;
  740: # String similarity gives up if not even limit
  741: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  742: # Found one
  743: 	if ($tsimilar>$limit) {
  744: 	    $limit=$tsimilar;
  745: 	    $sname=$tname;
  746: 	    $sdom=$tdom;
  747: 	    $scrsid=$tcrsid;
  748: 	    $sessay=$old_essays->{$tkey};
  749: 	}
  750:     }
  751:     if ($limit>0.6) {
  752:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  753:     } else {
  754:        return ('','','','',0);
  755:     }
  756: }
  757: 
  758: #-------------------------------------------------------------------
  759: 
  760: #------------------------------------ Receipt Verification Routines
  761: #
  762: #--- Check whether a receipt number is valid.---
  763: sub verifyreceipt {
  764:     my $request  = shift;
  765: 
  766:     my $courseid = $env{'request.course.id'};
  767:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  768: 	$env{'form.receipt'};
  769:     $receipt     =~ s/[^\-\d]//g;
  770:     my ($symb)   = &get_symb($request);
  771: 
  772:     my $title.=
  773: 	'<h3><span class="LC_info">'.
  774: 	&mt('Verifying Receipt No. [_1]',$receipt).
  775: 	'</span></h3>'."\n".
  776: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  777: 	'</h4>'."\n";
  778: 
  779:     my ($string,$contents,$matches) = ('','',0);
  780:     my (undef,undef,$fullname) = &getclasslist('all','0');
  781:     
  782:     my $receiptparts=0;
  783:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  784: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  785:     my $parts=['0'];
  786:     if ($receiptparts) {
  787:         my $res_error; 
  788:         ($parts)=&response_type($symb,\$res_error);
  789:         if ($res_error) {
  790:             return &navmap_errormsg();
  791:         } 
  792:     }
  793:     
  794:     my $header = 
  795: 	&Apache::loncommon::start_data_table().
  796: 	&Apache::loncommon::start_data_table_header_row().
  797: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  798: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  799: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  800:     if ($receiptparts) {
  801: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  802:     }
  803:     $header.=
  804: 	&Apache::loncommon::end_data_table_header_row();
  805: 
  806:     foreach (sort 
  807: 	     {
  808: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  809: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  810: 		 }
  811: 		 return $a cmp $b;
  812: 	     } (keys(%$fullname))) {
  813: 	my ($uname,$udom)=split(/\:/);
  814: 	foreach my $part (@$parts) {
  815: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  816: 		$contents.=
  817: 		    &Apache::loncommon::start_data_table_row().
  818: 		    '<td>&nbsp;'."\n".
  819: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  820: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  821: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  822: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  823: 		if ($receiptparts) {
  824: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  825: 		}
  826: 		$contents.= 
  827: 		    &Apache::loncommon::end_data_table_row()."\n";
  828: 		
  829: 		$matches++;
  830: 	    }
  831: 	}
  832:     }
  833:     if ($matches == 0) {
  834: 	$string = $title.&mt('No match found for the above receipt number.');
  835:     } else {
  836: 	$string = &jscriptNform($symb).$title.
  837: 	    '<p>'.
  838: 	    &mt('The above receipt number matches the following [numerate,_1,student].',$matches).
  839: 	    '</p>'.
  840: 	    $header.
  841: 	    $contents.
  842: 	    &Apache::loncommon::end_data_table()."\n";
  843:     }
  844:     return $string.&show_grading_menu_form($symb);
  845: }
  846: 
  847: #--- This is called by a number of programs.
  848: #--- Called from the Grading Menu - View/Grade an individual student
  849: #--- Also called directly when one clicks on the subm button 
  850: #    on the problem page.
  851: sub listStudents {
  852:     my ($request) = shift;
  853: 
  854:     my ($symb) = &get_symb($request);
  855:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  856:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  857:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  858:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  859:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  860:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  861:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  862: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  863: 
  864:     my $result='<h3><span class="LC_info">&nbsp;'
  865: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  866: 	.'</span></h3>';
  867: 
  868:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  869: 
  870:     my %lt = &Apache::lonlocal::texthash (
  871: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  872: 		'single'   => 'Please select the student before clicking on the Next button.',
  873: 	     );
  874:     $request->print(<<LISTJAVASCRIPT);
  875: <script type="text/javascript" language="javascript">
  876:     function checkSelect(checkBox) {
  877: 	var ctr=0;
  878: 	var sense="";
  879: 	if (checkBox.length > 1) {
  880: 	    for (var i=0; i<checkBox.length; i++) {
  881: 		if (checkBox[i].checked) {
  882: 		    ctr++;
  883: 		}
  884: 	    }
  885: 	    sense = '$lt{'multiple'}';
  886: 	} else {
  887: 	    if (checkBox.checked) {
  888: 		ctr = 1;
  889: 	    }
  890: 	    sense = '$lt{'single'}';
  891: 	}
  892: 	if (ctr == 0) {
  893: 	    alert(sense);
  894: 	    return false;
  895: 	}
  896: 	document.gradesub.submit();
  897:     }
  898: 
  899:     function reLoadList(formname) {
  900: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  901: 	formname.command.value = 'submission';
  902: 	formname.submit();
  903:     }
  904: </script>
  905: LISTJAVASCRIPT
  906: 
  907:     &commonJSfunctions($request);
  908:     $request->print($result);
  909: 
  910:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  911:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  912:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  913: 	"\n".$table;
  914: 	
  915:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
  916:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
  917:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
  918:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
  919:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
  920:                   .&Apache::lonhtmlcommon::row_closure();
  921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
  922:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
  923:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
  924:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
  925:                   .&Apache::lonhtmlcommon::row_closure();
  926: 
  927:     my $submission_options;
  928:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  929: 	$submission_options.=
  930: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  931:     }
  932:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  933:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  934:     $env{'form.Status'} = $saveStatus;
  935:     $submission_options.=
  936: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  937: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  938: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  939: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  940:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
  941:                   .$submission_options
  942:                   .&Apache::lonhtmlcommon::row_closure();
  943: 
  944:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
  945:                   .'<select name="increment">'
  946:                   .'<option value="1">'.&mt('Whole Points').'</option>'
  947:                   .'<option value=".5">'.&mt('Half Points').'</option>'
  948:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
  949:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
  950:                   .'</select>'
  951:                   .&Apache::lonhtmlcommon::row_closure();
  952: 
  953:     $gradeTable .= 
  954:         &build_section_inputs().
  955: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  956: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  957: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  958: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  959: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  960: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  961: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  962: 
  963:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  964: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
  965:     } else {
  966:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
  967:                       .&Apache::lonhtmlcommon::StatusOptions(
  968:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
  969:                       .&Apache::lonhtmlcommon::row_closure();
  970:     }
  971: 
  972:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
  973:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
  974:                   .&Apache::lonhtmlcommon::row_closure(1)
  975:                   .&Apache::lonhtmlcommon::end_pick_box();
  976: 
  977:     $gradeTable .= '<p>'
  978:                   .&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"
  979:                   .'<input type="hidden" name="command" value="processGroup" />'
  980:                   .'</p>';
  981: 
  982: # checkall buttons
  983:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  984:     $gradeTable.='<input type="button" '."\n".
  985: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  986: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  987:     $gradeTable.=&check_buttons();
  988:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  989:     $gradeTable.= &Apache::loncommon::start_data_table().
  990: 	&Apache::loncommon::start_data_table_header_row();
  991:     my $loop = 0;
  992:     while ($loop < 2) {
  993: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  994: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  995: 	if ($env{'form.showgrading'} eq 'yes' 
  996: 	    && $submitonly ne 'queued'
  997: 	    && $submitonly ne 'all') {
  998: 	    foreach my $part (sort(@$partlist)) {
  999: 		my $display_part=
 1000: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1001: 		$gradeTable.=
 1002: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1003: 	    }
 1004: 	} elsif ($submitonly eq 'queued') {
 1005: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1006: 	}
 1007: 	$loop++;
 1008: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1009:     }
 1010:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1011: 
 1012:     my $ctr = 0;
 1013:     foreach my $student (sort 
 1014: 			 {
 1015: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1016: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1017: 			     }
 1018: 			     return $a cmp $b;
 1019: 			 }
 1020: 			 (keys(%$fullname))) {
 1021: 	my ($uname,$udom) = split(/:/,$student);
 1022: 
 1023: 	my %status = ();
 1024: 
 1025: 	if ($submitonly eq 'queued') {
 1026: 	    my %queue_status = 
 1027: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1028: 							$udom,$uname);
 1029: 	    next if (!defined($queue_status{'gradingqueue'}));
 1030: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1031: 	}
 1032: 
 1033: 	if ($env{'form.showgrading'} eq 'yes' 
 1034: 	    && $submitonly ne 'queued'
 1035: 	    && $submitonly ne 'all') {
 1036: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1037: 	    my $submitted = 0;
 1038: 	    my $graded = 0;
 1039: 	    my $incorrect = 0;
 1040: 	    foreach (keys(%status)) {
 1041: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1042: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1043: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1044: 		
 1045: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1046: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1047: 		    $submitted = 0;
 1048: 		    my ($part)=split(/\./,$partid);
 1049: 		    $gradeTable.='<input type="hidden" name="'.
 1050: 			$student.':'.$part.':submitted_by" value="'.
 1051: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1052: 		}
 1053: 	    }
 1054: 	    
 1055: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1056: 				     $submitonly eq 'incorrect' ||
 1057: 				     $submitonly eq 'graded'));
 1058: 	    next if (!$graded && ($submitonly eq 'graded'));
 1059: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1060: 	}
 1061: 
 1062: 	$ctr++;
 1063: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1064:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1065: 	if ( $perm{'vgr'} eq 'F' ) {
 1066: 	    if ($ctr%2 ==1) {
 1067: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1068: 	    }
 1069: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1070:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
 1071:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1072: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1073: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1074: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1075: 
 1076: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1077: 		foreach (sort(keys(%status))) {
 1078: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1079: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1080: 		}
 1081: 	    }
 1082: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1083: 	    if ($ctr%2 ==0) {
 1084: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1085: 	    }
 1086: 	}
 1087:     }
 1088:     if ($ctr%2 ==1) {
 1089: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1090: 	    if ($env{'form.showgrading'} eq 'yes' 
 1091: 		&& $submitonly ne 'queued'
 1092: 		&& $submitonly ne 'all') {
 1093: 		foreach (@$partlist) {
 1094: 		    $gradeTable.='<td>&nbsp;</td>';
 1095: 		}
 1096: 	    } elsif ($submitonly eq 'queued') {
 1097: 		$gradeTable.='<td>&nbsp;</td>';
 1098: 	    }
 1099: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1100:     }
 1101: 
 1102:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1103: 	'<input type="button" '.
 1104: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1105: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1106:     if ($ctr == 0) {
 1107: 	my $num_students=(scalar(keys(%$fullname)));
 1108: 	if ($num_students eq 0) {
 1109: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1110: 	} else {
 1111: 	    my $submissions='submissions';
 1112: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1113: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1114: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1115: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1116: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1117: 		    $num_students).
 1118: 		'</span><br />';
 1119: 	}
 1120:     } elsif ($ctr == 1) {
 1121: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1122:     }
 1123:     $gradeTable.=&show_grading_menu_form($symb);
 1124:     $request->print($gradeTable);
 1125:     return '';
 1126: }
 1127: 
 1128: #---- Called from the listStudents routine
 1129: 
 1130: sub check_script {
 1131:     my ($form, $type)=@_;
 1132:     my $chkallscript='<script type="text/javascript">
 1133:     function checkall() {
 1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1135:             ele = document.forms.'.$form.'.elements[i];
 1136:             if (ele.name == "'.$type.'") {
 1137:             document.forms.'.$form.'.elements[i].checked=true;
 1138:                                        }
 1139:         }
 1140:     }
 1141: 
 1142:     function checksec() {
 1143:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1144:             ele = document.forms.'.$form.'.elements[i];
 1145:            string = document.forms.'.$form.'.chksec.value;
 1146:            if
 1147:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1148:               document.forms.'.$form.'.elements[i].checked=true;
 1149:             }
 1150:         }
 1151:     }
 1152: 
 1153: 
 1154:     function uncheckall() {
 1155:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1156:             ele = document.forms.'.$form.'.elements[i];
 1157:             if (ele.name == "'.$type.'") {
 1158:             document.forms.'.$form.'.elements[i].checked=false;
 1159:                                        }
 1160:         }
 1161:     }
 1162: 
 1163: </script>'."\n";
 1164:     return $chkallscript;
 1165: }
 1166: 
 1167: sub check_buttons {
 1168:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1169:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1170:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1171:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1172:     return $buttons;
 1173: }
 1174: 
 1175: #     Displays the submissions for one student or a group of students
 1176: sub processGroup {
 1177:     my ($request)  = shift;
 1178:     my $ctr        = 0;
 1179:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1180:     my $total      = scalar(@stuchecked)-1;
 1181: 
 1182:     foreach my $student (@stuchecked) {
 1183: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1184: 	$env{'form.student'}        = $uname;
 1185: 	$env{'form.userdom'}        = $udom;
 1186: 	$env{'form.fullname'}       = $fullname;
 1187: 	&submission($request,$ctr,$total);
 1188: 	$ctr++;
 1189:     }
 1190:     return '';
 1191: }
 1192: 
 1193: #------------------------------------------------------------------------------------
 1194: #
 1195: #-------------------------- Next few routines handles grading by student, essentially
 1196: #                           handles essay response type problem/part
 1197: #
 1198: #--- Javascript to handle the submission page functionality ---
 1199: sub sub_page_js {
 1200:     my $request = shift;
 1201: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1202:     $request->print(<<SUBJAVASCRIPT);
 1203: <script type="text/javascript" language="javascript">
 1204:     function updateRadio(formname,id,weight) {
 1205: 	var gradeBox = formname["GD_BOX"+id];
 1206: 	var radioButton = formname["RADVAL"+id];
 1207: 	var oldpts = formname["oldpts"+id].value;
 1208: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1209: 	gradeBox.value = pts;
 1210: 	var resetbox = false;
 1211: 	if (isNaN(pts) || pts < 0) {
 1212: 	    alert("$alertmsg"+pts);
 1213: 	    for (var i=0; i<radioButton.length; i++) {
 1214: 		if (radioButton[i].checked) {
 1215: 		    gradeBox.value = i;
 1216: 		    resetbox = true;
 1217: 		}
 1218: 	    }
 1219: 	    if (!resetbox) {
 1220: 		formtextbox.value = "";
 1221: 	    }
 1222: 	    return;
 1223: 	}
 1224: 
 1225: 	if (pts > weight) {
 1226: 	    var resp = confirm("You entered a value ("+pts+
 1227: 			       ") greater than the weight for the part. Accept?");
 1228: 	    if (resp == false) {
 1229: 		gradeBox.value = oldpts;
 1230: 		return;
 1231: 	    }
 1232: 	}
 1233: 
 1234: 	for (var i=0; i<radioButton.length; i++) {
 1235: 	    radioButton[i].checked=false;
 1236: 	    if (pts == i && pts != "") {
 1237: 		radioButton[i].checked=true;
 1238: 	    }
 1239: 	}
 1240: 	updateSelect(formname,id);
 1241: 	formname["stores"+id].value = "0";
 1242:     }
 1243: 
 1244:     function writeBox(formname,id,pts) {
 1245: 	var gradeBox = formname["GD_BOX"+id];
 1246: 	if (checkSolved(formname,id) == 'update') {
 1247: 	    gradeBox.value = pts;
 1248: 	} else {
 1249: 	    var oldpts = formname["oldpts"+id].value;
 1250: 	    gradeBox.value = oldpts;
 1251: 	    var radioButton = formname["RADVAL"+id];
 1252: 	    for (var i=0; i<radioButton.length; i++) {
 1253: 		radioButton[i].checked=false;
 1254: 		if (i == oldpts) {
 1255: 		    radioButton[i].checked=true;
 1256: 		}
 1257: 	    }
 1258: 	}
 1259: 	formname["stores"+id].value = "0";
 1260: 	updateSelect(formname,id);
 1261: 	return;
 1262:     }
 1263: 
 1264:     function clearRadBox(formname,id) {
 1265: 	if (checkSolved(formname,id) == 'noupdate') {
 1266: 	    updateSelect(formname,id);
 1267: 	    return;
 1268: 	}
 1269: 	gradeSelect = formname["GD_SEL"+id];
 1270: 	for (var i=0; i<gradeSelect.length; i++) {
 1271: 	    if (gradeSelect[i].selected) {
 1272: 		var selectx=i;
 1273: 	    }
 1274: 	}
 1275: 	var stores = formname["stores"+id];
 1276: 	if (selectx == stores.value) { return };
 1277: 	var gradeBox = formname["GD_BOX"+id];
 1278: 	gradeBox.value = "";
 1279: 	var radioButton = formname["RADVAL"+id];
 1280: 	for (var i=0; i<radioButton.length; i++) {
 1281: 	    radioButton[i].checked=false;
 1282: 	}
 1283: 	stores.value = selectx;
 1284:     }
 1285: 
 1286:     function checkSolved(formname,id) {
 1287: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1288: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1289: 	    if (!reply) {return "noupdate";}
 1290: 	    formname.overRideScore.value = 'yes';
 1291: 	}
 1292: 	return "update";
 1293:     }
 1294: 
 1295:     function updateSelect(formname,id) {
 1296: 	formname["GD_SEL"+id][0].selected = true;
 1297: 	return;
 1298:     }
 1299: 
 1300: //=========== Check that a point is assigned for all the parts  ============
 1301:     function checksubmit(formname,val,total,parttot) {
 1302: 	formname.gradeOpt.value = val;
 1303: 	if (val == "Save & Next") {
 1304: 	    for (i=0;i<=total;i++) {
 1305: 		for (j=0;j<parttot;j++) {
 1306: 		    var partid = formname["partid"+i+"_"+j].value;
 1307: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1308: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1309: 			if (points == "") {
 1310: 			    var name = formname["name"+i].value;
 1311: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1312: 			    var resp = confirm("You did not assign a score for "+studentID+
 1313: 					       ", part "+partid+". Continue?");
 1314: 			    if (resp == false) {
 1315: 				formname["GD_BOX"+i+"_"+partid].focus();
 1316: 				return false;
 1317: 			    }
 1318: 			}
 1319: 		    }
 1320: 		    
 1321: 		}
 1322: 	    }
 1323: 	    
 1324: 	}
 1325: 	if (val == "Grade Student") {
 1326: 	    formname.showgrading.value = "yes";
 1327: 	    if (formname.Status.value == "") {
 1328: 		formname.Status.value = "Active";
 1329: 	    }
 1330: 	    formname.studentNo.value = total;
 1331: 	}
 1332: 	formname.submit();
 1333:     }
 1334: 
 1335: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1336:     function checkSubmitPage(formname,total) {
 1337: 	noscore = new Array(100);
 1338: 	var ptr = 0;
 1339: 	for (i=1;i<total;i++) {
 1340: 	    var partid = formname["q_"+i].value;
 1341: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1342: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1343: 		var status = formname["solved"+i+"_"+partid].value;
 1344: 		if (points == "" && status != "correct_by_student") {
 1345: 		    noscore[ptr] = i;
 1346: 		    ptr++;
 1347: 		}
 1348: 	    }
 1349: 	}
 1350: 	if (ptr != 0) {
 1351: 	    var sense = ptr == 1 ? ": " : "s: ";
 1352: 	    var prolist = "";
 1353: 	    if (ptr == 1) {
 1354: 		prolist = noscore[0];
 1355: 	    } else {
 1356: 		var i = 0;
 1357: 		while (i < ptr-1) {
 1358: 		    prolist += noscore[i]+", ";
 1359: 		    i++;
 1360: 		}
 1361: 		prolist += "and "+noscore[i];
 1362: 	    }
 1363: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1364: 	    if (resp == false) {
 1365: 		return false;
 1366: 	    }
 1367: 	}
 1368: 
 1369: 	formname.submit();
 1370:     }
 1371: </script>
 1372: SUBJAVASCRIPT
 1373: }
 1374: 
 1375: #--- javascript for essay type problem --
 1376: sub sub_page_kw_js {
 1377:     my $request = shift;
 1378:     my $iconpath = $request->dir_config('lonIconsURL');
 1379:     &commonJSfunctions($request);
 1380: 
 1381:     my $inner_js_msg_central=<<INNERJS;
 1382:     <script text="text/javascript">
 1383:     function checkInput() {
 1384:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1385:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1386:       var usrctr = document.msgcenter.usrctr.value;
 1387:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1388:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1389: 
 1390:       var msgchk = "";
 1391:       if (document.msgcenter.subchk.checked) {
 1392:          msgchk = "msgsub,";
 1393:       }
 1394:       var includemsg = 0;
 1395:       for (var i=1; i<=nmsg; i++) {
 1396:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1397:           var frmmsg = document.msgcenter["msg"+i];
 1398:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1399:           var showflg = opener.document.SCORE["shownOnce"+i];
 1400:           showflg.value = "1";
 1401:           var chkbox = document.msgcenter["msgn"+i];
 1402:           if (chkbox.checked) {
 1403:              msgchk += "savemsg"+i+",";
 1404:              includemsg = 1;
 1405:           }
 1406:       }
 1407:       if (document.msgcenter.newmsgchk.checked) {
 1408:          msgchk += "newmsg"+usrctr;
 1409:          includemsg = 1;
 1410:       }
 1411:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1412:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1413:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1414:       includemsg.value = msgchk;
 1415: 
 1416:       self.close()
 1417: 
 1418:     }
 1419:     </script>
 1420: INNERJS
 1421: 
 1422:     my $inner_js_highlight_central=<<INNERJS;
 1423:  <script type="text/javascript">
 1424:     function updateChoice(flag) {
 1425:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1426:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1427:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1428:       opener.document.SCORE.refresh.value = "on";
 1429:       if (opener.document.SCORE.keywords.value!=""){
 1430:          opener.document.SCORE.submit();
 1431:       }
 1432:       self.close()
 1433:     }
 1434: </script>
 1435: INNERJS
 1436: 
 1437:     my $start_page_msg_central = 
 1438:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1439: 				       {'js_ready'  => 1,
 1440: 					'only_body' => 1,
 1441: 					'bgcolor'   =>'#FFFFFF',});
 1442:     my $end_page_msg_central = 
 1443: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1444: 
 1445: 
 1446:     my $start_page_highlight_central = 
 1447:         &Apache::loncommon::start_page('Highlight Central',
 1448: 				       $inner_js_highlight_central,
 1449: 				       {'js_ready'  => 1,
 1450: 					'only_body' => 1,
 1451: 					'bgcolor'   =>'#FFFFFF',});
 1452:     my $end_page_highlight_central = 
 1453: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1454: 
 1455:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1456:     $docopen=~s/^document\.//;
 1457:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1458:     $request->print(<<SUBJAVASCRIPT);
 1459: <script type="text/javascript" language="javascript">
 1460: 
 1461: //===================== Show list of keywords ====================
 1462:   function keywords(formname) {
 1463:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1464:     if (nret==null) return;
 1465:     formname.keywords.value = nret;
 1466: 
 1467:     if (formname.keywords.value != "") {
 1468: 	formname.refresh.value = "on";
 1469: 	formname.submit();
 1470:     }
 1471:     return;
 1472:   }
 1473: 
 1474: //===================== Script to view submitted by ==================
 1475:   function viewSubmitter(submitter) {
 1476:     document.SCORE.refresh.value = "on";
 1477:     document.SCORE.NCT.value = "1";
 1478:     document.SCORE.unamedom0.value = submitter;
 1479:     document.SCORE.submit();
 1480:     return;
 1481:   }
 1482: 
 1483: //===================== Script to add keyword(s) ==================
 1484:   function getSel() {
 1485:     if (document.getSelection) txt = document.getSelection();
 1486:     else if (document.selection) txt = document.selection.createRange().text;
 1487:     else return;
 1488:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1489:     if (cleantxt=="") {
 1490: 	alert("$alertmsg");
 1491: 	return;
 1492:     }
 1493:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1494:     if (nret==null) return;
 1495:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1496:     if (document.SCORE.keywords.value != "") {
 1497: 	document.SCORE.refresh.value = "on";
 1498: 	document.SCORE.submit();
 1499:     }
 1500:     return;
 1501:   }
 1502: 
 1503: //====================== Script for composing message ==============
 1504:    // preload images
 1505:    img1 = new Image();
 1506:    img1.src = "$iconpath/mailbkgrd.gif";
 1507:    img2 = new Image();
 1508:    img2.src = "$iconpath/mailto.gif";
 1509: 
 1510:   function msgCenter(msgform,usrctr,fullname) {
 1511:     var Nmsg  = msgform.savemsgN.value;
 1512:     savedMsgHeader(Nmsg,usrctr,fullname);
 1513:     var subject = msgform.msgsub.value;
 1514:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1515:     re = /msgsub/;
 1516:     var shwsel = "";
 1517:     if (re.test(msgchk)) { shwsel = "checked" }
 1518:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1519:     displaySubject(checkEntities(subject),shwsel);
 1520:     for (var i=1; i<=Nmsg; i++) {
 1521: 	var testmsg = "savemsg"+i+",";
 1522: 	re = new RegExp(testmsg,"g");
 1523: 	shwsel = "";
 1524: 	if (re.test(msgchk)) { shwsel = "checked" }
 1525: 	var message = document.SCORE["savemsg"+i].value;
 1526: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1527: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1528: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1529:     }
 1530:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1531:     shwsel = "";
 1532:     re = /newmsg/;
 1533:     if (re.test(msgchk)) { shwsel = "checked" }
 1534:     newMsg(newmsg,shwsel);
 1535:     msgTail(); 
 1536:     return;
 1537:   }
 1538: 
 1539:   function checkEntities(strx) {
 1540:     if (strx.length == 0) return strx;
 1541:     var orgStr = ["&", "<", ">", '"']; 
 1542:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1543:     var counter = 0;
 1544:     while (counter < 4) {
 1545: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1546: 	counter++;
 1547:     }
 1548:     return strx;
 1549:   }
 1550: 
 1551:   function strReplace(strx, orgStr, newStr) {
 1552:     return strx.split(orgStr).join(newStr);
 1553:   }
 1554: 
 1555:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1556:     var height = 70*Nmsg+250;
 1557:     var scrollbar = "no";
 1558:     if (height > 600) {
 1559: 	height = 600;
 1560: 	scrollbar = "yes";
 1561:     }
 1562:     var xpos = (screen.width-600)/2;
 1563:     xpos = (xpos < 0) ? '0' : xpos;
 1564:     var ypos = (screen.height-height)/2-30;
 1565:     ypos = (ypos < 0) ? '0' : ypos;
 1566: 
 1567:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1568:     pWin.focus();
 1569:     pDoc = pWin.document;
 1570:     pDoc.$docopen;
 1571:     pDoc.write('$start_page_msg_central');
 1572: 
 1573:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1574:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1575:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1576: 
 1577:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1578:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1579:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1580: }
 1581:     function displaySubject(msg,shwsel) {
 1582:     pDoc = pWin.document;
 1583:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1584:     pDoc.write("<td>Subject<\\/td>");
 1585:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1586:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1587: }
 1588: 
 1589:   function displaySavedMsg(ctr,msg,shwsel) {
 1590:     pDoc = pWin.document;
 1591:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1592:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1593:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1594:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1595: }
 1596: 
 1597:   function newMsg(newmsg,shwsel) {
 1598:     pDoc = pWin.document;
 1599:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1600:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1601:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1602:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1603: }
 1604: 
 1605:   function msgTail() {
 1606:     pDoc = pWin.document;
 1607:     pDoc.write("<\\/table>");
 1608:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1609:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1610:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1611:     pDoc.write("<\\/form>");
 1612:     pDoc.write('$end_page_msg_central');
 1613:     pDoc.close();
 1614: }
 1615: 
 1616: //====================== Script for keyword highlight options ==============
 1617:   function kwhighlight() {
 1618:     var kwclr    = document.SCORE.kwclr.value;
 1619:     var kwsize   = document.SCORE.kwsize.value;
 1620:     var kwstyle  = document.SCORE.kwstyle.value;
 1621:     var redsel = "";
 1622:     var grnsel = "";
 1623:     var blusel = "";
 1624:     if (kwclr=="red")   {var redsel="checked"};
 1625:     if (kwclr=="green") {var grnsel="checked"};
 1626:     if (kwclr=="blue")  {var blusel="checked"};
 1627:     var sznsel = "";
 1628:     var sz1sel = "";
 1629:     var sz2sel = "";
 1630:     if (kwsize=="0")  {var sznsel="checked"};
 1631:     if (kwsize=="+1") {var sz1sel="checked"};
 1632:     if (kwsize=="+2") {var sz2sel="checked"};
 1633:     var synsel = "";
 1634:     var syisel = "";
 1635:     var sybsel = "";
 1636:     if (kwstyle=="")    {var synsel="checked"};
 1637:     if (kwstyle=="<i>") {var syisel="checked"};
 1638:     if (kwstyle=="<b>") {var sybsel="checked"};
 1639:     highlightCentral();
 1640:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1641:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1642:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1643:     highlightend();
 1644:     return;
 1645:   }
 1646: 
 1647:   function highlightCentral() {
 1648: //    if (window.hwdWin) window.hwdWin.close();
 1649:     var xpos = (screen.width-400)/2;
 1650:     xpos = (xpos < 0) ? '0' : xpos;
 1651:     var ypos = (screen.height-330)/2-30;
 1652:     ypos = (ypos < 0) ? '0' : ypos;
 1653: 
 1654:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1655:     hwdWin.focus();
 1656:     var hDoc = hwdWin.document;
 1657:     hDoc.$docopen;
 1658:     hDoc.write('$start_page_highlight_central');
 1659:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1660:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1661: 
 1662:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
 1663:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
 1664:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1665:   }
 1666: 
 1667:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1668:     var hDoc = hwdWin.document;
 1669:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1670:     hDoc.write("<td align=\\"left\\">");
 1671:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1672:     hDoc.write("<td align=\\"left\\">");
 1673:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1674:     hDoc.write("<td align=\\"left\\">");
 1675:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1676:     hDoc.write("<\\/tr>");
 1677:   }
 1678: 
 1679:   function highlightend() { 
 1680:     var hDoc = hwdWin.document;
 1681:     hDoc.write("<\\/table>");
 1682:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1683:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1684:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1685:     hDoc.write("<\\/form>");
 1686:     hDoc.write('$end_page_highlight_central');
 1687:     hDoc.close();
 1688:   }
 1689: 
 1690: </script>
 1691: SUBJAVASCRIPT
 1692: }
 1693: 
 1694: sub get_increment {
 1695:     my $increment = $env{'form.increment'};
 1696:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1697:         $increment != .1) {
 1698:         $increment = 1;
 1699:     }
 1700:     return $increment;
 1701: }
 1702: 
 1703: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1704: sub gradeBox {
 1705:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1706:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1707: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1708:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1709:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1710:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1711:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1712:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1713: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1714:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1715:     my $display_part= &get_display_part($partid,$symb);
 1716:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1717: 				       [$partid]);
 1718:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1719:     if ($last_resets{$partid}) {
 1720:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1721:     }
 1722:     $result.='<table border="0"><tr>';
 1723:     my $ctr = 0;
 1724:     my $thisweight = 0;
 1725:     my $increment = &get_increment();
 1726: 
 1727:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1728:     while ($thisweight<=$wgt) {
 1729: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1730: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1731: 	    $thisweight.')" value="'.$thisweight.'" '.
 1732: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1733: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1734:         $thisweight += $increment;
 1735: 	$ctr++;
 1736:     }
 1737:     $radio.='</tr></table>';
 1738: 
 1739:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1740: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1741: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1742: 	$wgt.')" /></td>'."\n";
 1743:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1744: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1745: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1746:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1747: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1748:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1749: 	$line.='<option></option>'.
 1750: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1751:     } else {
 1752: 	$line.='<option selected="selected"></option>'.
 1753: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1754:     }
 1755:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1756: 
 1757:     $result .= 
 1758: 	    '<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>';
 1759:     $result.='</tr></table>'."\n";
 1760:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1761: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1762: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1763: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1764:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1765:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1766:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1767:         $aggtries.'" />'."\n";
 1768:     my $res_error;
 1769:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1770:     if ($res_error) {
 1771:         return &navmap_errormsg();
 1772:     }
 1773:     return $result;
 1774: }
 1775: 
 1776: sub handback_box {
 1777:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1778:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1779:     my (@respids);
 1780:     my @part_response_id = &flatten_responseType($responseType);
 1781:     foreach my $part_response_id (@part_response_id) {
 1782:     	my ($part,$resp) = @{ $part_response_id };
 1783:         if ($part eq $partid) {
 1784:             push(@respids,$resp);
 1785:         }
 1786:     }
 1787:     my $result;
 1788:     foreach my $respid (@respids) {
 1789: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1790: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1791: 	next if (!@$files);
 1792: 	my $file_counter = 1;
 1793: 	foreach my $file (@$files) {
 1794: 	    if ($file =~ /\/portfolio\//) {
 1795:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1796:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1797:     	        $file_disp = "$name.$ext";
 1798:     	        $file = $file_path.$file_disp;
 1799:     	        $result.=&mt('Return commented version of [_1] to student.',
 1800:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1801:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1802:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1803:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1804:     	        $file_counter++;
 1805: 	    }
 1806: 	}
 1807:     }
 1808:     return $result;    
 1809: }
 1810: 
 1811: sub show_problem {
 1812:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1813:     my $rendered;
 1814:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1815:     &Apache::lonxml::remember_problem_counter();
 1816:     if ($mode eq 'both' or $mode eq 'text') {
 1817: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1818: 						       $env{'request.course.id'},
 1819: 						       undef,\%form);
 1820:     }
 1821:     if ($removeform) {
 1822: 	$rendered=~s|<form(.*?)>||g;
 1823: 	$rendered=~s|</form>||g;
 1824: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1825:     }
 1826:     my $companswer;
 1827:     if ($mode eq 'both' or $mode eq 'answer') {
 1828: 	&Apache::lonxml::restore_problem_counter();
 1829: 	$companswer=
 1830: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1831: 						    $env{'request.course.id'},
 1832: 						    %form);
 1833:     }
 1834:     if ($removeform) {
 1835: 	$companswer=~s|<form(.*?)>||g;
 1836: 	$companswer=~s|</form>||g;
 1837: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1838:     }
 1839:     $rendered=
 1840: 	'<div class="LC_grade_show_problem_header">'.
 1841: 	&mt('View of the problem').
 1842: 	'</div><div class="LC_grade_show_problem_problem">'.
 1843: 	$rendered.
 1844: 	'</div>';
 1845:     $companswer=
 1846: 	'<div class="LC_grade_show_problem_header">'.
 1847: 	&mt('Correct answer').
 1848: 	'</div><div class="LC_grade_show_problem_problem">'.
 1849: 	$companswer.
 1850: 	'</div>';
 1851:     my $result;
 1852:     if ($mode eq 'both') {
 1853: 	$result=$rendered.$companswer;
 1854:     } elsif ($mode eq 'text') {
 1855: 	$result=$rendered;
 1856:     } elsif ($mode eq 'answer') {
 1857: 	$result=$companswer;
 1858:     }
 1859:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1860:     return $result;
 1861: }
 1862: 
 1863: sub files_exist {
 1864:     my ($r, $symb) = @_;
 1865:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1866: 
 1867:     foreach my $student (@students) {
 1868:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1869:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1870: 					      $udom,$uname);
 1871:         my ($string,$timestamp)= &get_last_submission(\%record);
 1872:         foreach my $submission (@$string) {
 1873:             my ($partid,$respid) =
 1874: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1875:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1876: 					   \%record);
 1877:             return 1 if (@$files);
 1878:         }
 1879:     }
 1880:     return 0;
 1881: }
 1882: 
 1883: sub download_all_link {
 1884:     my ($r,$symb) = @_;
 1885:     my $all_students = 
 1886: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1887: 
 1888:     my $parts =
 1889: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1890: 
 1891:     my $identifier = &Apache::loncommon::get_cgi_id();
 1892:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1893:                              'cgi.'.$identifier.'.symb' => $symb,
 1894:                              'cgi.'.$identifier.'.parts' => $parts,});
 1895:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1896: 	      &mt('Download All Submitted Documents').'</a>');
 1897:     return
 1898: }
 1899: 
 1900: sub build_section_inputs {
 1901:     my $section_inputs;
 1902:     if ($env{'form.section'} eq '') {
 1903:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1904:     } else {
 1905:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1906:         foreach my $section (@sections) {
 1907:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1908:         }
 1909:     }
 1910:     return $section_inputs;
 1911: }
 1912: 
 1913: # --------------------------- show submissions of a student, option to grade 
 1914: sub submission {
 1915:     my ($request,$counter,$total) = @_;
 1916:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1917:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1918:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1919:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1920:     my $symb = &get_symb($request); 
 1921:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1922: 
 1923:     if (!&canview($usec)) {
 1924: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1925: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1926: 			$env{'request.course.id'}.')</span>');
 1927: 	$request->print(&show_grading_menu_form($symb));
 1928: 	return;
 1929:     }
 1930: 
 1931:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1932:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1933:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1934:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1935:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1936: 	'" src="'.$request->dir_config('lonIconsURL').
 1937: 	'/check.gif" height="16" border="0" />';
 1938: 
 1939:     my %old_essays;
 1940:     # header info
 1941:     if ($counter == 0) {
 1942: 	&sub_page_js($request);
 1943: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1944: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1945: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1946: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1947: 	    &download_all_link($request, $symb);
 1948: 	}
 1949: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1950: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1951: 
 1952: 	# option to display problem, only once else it cause problems 
 1953:         # with the form later since the problem has a form.
 1954: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1955: 	    my $mode;
 1956: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1957: 		$mode='both';
 1958: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1959: 		$mode='text';
 1960: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1961: 		$mode='answer';
 1962: 	    }
 1963: 	    &Apache::lonxml::clear_problem_counter();
 1964: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1965: 	}
 1966: 
 1967: 	# kwclr is the only variable that is guaranteed to be non blank 
 1968:         # if this subroutine has been called once.
 1969: 	my %keyhash = ();
 1970: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1971: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1972: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1973: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1974: 
 1975: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1976: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1977: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1978: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1979: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1980: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1981: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1982: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1983: 	}
 1984: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1985: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1986: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1987: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1988: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1989: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1990: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1991: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1992: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1993: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1994: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1995: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1996: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1997: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1998: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1999: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2000: 			&build_section_inputs().
 2001: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2002: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2003: 			'<input type="hidden" name="NCT"'.
 2004: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2005: 	if ($env{'form.handgrade'} eq 'yes') {
 2006: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2007: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2008: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2009: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2010: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2011: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2012: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2013: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2014: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2015: 	    }
 2016: 	}
 2017: 	
 2018: 	my ($cts,$prnmsg) = (1,'');
 2019: 	while ($cts <= $env{'form.savemsgN'}) {
 2020: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2021: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2022: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2023: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2024: 		'" />'."\n".
 2025: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2026: 	    $cts++;
 2027: 	}
 2028: 	$request->print($prnmsg);
 2029: 
 2030: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2031: #
 2032: # Print out the keyword options line
 2033: #
 2034: 	    $request->print(<<KEYWORDS);
 2035: &nbsp;<b>Keyword Options:</b>&nbsp;
 2036: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2037: <a href="#" onMouseDown="javascript:getSel(); return false"
 2038:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2039: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2040: KEYWORDS
 2041: #
 2042: # Load the other essays for similarity check
 2043: #
 2044:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2045: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2046: 	    $apath=&escape($apath);
 2047: 	    $apath=~s/\W/\_/gs;
 2048: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2049:         }
 2050:     }
 2051: 
 2052: # This is where output for one specific student would start
 2053:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2054:     $request->print("\n\n".
 2055:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2056: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2057: 		    '<div class="LC_grade_show_user_body">'."\n");
 2058: 
 2059:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2060: 	my $mode;
 2061: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2062: 	    $mode='both';
 2063: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2064: 	    $mode='text';
 2065: 	} elsif ($env{'form.vAns'} eq 'all') {
 2066: 	    $mode='answer';
 2067: 	}
 2068: 	&Apache::lonxml::clear_problem_counter();
 2069: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2070:     }
 2071: 
 2072:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2073:     my $res_error;
 2074:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2075:     if ($res_error) {
 2076:         $request->print(&navmap_errormsg());
 2077:         return;
 2078:     }
 2079: 
 2080:     # Display student info
 2081:     $request->print(($counter == 0 ? '' : '<br />'));
 2082:     my $result='<div class="LC_grade_submissions">';
 2083:     
 2084:     $result.='<div class="LC_grade_submissions_header">';
 2085:     $result.= &mt('Submissions');
 2086:     $result.='<input type="hidden" name="name'.$counter.
 2087: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2088:     if ($env{'form.handgrade'} eq 'no') {
 2089: 	$result.='<span class="LC_grade_check_note">'.
 2090: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2091: 
 2092:     }
 2093: 
 2094: 
 2095: 
 2096:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2097:     my $fullname;
 2098:     my $col_fullnames = [];
 2099:     if ($env{'form.handgrade'} eq 'yes') {
 2100: 	(my $sub_result,$fullname,$col_fullnames)=
 2101: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2102: 				 $counter);
 2103: 	$result.=$sub_result;
 2104:     }
 2105:     $request->print($result."\n");
 2106:     $request->print('</div>'."\n");
 2107:     # print student answer/submission
 2108:     # Options are (1) Handgaded submission only
 2109:     #             (2) Last submission, includes submission that is not handgraded 
 2110:     #                  (for multi-response type part)
 2111:     #             (3) Last submission plus the parts info
 2112:     #             (4) The whole record for this student
 2113:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2114: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2115: 	
 2116: 	my $lastsubonly;
 2117: 
 2118: 	if ($$timestamp eq '') {
 2119: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2120: 	} else {
 2121: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2122: 
 2123: 	    my %seenparts;
 2124: 	    my @part_response_id = &flatten_responseType($responseType);
 2125: 	    foreach my $part (@part_response_id) {
 2126: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2127: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2128: 
 2129: 		my ($partid,$respid) = @{ $part };
 2130: 		my $display_part=&get_display_part($partid,$symb);
 2131: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2132: 		    if (exists($seenparts{$partid})) { next; }
 2133: 		    $seenparts{$partid}=1;
 2134: 		    my $submitby='<b>Part:</b> '.$display_part.
 2135: 			' <b>Collaborative submission by:</b> '.
 2136: 			'<a href="javascript:viewSubmitter(\''.
 2137: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2138: 			'\');" target="_self">'.
 2139: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2140: 		    $request->print($submitby);
 2141: 		    next;
 2142: 		}
 2143: 		my $responsetype = $responseType->{$partid}->{$respid};
 2144: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2145: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2146: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2147: 			' )</span>&nbsp; &nbsp;'.
 2148: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2149: 		    next;
 2150: 		}
 2151: 		foreach my $submission (@$string) {
 2152: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2153: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2154: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2155: 		    # Similarity check
 2156: 		    my $similar='';
 2157: 		    if($env{'form.checkPlag'}){
 2158: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2159: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2160: 			if ($osim) {
 2161: 			    $osim=int($osim*100.0);
 2162: 			    my %old_course_desc = 
 2163: 				&Apache::lonnet::coursedescription($ocrsid,
 2164: 								   {'one_time' => 1});
 2165: 
 2166: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2167: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2168: 				    $osim,
 2169: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2170: 				    $old_course_desc{'description'},
 2171: 				    $old_course_desc{'num'},
 2172: 				    $old_course_desc{'domain'}).
 2173: 				'</span></h3><blockquote><i>'.
 2174: 				&keywords_highlight($oessay).
 2175: 				'</i></blockquote><hr />';
 2176: 			}
 2177: 		    }
 2178: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2179: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2180: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2181: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2182: 			my $display_part=&get_display_part($partid,$symb);
 2183: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2184: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2185: 			    ' )</span>&nbsp; &nbsp;';
 2186: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2187: 			if (@$files) {
 2188: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2189: 			    my $file_counter = 0;
 2190: 			    foreach my $file (@$files) {
 2191: 			        $file_counter++;
 2192: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2193: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2194: 			    }
 2195: 			    $lastsubonly.='<br />';
 2196: 			}
 2197: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2198: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2199: 					 $respid,\%record,$order,undef,$uname,$udom);
 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2201: 			$lastsubonly.='</div>';
 2202: 		    }
 2203: 		}
 2204: 	    }
 2205: 	    $lastsubonly.='</div>'."\n";
 2206: 	}
 2207: 	$request->print($lastsubonly);
 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2209: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2213: 								 $env{'request.course.id'},
 2214: 								 $last,'.submission',
 2215: 								 'Apache::grades::keywords_highlight'));
 2216:     }
 2217: 
 2218:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2219: 	.$udom.'" />'."\n");
 2220:     # return if view submission with no grading option
 2221:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2222: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2223: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2224: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2225: 	$toGrade.='</div>'."\n";
 2226: 	if (($env{'form.command'} eq 'submission') || 
 2227: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2228: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2229: 	}
 2230: 	$request->print($toGrade);
 2231: 	return;
 2232:     } else {
 2233: 	$request->print('</div>'."\n");
 2234:     }
 2235: 
 2236:     # essay grading message center
 2237:     if ($env{'form.handgrade'} eq 'yes') {
 2238: 	my $result='<div class="LC_grade_message_center">';
 2239:     
 2240: 	$result.='<div class="LC_grade_message_center_header">'.
 2241: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2242: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2243: 	my $msgfor = $givenn.' '.$lastname;
 2244: 	if (scalar(@$col_fullnames) > 0) {
 2245: 	    my $lastone = pop(@$col_fullnames);
 2246: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2247: 	}
 2248: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2249: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2250: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2251: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2252: 	    ',\''.$msgfor.'\');" target="_self">'.
 2253: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2254: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2255: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2256: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2257: 	    '<br />&nbsp;('.
 2258: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2259: 	$result.='</div></div>';
 2260: 	$request->print($result);
 2261:     }
 2262: 
 2263:     my %seen = ();
 2264:     my @partlist;
 2265:     my @gradePartRespid;
 2266:     my @part_response_id = &flatten_responseType($responseType);
 2267:     $request->print('<div class="LC_grade_assign">'.
 2268: 		    
 2269: 		    '<div class="LC_grade_assign_header">'.
 2270: 		    &mt('Assign Grades').'</div>'.
 2271: 		    '<div class="LC_grade_assign_body">');
 2272:     foreach my $part_response_id (@part_response_id) {
 2273:     	my ($partid,$respid) = @{ $part_response_id };
 2274: 	my $part_resp = join('_',@{ $part_response_id });
 2275: 	next if ($seen{$partid} > 0);
 2276: 	$seen{$partid}++;
 2277: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2278: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2279: 	push(@partlist,$partid);
 2280: 	push(@gradePartRespid,$partid.'.'.$respid);
 2281: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2282:     }
 2283:     $request->print('</div></div>');
 2284: 
 2285:     $request->print('<div class="LC_grade_info_links">');
 2286:     if ($perm{'vgr'}) {
 2287: 	$request->print(
 2288: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2289: 						   $uname,$udom,'check'));
 2290:     }
 2291:     if ($perm{'opa'}) {
 2292: 	$request->print(
 2293: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2294: 					 $uname,$udom,$symb,'check'));
 2295:     }
 2296:     $request->print('</div>');
 2297: 
 2298:     $result='<input type="hidden" name="partlist'.$counter.
 2299: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2300:     $result.='<input type="hidden" name="gradePartRespid'.
 2301: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2302:     my $ctr = 0;
 2303:     while ($ctr < scalar(@partlist)) {
 2304: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2305: 	    $partlist[$ctr].'" />'."\n";
 2306: 	$ctr++;
 2307:     }
 2308:     $request->print($result.''."\n");
 2309: 
 2310: # Done with printing info for one student
 2311: 
 2312:     $request->print('</div>');#LC_grade_show_user_body
 2313:     $request->print('</div>');#LC_grade_show_user
 2314: 
 2315: 
 2316:     # print end of form
 2317:     if ($counter == $total) {
 2318: 	my $endform='<table border="0"><tr><td>'."\n";
 2319: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2320: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2321: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2322: 	my $ntstu ='<select name="NTSTU">'.
 2323: 	    '<option>1</option><option>2</option>'.
 2324: 	    '<option>3</option><option>5</option>'.
 2325: 	    '<option>7</option><option>10</option></select>'."\n";
 2326: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2327: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2328:         $endform.=&mt('[_1]student(s)',$ntstu);
 2329: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2330: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2331: 	    '<input type="button" value="'.&mt('Next').'" '.
 2332: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2333: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2334:         $endform.="<input type='hidden' value='".&get_increment().
 2335:             "' name='increment' />";
 2336: 	$endform.='</td></tr></table></form>';
 2337: 	$endform.=&show_grading_menu_form($symb);
 2338: 	$request->print($endform);
 2339:     }
 2340:     return '';
 2341: }
 2342: 
 2343: sub check_collaborators {
 2344:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2345:     my ($result,@col_fullnames);
 2346:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2347:     foreach my $part (keys(%$handgrade)) {
 2348: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2349: 					'.maxcollaborators',
 2350: 					$symb,$udom,$uname);
 2351: 	next if ($ncol <= 0);
 2352: 	$part =~ s/\_/\./g;
 2353: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2354: 	my (@good_collaborators, @bad_collaborators);
 2355: 	foreach my $possible_collaborator
 2356: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2357: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2358: 	    next if ($possible_collaborator eq '');
 2359: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2360: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2361: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2362: 	    # Doing this grep allows 'fuzzy' specification
 2363: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2364: 			       keys(%$classlist));
 2365: 	    if (! scalar(@matches)) {
 2366: 		push(@bad_collaborators, $possible_collaborator);
 2367: 	    } else {
 2368: 		push(@good_collaborators, @matches);
 2369: 	    }
 2370: 	}
 2371: 	if (scalar(@good_collaborators) != 0) {
 2372: 	    $result.='<br />'.&mt('Collaborators: ');
 2373: 	    foreach my $name (@good_collaborators) {
 2374: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2375: 		push(@col_fullnames, $givenn.' '.$lastname);
 2376: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2377: 	    }
 2378: 	    $result.='<br />'."\n";
 2379: 	    my ($part)=split(/\./,$part);
 2380: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2381: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2382: 		"\n";
 2383: 	}
 2384: 	if (scalar(@bad_collaborators) > 0) {
 2385: 	    $result.='<div class="LC_warning">';
 2386: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2387: 	    $result .= '</div>';
 2388: 	}         
 2389: 	if (scalar(@bad_collaborators > $ncol)) {
 2390: 	    $result .= '<div class="LC_warning">';
 2391: 	    $result .= &mt('This student has submitted too many '.
 2392: 		'collaborators.  Maximum is [_1].',$ncol);
 2393: 	    $result .= '</div>';
 2394: 	}
 2395:     }
 2396:     return ($result,$fullname,\@col_fullnames);
 2397: }
 2398: 
 2399: #--- Retrieve the last submission for all the parts
 2400: sub get_last_submission {
 2401:     my ($returnhash)=@_;
 2402:     my (@string,$timestamp);
 2403:     if ($$returnhash{'version'}) {
 2404: 	my %lasthash=();
 2405: 	my ($version);
 2406: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2407: 	    foreach my $key (sort(split(/\:/,
 2408: 					$$returnhash{$version.':keys'}))) {
 2409: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2410: 		$timestamp = 
 2411: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2412: 	    }
 2413: 	}
 2414: 	foreach my $key (keys(%lasthash)) {
 2415: 	    next if ($key !~ /\.submission$/);
 2416: 
 2417: 	    my ($partid,$foo) = split(/submission$/,$key);
 2418: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2419: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2420: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2421: 	}
 2422:     }
 2423:     if (!@string) {
 2424: 	$string[0] =
 2425: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2426:     }
 2427:     return (\@string,\$timestamp);
 2428: }
 2429: 
 2430: #--- High light keywords, with style choosen by user.
 2431: sub keywords_highlight {
 2432:     my $string    = shift;
 2433:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2434:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2435:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2436:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2437:     foreach my $keyword (@keylist) {
 2438: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2439:     }
 2440:     return $string;
 2441: }
 2442: 
 2443: #--- Called from submission routine
 2444: sub processHandGrade {
 2445:     my ($request) = shift;
 2446:     my $symb   = &get_symb($request);
 2447:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2448:     my $button = $env{'form.gradeOpt'};
 2449:     my $ngrade = $env{'form.NCT'};
 2450:     my $ntstu  = $env{'form.NTSTU'};
 2451:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2452:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2453: 
 2454:     if ($button eq 'Save & Next') {
 2455: 	my $ctr = 0;
 2456: 	while ($ctr < $ngrade) {
 2457: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2458: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2459: 	    if ($errorflag eq 'no_score') {
 2460: 		$ctr++;
 2461: 		next;
 2462: 	    }
 2463: 	    if ($errorflag eq 'not_allowed') {
 2464: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2465: 		$ctr++;
 2466: 		next;
 2467: 	    }
 2468: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2469: 	    my ($subject,$message,$msgstatus) = ('','','');
 2470: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2471:             my ($feedurl,$showsymb) =
 2472: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2473: 	    my $messagetail;
 2474: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2475: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2476: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2477: 		$subject.=' ['.$restitle.']';
 2478: 		my (@msgnum) = split(/,/,$includemsg);
 2479: 		foreach (@msgnum) {
 2480: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2481: 		}
 2482: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2483: 		if ($env{'form.withgrades'.$ctr}) {
 2484: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2485: 		    $messagetail = " for <a href=\"".
 2486: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2487: 		}
 2488: 		$msgstatus = 
 2489:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2490: 						     $message.$messagetail,
 2491:                                                      undef,$feedurl,undef,
 2492:                                                      undef,undef,$showsymb,
 2493:                                                      $restitle);
 2494: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2495: 				$msgstatus);
 2496: 	    }
 2497: 	    if ($env{'form.collaborator'.$ctr}) {
 2498: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2499: 		foreach my $collabstr (@collabstrs) {
 2500: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2501: 		    foreach my $collaborator (@collaborators) {
 2502: 			my ($errorflag,$pts,$wgt) = 
 2503: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2504: 					   $env{'form.unamedom'.$ctr},$part);
 2505: 			if ($errorflag eq 'not_allowed') {
 2506: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2507: 			    next;
 2508: 			} elsif ($message ne '') {
 2509: 			    my ($baseurl,$showsymb) = 
 2510: 				&get_feedurl_and_symb($symb,$collaborator,
 2511: 						      $udom);
 2512: 			    if ($env{'form.withgrades'.$ctr}) {
 2513: 				$messagetail = " for <a href=\"".
 2514:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2515: 			    }
 2516: 			    $msgstatus = 
 2517: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2518: 			}
 2519: 		    }
 2520: 		}
 2521: 	    }
 2522: 	    $ctr++;
 2523: 	}
 2524:     }
 2525: 
 2526:     if ($env{'form.handgrade'} eq 'yes') {
 2527: 	# Keywords sorted in alphabatical order
 2528: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2529: 	my %keyhash = ();
 2530: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2531: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2532: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2533: 	$env{'form.keywords'} = join(' ',@keywords);
 2534: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2535: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2536: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2537: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2538: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2539: 
 2540: 	# message center - Order of message gets changed. Blank line is eliminated.
 2541: 	# New messages are saved in env for the next student.
 2542: 	# All messages are saved in nohist_handgrade.db
 2543: 	my ($ctr,$idx) = (1,1);
 2544: 	while ($ctr <= $env{'form.savemsgN'}) {
 2545: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2546: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2547: 		$idx++;
 2548: 	    }
 2549: 	    $ctr++;
 2550: 	}
 2551: 	$ctr = 0;
 2552: 	while ($ctr < $ngrade) {
 2553: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2554: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2555: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2556: 		$idx++;
 2557: 	    }
 2558: 	    $ctr++;
 2559: 	}
 2560: 	$env{'form.savemsgN'} = --$idx;
 2561: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2562: 	my $putresult = &Apache::lonnet::put
 2563: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2564:     }
 2565:     # Called by Save & Refresh from Highlight Attribute Window
 2566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2567:     if ($env{'form.refresh'} eq 'on') {
 2568: 	my ($ctr,$total) = (0,0);
 2569: 	while ($ctr < $ngrade) {
 2570: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2571: 	    $ctr++;
 2572: 	}
 2573: 	$env{'form.NTSTU'}=$ngrade;
 2574: 	$ctr = 0;
 2575: 	while ($ctr < $total) {
 2576: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2577: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2578: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2579: 	    &submission($request,$ctr,$total-1);
 2580: 	    $ctr++;
 2581: 	}
 2582: 	return '';
 2583:     }
 2584: 
 2585: # Go directly to grade student - from submission or link from chart page
 2586:     if ($button eq 'Grade Student') {
 2587: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2588: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2589: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2590: 	$env{'form.fullname'} = $$fullname{$processUser};
 2591: 	&submission($request,0,0);
 2592: 	return '';
 2593:     }
 2594: 
 2595:     # Get the next/previous one or group of students
 2596:     my $firststu = $env{'form.unamedom0'};
 2597:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2598:     my $ctr = 2;
 2599:     while ($laststu eq '') {
 2600: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2601: 	$ctr++;
 2602: 	$laststu = $firststu if ($ctr > $ngrade);
 2603:     }
 2604: 
 2605:     my (@parsedlist,@nextlist);
 2606:     my ($nextflg) = 0;
 2607:     foreach my $item (sort 
 2608: 	     {
 2609: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2610: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2611: 		 }
 2612: 		 return $a cmp $b;
 2613: 	     } (keys(%$fullname))) {
 2614: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2615: 	    push(@parsedlist,$item);
 2616: 	}
 2617: 	$nextflg = 1 if ($item eq $laststu);
 2618: 	if ($button eq 'Previous') {
 2619: 	    last if ($item eq $firststu);
 2620: 	    push(@parsedlist,$item);
 2621: 	}
 2622:     }
 2623:     $ctr = 0;
 2624:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2625:     my $res_error;
 2626:     my ($partlist) = &response_type($symb,\$res_error);
 2627:     if ($res_error) {
 2628:         $request->print(&navmap_errormsg());
 2629:         return;
 2630:     }
 2631:     foreach my $student (@parsedlist) {
 2632: 	my $submitonly=$env{'form.submitonly'};
 2633: 	my ($uname,$udom) = split(/:/,$student);
 2634: 	
 2635: 	if ($submitonly eq 'queued') {
 2636: 	    my %queue_status = 
 2637: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2638: 							$udom,$uname);
 2639: 	    next if (!defined($queue_status{'gradingqueue'}));
 2640: 	}
 2641: 
 2642: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2643: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2644: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2645: 	    my $submitted = 0;
 2646: 	    my $ungraded = 0;
 2647: 	    my $incorrect = 0;
 2648: 	    foreach my $item (keys(%status)) {
 2649: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2650: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2651: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2652: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2653: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2654: 		    $submitted = 0;
 2655: 		}
 2656: 	    }
 2657: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2658: 				     $submitonly eq 'incorrect' ||
 2659: 				     $submitonly eq 'graded'));
 2660: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2661: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2662: 	}
 2663: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2664: 	last if ($ctr == $ntstu);
 2665: 	$ctr++;
 2666:     }
 2667: 
 2668:     $ctr = 0;
 2669:     my $total = scalar(@nextlist)-1;
 2670: 
 2671:     foreach (sort(@nextlist)) {
 2672: 	my ($uname,$udom,$submitter) = split(/:/);
 2673: 	$env{'form.student'}  = $uname;
 2674: 	$env{'form.userdom'}  = $udom;
 2675: 	$env{'form.fullname'} = $$fullname{$_};
 2676: 	&submission($request,$ctr,$total);
 2677: 	$ctr++;
 2678:     }
 2679:     if ($total < 0) {
 2680: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2681: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2682: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2683: 	$the_end.=&show_grading_menu_form($symb);
 2684: 	$request->print($the_end);
 2685:     }
 2686:     return '';
 2687: }
 2688: 
 2689: #---- Save the score and award for each student, if changed
 2690: sub saveHandGrade {
 2691:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2692:     my @version_parts;
 2693:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2694: 					   $env{'request.course.id'});
 2695:     if (!&canmodify($usec)) { return('not_allowed'); }
 2696:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2697:     my @parts_graded;
 2698:     my %newrecord  = ();
 2699:     my ($pts,$wgt) = ('','');
 2700:     my %aggregate = ();
 2701:     my $aggregateflag = 0;
 2702:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2703:     foreach my $new_part (@parts) {
 2704: 	#collaborator ($submi may vary for different parts
 2705: 	if ($submitter && $new_part ne $part) { next; }
 2706: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2707: 	if ($dropMenu eq 'excused') {
 2708: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2709: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2710: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2711: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2712: 		}
 2713: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2714: 	    }
 2715: 	} elsif ($dropMenu eq 'reset status'
 2716: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2717: 	    foreach my $key (keys(%record)) {
 2718: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2719: 	    }
 2720: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2721: 		"$env{'user.name'}:$env{'user.domain'}";
 2722:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2723: 
 2724:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2725: 					       [$new_part]);
 2726:             my $aggtries =$totaltries;
 2727:             if ($last_resets{$new_part}) {
 2728:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2729: 					   $new_part);
 2730:             }
 2731: 
 2732:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2733:             if ($aggtries > 0) {
 2734:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2735:                 $aggregateflag = 1;
 2736:             }
 2737: 	} elsif ($dropMenu eq '') {
 2738: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2739: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2740: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2741: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2742: 		next;
 2743: 	    }
 2744: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2745: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2746: 	    my $partial= $pts/$wgt;
 2747: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2748: 		#do not update score for part if not changed.
 2749:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2750: 		next;
 2751: 	    } else {
 2752: 	        push(@parts_graded,$new_part);
 2753: 	    }
 2754: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2755: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2756: 	    }
 2757: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2758: 	    if ($partial == 0) {
 2759: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2760: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2761: 		}
 2762: 	    } else {
 2763: 		if ($record{$reckey} ne 'correct_by_override') {
 2764: 		    $newrecord{$reckey} = 'correct_by_override';
 2765: 		}
 2766: 	    }	    
 2767: 	    if ($submitter && 
 2768: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2769: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2770: 	    }
 2771: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2772: 		"$env{'user.name'}:$env{'user.domain'}";
 2773: 	}
 2774: 	# unless problem has been graded, set flag to version the submitted files
 2775: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2776: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2777: 	        $dropMenu eq 'reset status')
 2778: 	   {
 2779: 	    push(@version_parts,$new_part);
 2780: 	}
 2781:     }
 2782:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2783:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2784: 
 2785:     if (%newrecord) {
 2786:         if (@version_parts) {
 2787:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2788:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2789: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2790: 	    foreach my $new_part (@version_parts) {
 2791: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2792: 				$new_part,\%newrecord);
 2793: 	    }
 2794:         }
 2795: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2796: 				$env{'request.course.id'},$domain,$stuname);
 2797: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2798: 				     $cdom,$cnum,$domain,$stuname);
 2799:     }
 2800:     if ($aggregateflag) {
 2801:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2802: 			      $cdom,$cnum);
 2803:     }
 2804:     return ('',$pts,$wgt);
 2805: }
 2806: 
 2807: sub check_and_remove_from_queue {
 2808:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2809:     my @ungraded_parts;
 2810:     foreach my $part (@{$parts}) {
 2811: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2812: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2813: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2814: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2815: 		) {
 2816: 	    push(@ungraded_parts, $part);
 2817: 	}
 2818:     }
 2819:     if ( !@ungraded_parts ) {
 2820: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2821: 					       $cnum,$domain,$stuname);
 2822:     }
 2823: }
 2824: 
 2825: sub handback_files {
 2826:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2827:     my $portfolio_root = '/userfiles/portfolio';
 2828:     my $res_error;
 2829:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2830:     if ($res_error) {
 2831:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2832:         return;
 2833:     }
 2834:     my @part_response_id = &flatten_responseType($responseType);
 2835:     foreach my $part_response_id (@part_response_id) {
 2836:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2837: 	my $part_resp = join('_',@{ $part_response_id });
 2838:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2839:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2840:                 my $file_counter = 1;
 2841: 		my $file_msg;
 2842:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2843:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2844:                     my ($directory,$answer_file) = 
 2845:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2846:                     my ($answer_name,$answer_ver,$answer_ext) =
 2847: 		        &file_name_version_ext($answer_file);
 2848: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2849:                     my $getpropath = 1;
 2850: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2851: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2852:                     # fix file name
 2853:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2854:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2855:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2856:             	                                $save_file_name);
 2857:                     if ($result !~ m|^/uploaded/|) {
 2858:                         $request->print('<br /><span class="LC_error">'.
 2859:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2860:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2861:                                         '</span>');
 2862:                     } else {
 2863:                         # mark the file as read only
 2864:                         my @files = ($save_file_name);
 2865:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2866:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2867: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2868: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2869: 			}
 2870:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2871: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2872: 
 2873:                     }
 2874:                     $request->print("<br />".$fname." will be the uploaded file name");
 2875:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2876:                     $file_counter++;
 2877:                 }
 2878: 		my $subject = "File Handed Back by Instructor ";
 2879: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2880: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2881: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2882: 		$message .= " and can be found in your portfolio space.";
 2883: 		my ($feedurl,$showsymb) = 
 2884: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2885:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2886: 		my $msgstatus = 
 2887:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2888: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2889:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2890:             }
 2891:         }
 2892:     return;
 2893: }
 2894: 
 2895: sub get_feedurl_and_symb {
 2896:     my ($symb,$uname,$udom) = @_;
 2897:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2898:     $url = &Apache::lonnet::clutter($url);
 2899:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2900: 					$symb,$udom,$uname);
 2901:     if ($encrypturl =~ /^yes$/i) {
 2902: 	&Apache::lonenc::encrypted(\$url,1);
 2903: 	&Apache::lonenc::encrypted(\$symb,1);
 2904:     }
 2905:     return ($url,$symb);
 2906: }
 2907: 
 2908: sub get_submitted_files {
 2909:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2910:     my @files;
 2911:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2912:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2913:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2914:     	    push(@files,$file_url.$file);
 2915:         }
 2916:     }
 2917:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2918:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2919:     }
 2920:     return (\@files);
 2921: }
 2922: 
 2923: # ----------- Provides number of tries since last reset.
 2924: sub get_num_tries {
 2925:     my ($record,$last_reset,$part) = @_;
 2926:     my $timestamp = '';
 2927:     my $num_tries = 0;
 2928:     if ($$record{'version'}) {
 2929:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2930:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2931:                 $timestamp = $$record{$version.':timestamp'};
 2932:                 if ($timestamp > $last_reset) {
 2933:                     $num_tries ++;
 2934:                 } else {
 2935:                     last;
 2936:                 }
 2937:             }
 2938:         }
 2939:     }
 2940:     return $num_tries;
 2941: }
 2942: 
 2943: # ----------- Determine decrements required in aggregate totals 
 2944: sub decrement_aggs {
 2945:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2946:     my %decrement = (
 2947:                         attempts => 0,
 2948:                         users => 0,
 2949:                         correct => 0
 2950:                     );
 2951:     $decrement{'attempts'} = $aggtries;
 2952:     if ($solvedstatus =~ /^correct/) {
 2953:         $decrement{'correct'} = 1;
 2954:     }
 2955:     if ($aggtries == $totaltries) {
 2956:         $decrement{'users'} = 1;
 2957:     }
 2958:     foreach my $type (keys(%decrement)) {
 2959:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2960:     }
 2961:     return;
 2962: }
 2963: 
 2964: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2965: sub get_last_resets {
 2966:     my ($symb,$courseid,$partids) =@_;
 2967:     my %last_resets;
 2968:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2969:     my $cname = $env{'course.'.$courseid.'.num'};
 2970:     my @keys;
 2971:     foreach my $part (@{$partids}) {
 2972: 	push(@keys,"$symb\0$part\0resettime");
 2973:     }
 2974:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2975: 				     $cdom,$cname);
 2976:     foreach my $part (@{$partids}) {
 2977: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2978:     }
 2979:     return %last_resets;
 2980: }
 2981: 
 2982: # ----------- Handles creating versions for portfolio files as answers
 2983: sub version_portfiles {
 2984:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2985:     my $version_parts = join('|',@$v_flag);
 2986:     my @returned_keys;
 2987:     my $parts = join('|', @$parts_graded);
 2988:     my $portfolio_root = '/userfiles/portfolio';
 2989:     foreach my $key (keys(%$record)) {
 2990:         my $new_portfiles;
 2991:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2992:             my @versioned_portfiles;
 2993:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2994:             foreach my $file (@portfiles) {
 2995:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2996:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2997: 		my ($answer_name,$answer_ver,$answer_ext) =
 2998: 		    &file_name_version_ext($answer_file);
 2999:                 my $getpropath = 1;    
 3000:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3001:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3002:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3003:                 if ($new_answer ne 'problem getting file') {
 3004:                     push(@versioned_portfiles, $directory.$new_answer);
 3005:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3006:                         [$directory.$new_answer],
 3007:                         [$symb,$env{'request.course.id'},'graded']);
 3008:                 }
 3009:             }
 3010:             $$record{$key} = join(',',@versioned_portfiles);
 3011:             push(@returned_keys,$key);
 3012:         }
 3013:     } 
 3014:     return (@returned_keys);   
 3015: }
 3016: 
 3017: sub get_next_version {
 3018:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3019:     my $version;
 3020:     foreach my $row (@$dir_list) {
 3021:         my ($file) = split(/\&/,$row,2);
 3022:         my ($file_name,$file_version,$file_ext) =
 3023: 	    &file_name_version_ext($file);
 3024:         if (($file_name eq $answer_name) && 
 3025: 	    ($file_ext eq $answer_ext)) {
 3026:                 # gets here if filename and extension match, regardless of version
 3027:                 if ($file_version ne '') {
 3028:                 # a versioned file is found  so save it for later
 3029:                 if ($file_version > $version) {
 3030: 		    $version = $file_version;
 3031: 	        }
 3032:             }
 3033:         }
 3034:     } 
 3035:     $version ++;
 3036:     return($version);
 3037: }
 3038: 
 3039: sub version_selected_portfile {
 3040:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3041:     my ($answer_name,$answer_ver,$answer_ext) =
 3042:         &file_name_version_ext($file_name);
 3043:     my $new_answer;
 3044:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3045:     if($env{'form.copy'} eq '-1') {
 3046:         $new_answer = 'problem getting file';
 3047:     } else {
 3048:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3049:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3050:                             $stu_name,$domain,'copy',
 3051: 		        '/portfolio'.$directory.$new_answer);
 3052:     }    
 3053:     return ($new_answer);
 3054: }
 3055: 
 3056: sub file_name_version_ext {
 3057:     my ($file)=@_;
 3058:     my @file_parts = split(/\./, $file);
 3059:     my ($name,$version,$ext);
 3060:     if (@file_parts > 1) {
 3061: 	$ext=pop(@file_parts);
 3062: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3063: 	    $version=pop(@file_parts);
 3064: 	}
 3065: 	$name=join('.',@file_parts);
 3066:     } else {
 3067: 	$name=join('.',@file_parts);
 3068:     }
 3069:     return($name,$version,$ext);
 3070: }
 3071: 
 3072: #--------------------------------------------------------------------------------------
 3073: #
 3074: #-------------------------- Next few routines handles grading by section or whole class
 3075: #
 3076: #--- Javascript to handle grading by section or whole class
 3077: sub viewgrades_js {
 3078:     my ($request) = shift;
 3079: 
 3080:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3081:     $request->print(<<VIEWJAVASCRIPT);
 3082: <script type="text/javascript" language="javascript">
 3083:    function writePoint(partid,weight,point) {
 3084: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3085: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3086: 	if (point == "textval") {
 3087: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3088: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3089: 		alert("$alertmsg"+parseFloat(point));
 3090: 		var resetbox = false;
 3091: 		for (var i=0; i<radioButton.length; i++) {
 3092: 		    if (radioButton[i].checked) {
 3093: 			textbox.value = i;
 3094: 			resetbox = true;
 3095: 		    }
 3096: 		}
 3097: 		if (!resetbox) {
 3098: 		    textbox.value = "";
 3099: 		}
 3100: 		return;
 3101: 	    }
 3102: 	    if (parseFloat(point) > parseFloat(weight)) {
 3103: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3104: 				   ") greater than the weight for the part. Accept?");
 3105: 		if (resp == false) {
 3106: 		    textbox.value = "";
 3107: 		    return;
 3108: 		}
 3109: 	    }
 3110: 	    for (var i=0; i<radioButton.length; i++) {
 3111: 		radioButton[i].checked=false;
 3112: 		if (parseFloat(point) == i) {
 3113: 		    radioButton[i].checked=true;
 3114: 		}
 3115: 	    }
 3116: 
 3117: 	} else {
 3118: 	    textbox.value = parseFloat(point);
 3119: 	}
 3120: 	for (i=0;i<document.classgrade.total.value;i++) {
 3121: 	    var user = document.classgrade["ctr"+i].value;
 3122: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3123: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3124: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3125: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3126: 	    if (saveval != "correct") {
 3127: 		scorename.value = point;
 3128: 		if (selname[0].selected != true) {
 3129: 		    selname[0].selected = true;
 3130: 		}
 3131: 	    }
 3132: 	}
 3133: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3134:     }
 3135: 
 3136:     function writeRadText(partid,weight) {
 3137: 	var selval   = document.classgrade["SELVAL_"+partid];
 3138: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3139:         var override = document.classgrade["FORCE_"+partid].checked;
 3140: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3141: 	if (selval[1].selected || selval[2].selected) {
 3142: 	    for (var i=0; i<radioButton.length; i++) {
 3143: 		radioButton[i].checked=false;
 3144: 
 3145: 	    }
 3146: 	    textbox.value = "";
 3147: 
 3148: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3149: 		var user = document.classgrade["ctr"+i].value;
 3150: 		user = user.replace(new RegExp(':', 'g'),"_");
 3151: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3152: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3153: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3154: 		if ((saveval != "correct") || override) {
 3155: 		    scorename.value = "";
 3156: 		    if (selval[1].selected) {
 3157: 			selname[1].selected = true;
 3158: 		    } else {
 3159: 			selname[2].selected = true;
 3160: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3161: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3162: 		    }
 3163: 		}
 3164: 	    }
 3165: 	} else {
 3166: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3167: 		var user = document.classgrade["ctr"+i].value;
 3168: 		user = user.replace(new RegExp(':', 'g'),"_");
 3169: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3170: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3172: 		if ((saveval != "correct") || override) {
 3173: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3174: 		    selname[0].selected = true;
 3175: 		}
 3176: 	    }
 3177: 	}	    
 3178:     }
 3179: 
 3180:     function changeSelect(partid,user) {
 3181: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3182: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3183: 	var point  = textbox.value;
 3184: 	var weight = document.classgrade["weight_"+partid].value;
 3185: 
 3186: 	if (isNaN(point) || parseFloat(point) < 0) {
 3187: 	    alert("$alertmsg"+parseFloat(point));
 3188: 	    textbox.value = "";
 3189: 	    return;
 3190: 	}
 3191: 	if (parseFloat(point) > parseFloat(weight)) {
 3192: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3193: 			       ") greater than the weight of the part. Accept?");
 3194: 	    if (resp == false) {
 3195: 		textbox.value = "";
 3196: 		return;
 3197: 	    }
 3198: 	}
 3199: 	selval[0].selected = true;
 3200:     }
 3201: 
 3202:     function changeOneScore(partid,user) {
 3203: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3204: 	if (selval[1].selected || selval[2].selected) {
 3205: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3206: 	    if (selval[2].selected) {
 3207: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3208: 	    }
 3209:         }
 3210:     }
 3211: 
 3212:     function resetEntry(numpart) {
 3213: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3214: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3215: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3216: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3217: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3218: 	    for (var i=0; i<radioButton.length; i++) {
 3219: 		radioButton[i].checked=false;
 3220: 
 3221: 	    }
 3222: 	    textbox.value = "";
 3223: 	    selval[0].selected = true;
 3224: 
 3225: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3226: 		var user = document.classgrade["ctr"+i].value;
 3227: 		user = user.replace(new RegExp(':', 'g'),"_");
 3228: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3229: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3230: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3231: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3232: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3233: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3234: 		if (saveselval == "excused") {
 3235: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3236: 		} else {
 3237: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3238: 		}
 3239: 	    }
 3240: 	}
 3241:     }
 3242: 
 3243: </script>
 3244: VIEWJAVASCRIPT
 3245: }
 3246: 
 3247: #--- show scores for a section or whole class w/ option to change/update a score
 3248: sub viewgrades {
 3249:     my ($request) = shift;
 3250:     &viewgrades_js($request);
 3251: 
 3252:     my ($symb) = &get_symb($request);
 3253:     #need to make sure we have the correct data for later EXT calls, 
 3254:     #thus invalidate the cache
 3255:     &Apache::lonnet::devalidatecourseresdata(
 3256:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3257:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3258:     &Apache::lonnet::clear_EXT_cache_status();
 3259: 
 3260:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3261:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3262: 
 3263:     #view individual student submission form - called using Javascript viewOneStudent
 3264:     $result.=&jscriptNform($symb);
 3265: 
 3266:     #beginning of class grading form
 3267:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3268:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3269: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3270: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3271: 	&build_section_inputs().
 3272: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3273: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3274: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3275: 
 3276:     my ($common_header,$specific_header);
 3277:     if ($env{'form.section'} eq 'all') {
 3278: 	$common_header = &mt('Assign Common Grade to Class');
 3279:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3280:     } elsif ($env{'form.section'} eq 'none') {
 3281:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3282: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3283:     } else {
 3284:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3285:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3286: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3287:     }
 3288:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3289:     #radio buttons/text box for assigning points for a section or class.
 3290:     #handles different parts of a problem
 3291:     my $res_error;
 3292:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3293:     if ($res_error) {
 3294:         return &navmap_errormsg();
 3295:     }
 3296:     my %weight = ();
 3297:     my $ctsparts = 0;
 3298:     my %seen = ();
 3299:     my @part_response_id = &flatten_responseType($responseType);
 3300:     foreach my $part_response_id (@part_response_id) {
 3301:     	my ($partid,$respid) = @{ $part_response_id };
 3302: 	my $part_resp = join('_',@{ $part_response_id });
 3303: 	next if $seen{$partid};
 3304: 	$seen{$partid}++;
 3305: 	my $handgrade=$$handgrade{$part_resp};
 3306: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3307: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3308: 
 3309: 	my $display_part=&get_display_part($partid,$symb);
 3310: 	my $radio.='<table border="0"><tr>';  
 3311: 	my $ctr = 0;
 3312: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3313: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3314: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3315: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3316: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3317: 	    $ctr++;
 3318: 	}
 3319: 	$radio.='</tr></table>';
 3320: 	my $line = '<input type="text" name="TEXTVAL_'.
 3321: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3322: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3323: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3324: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3325: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3326: 		$weight{$partid}.')"> '.
 3327: 	    '<option selected="selected"> </option>'.
 3328: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3329: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3330: 	    '</select></td>'.
 3331:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3332: 	$line.='<input type="hidden" name="partid_'.
 3333: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3334: 	$line.='<input type="hidden" name="weight_'.
 3335: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3336: 
 3337: 	$result.=
 3338: 	    &Apache::loncommon::start_data_table_row()."\n".
 3339: 	    '<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>'.
 3340: 	    &Apache::loncommon::end_data_table_row()."\n";
 3341: 	$ctsparts++;
 3342:     }
 3343:     $result.=&Apache::loncommon::end_data_table()."\n".
 3344: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3345:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3346: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3347: 
 3348:     #table listing all the students in a section/class
 3349:     #header of table
 3350:     $result.= '<h3>'.$specific_header.'</h3>'.
 3351:               &Apache::loncommon::start_data_table().
 3352: 	      &Apache::loncommon::start_data_table_header_row().
 3353: 	      '<th>'.&mt('No.').'</th>'.
 3354: 	      '<th>'.&nameUserString('header')."</th>\n";
 3355:     my $partserror;
 3356:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3357:     if ($partserror) {
 3358:         return &navmap_errormsg();
 3359:     }
 3360:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3361:     my @partids = ();
 3362:     foreach my $part (@parts) {
 3363: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3364:         my $narrowtext = &mt('Tries');
 3365: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3366: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3367: 	my ($partid) = &split_part_type($part);
 3368:         push(@partids,$partid);
 3369: 	my $display_part=&get_display_part($partid,$symb);
 3370: 	if ($display =~ /^Partial Credit Factor/) {
 3371: 	    $result.='<th>'.
 3372: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3373: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3374: 	    next;
 3375: 	    
 3376: 	} else {
 3377: 	    if ($display =~ /Problem Status/) {
 3378: 		my $grade_status_mt = &mt('Grade Status');
 3379: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3380: 	    }
 3381: 	    my $part_mt = &mt('Part:');
 3382: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3383: 	}
 3384: 
 3385: 	$result.='<th>'.$display.'</th>'."\n";
 3386:     }
 3387:     $result.=&Apache::loncommon::end_data_table_header_row();
 3388: 
 3389:     my %last_resets = 
 3390: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3391: 
 3392:     #get info for each student
 3393:     #list all the students - with points and grade status
 3394:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3395:     my $ctr = 0;
 3396:     foreach (sort 
 3397: 	     {
 3398: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3399: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3400: 		 }
 3401: 		 return $a cmp $b;
 3402: 	     } (keys(%$fullname))) {
 3403: 	$ctr++;
 3404: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3405: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3406:     }
 3407:     $result.=&Apache::loncommon::end_data_table();
 3408:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3409:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3410: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3411:     if (scalar(%$fullname) eq 0) {
 3412: 	my $colspan=3+scalar(@parts);
 3413: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3414:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3415: 	$result='<span class="LC_warning">'.
 3416: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3417: 	        $section_display, $stu_status).
 3418: 	    '</span>';
 3419:     }
 3420:     $result.=&show_grading_menu_form($symb);
 3421:     return $result;
 3422: }
 3423: 
 3424: #--- call by previous routine to display each student
 3425: sub viewstudentgrade {
 3426:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3427:     my ($uname,$udom) = split(/:/,$student);
 3428:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3429:     my %aggregates = (); 
 3430:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3431: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3432: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3433: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3434: 	'\');" target="_self">'.$fullname.'</a> '.
 3435: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3436:     $student=~s/:/_/; # colon doen't work in javascript for names
 3437:     foreach my $apart (@$parts) {
 3438: 	my ($part,$type) = &split_part_type($apart);
 3439: 	my $score=$record{"resource.$part.$type"};
 3440:         $result.='<td align="center">';
 3441:         my ($aggtries,$totaltries);
 3442:         unless (exists($aggregates{$part})) {
 3443: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3444: 
 3445: 	    $aggtries = $totaltries;
 3446:             if ($$last_resets{$part}) {  
 3447:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3448: 					   $part);
 3449:             }
 3450:             $result.='<input type="hidden" name="'.
 3451:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3452:             $result.='<input type="hidden" name="'.
 3453:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3454:             $aggregates{$part} = 1;
 3455:         }
 3456: 	if ($type eq 'awarded') {
 3457: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3458: 	    $result.='<input type="hidden" name="'.
 3459: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3460: 	    $result.='<input type="text" name="'.
 3461: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3462: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3463: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3464: 	} elsif ($type eq 'solved') {
 3465: 	    my ($status,$foo)=split(/_/,$score,2);
 3466: 	    $status = 'nothing' if ($status eq '');
 3467: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3468: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3469: 	    $result.='&nbsp;<select name="'.
 3470: 		'GD_'.$student.'_'.$part.'_solved" '.
 3471: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3472: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3473: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3474: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3475: 	    $result.="</select>&nbsp;</td>\n";
 3476: 	} else {
 3477: 	    $result.='<input type="hidden" name="'.
 3478: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3479: 		    "\n";
 3480: 	    $result.='<input type="text" name="'.
 3481: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3482: 		'value="'.$score.'" size="4" /></td>'."\n";
 3483: 	}
 3484:     }
 3485:     $result.=&Apache::loncommon::end_data_table_row();
 3486:     return $result;
 3487: }
 3488: 
 3489: #--- change scores for all the students in a section/class
 3490: #    record does not get update if unchanged
 3491: sub editgrades {
 3492:     my ($request) = @_;
 3493: 
 3494:     my $symb=&get_symb($request);
 3495:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3496:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3497:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3498:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3499: 
 3500:     my $result= &Apache::loncommon::start_data_table().
 3501: 	&Apache::loncommon::start_data_table_header_row().
 3502: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3503: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3504:     my %scoreptr = (
 3505: 		    'correct'  =>'correct_by_override',
 3506: 		    'incorrect'=>'incorrect_by_override',
 3507: 		    'excused'  =>'excused',
 3508: 		    'ungraded' =>'ungraded_attempted',
 3509: 		    'nothing'  => '',
 3510: 		    );
 3511:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3512: 
 3513:     my (@partid);
 3514:     my %weight = ();
 3515:     my %columns = ();
 3516:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3517: 
 3518:     my $partserror;
 3519:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3520:     if ($partserror) {
 3521:         return &navmap_errormsg();
 3522:     }
 3523:     my $header;
 3524:     while ($ctr < $env{'form.totalparts'}) {
 3525: 	my $partid = $env{'form.partid_'.$ctr};
 3526: 	push(@partid,$partid);
 3527: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3528: 	$ctr++;
 3529:     }
 3530:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3531:     foreach my $partid (@partid) {
 3532: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3533: 	    '<th align="center">'.&mt('New Score').'</th>';
 3534: 	$columns{$partid}=2;
 3535: 	foreach my $stores (@parts) {
 3536: 	    my ($part,$type) = &split_part_type($stores);
 3537: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3538: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3539: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3540: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3541:             my $narrowtext = &mt('Tries');
 3542: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3543: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3544: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3545: 	    $columns{$partid}+=2;
 3546: 	}
 3547:     }
 3548:     foreach my $partid (@partid) {
 3549: 	my $display_part=&get_display_part($partid,$symb);
 3550: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3551: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3552: 	    '</th>';
 3553: 
 3554:     }
 3555:     $result .= &Apache::loncommon::end_data_table_header_row().
 3556: 	&Apache::loncommon::start_data_table_header_row().
 3557: 	$header.
 3558: 	&Apache::loncommon::end_data_table_header_row();
 3559:     my @noupdate;
 3560:     my ($updateCtr,$noupdateCtr) = (1,1);
 3561:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3562: 	my $line;
 3563: 	my $user = $env{'form.ctr'.$i};
 3564: 	my ($uname,$udom)=split(/:/,$user);
 3565: 	my %newrecord;
 3566: 	my $updateflag = 0;
 3567: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3568: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3569: 	if (!&canmodify($usec)) {
 3570: 	    my $numcols=scalar(@partid)*4+2;
 3571: 	    push(@noupdate,
 3572: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3573: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3574: 	    next;
 3575: 	}
 3576:         my %aggregate = ();
 3577:         my $aggregateflag = 0;
 3578: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3579: 	foreach (@partid) {
 3580: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3581: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3582: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3583: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3584: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3585: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3586: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3587: 	    my $score;
 3588: 	    if ($partial eq '') {
 3589: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3590: 	    } elsif ($partial > 0) {
 3591: 		$score = 'correct_by_override';
 3592: 	    } elsif ($partial == 0) {
 3593: 		$score = 'incorrect_by_override';
 3594: 	    }
 3595: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3596: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3597: 
 3598: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3599: 		"$env{'user.name'}:$env{'user.domain'}";
 3600: 	    if ($dropMenu eq 'reset status' &&
 3601: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3602: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3603: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3604: 		$newrecord{'resource.'.$_.'.award'} = '';
 3605: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3606: 		$updateflag = 1;
 3607:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3608:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3609:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3610:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3611:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3612:                     $aggregateflag = 1;
 3613:                 }
 3614: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3615: 		$updateflag = 1;
 3616: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3617: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3618: 		$rec_update++;
 3619: 	    }
 3620: 
 3621: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3622: 		'<td align="center">'.$awarded.
 3623: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3624: 
 3625: 
 3626: 	    my $partid=$_;
 3627: 	    foreach my $stores (@parts) {
 3628: 		my ($part,$type) = &split_part_type($stores);
 3629: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3630: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3631: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3632: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3633: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3634: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3635: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3636: 		    $updateflag=1;
 3637: 		}
 3638: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3639: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3640: 	    }
 3641: 	}
 3642: 	$line.="\n";
 3643: 
 3644: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3645: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3646: 
 3647: 	if ($updateflag) {
 3648: 	    $count++;
 3649: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3650: 				    $udom,$uname);
 3651: 
 3652: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3653: 					      $cnum,$udom,$uname)) {
 3654: 		# need to figure out if should be in queue.
 3655: 		my %record =  
 3656: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3657: 					     $udom,$uname);
 3658: 		my $all_graded = 1;
 3659: 		my $none_graded = 1;
 3660: 		foreach my $part (@parts) {
 3661: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3662: 			$all_graded = 0;
 3663: 		    } else {
 3664: 			$none_graded = 0;
 3665: 		    }
 3666: 		}
 3667: 
 3668: 		if ($all_graded || $none_graded) {
 3669: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3670: 							   $symb,$cdom,$cnum,
 3671: 							   $udom,$uname);
 3672: 		}
 3673: 	    }
 3674: 
 3675: 	    $result.=&Apache::loncommon::start_data_table_row().
 3676: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3677: 		&Apache::loncommon::end_data_table_row();
 3678: 	    $updateCtr++;
 3679: 	} else {
 3680: 	    push(@noupdate,
 3681: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3682: 	    $noupdateCtr++;
 3683: 	}
 3684:         if ($aggregateflag) {
 3685:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3686: 				  $cdom,$cnum);
 3687:         }
 3688:     }
 3689:     if (@noupdate) {
 3690: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3691: 	my $numcols=scalar(@partid)*4+2;
 3692: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3693: 	    '<td align="center" colspan="'.$numcols.'">'.
 3694: 	    &mt('No Changes Occurred For the Students Below').
 3695: 	    '</td>'.
 3696: 	    &Apache::loncommon::end_data_table_row();
 3697: 	foreach my $line (@noupdate) {
 3698: 	    $result.=
 3699: 		&Apache::loncommon::start_data_table_row().
 3700: 		$line.
 3701: 		&Apache::loncommon::end_data_table_row();
 3702: 	}
 3703:     }
 3704:     $result .= &Apache::loncommon::end_data_table().
 3705: 	&show_grading_menu_form($symb);
 3706:     my $msg = '<p><b>'.
 3707: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3708: 	    $rec_update,$count).'</b><br />'.
 3709: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3710: 	'</b></p>';
 3711:     return $title.$msg.$result;
 3712: }
 3713: 
 3714: sub split_part_type {
 3715:     my ($partstr) = @_;
 3716:     my ($temp,@allparts)=split(/_/,$partstr);
 3717:     my $type=pop(@allparts);
 3718:     my $part=join('_',@allparts);
 3719:     return ($part,$type);
 3720: }
 3721: 
 3722: #------------- end of section for handling grading by section/class ---------
 3723: #
 3724: #----------------------------------------------------------------------------
 3725: 
 3726: 
 3727: #----------------------------------------------------------------------------
 3728: #
 3729: #-------------------------- Next few routines handles grading by csv upload
 3730: #
 3731: #--- Javascript to handle csv upload
 3732: sub csvupload_javascript_reverse_associate {
 3733:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3734:     my $error2=&mt('You need to specify at least one grading field');
 3735:   return(<<ENDPICK);
 3736:   function verify(vf) {
 3737:     var foundsomething=0;
 3738:     var founduname=0;
 3739:     var foundID=0;
 3740:     for (i=0;i<=vf.nfields.value;i++) {
 3741:       tw=eval('vf.f'+i+'.selectedIndex');
 3742:       if (i==0 && tw!=0) { foundID=1; }
 3743:       if (i==1 && tw!=0) { founduname=1; }
 3744:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3745:     }
 3746:     if (founduname==0 && foundID==0) {
 3747: 	alert('$error1');
 3748: 	return;
 3749:     }
 3750:     if (foundsomething==0) {
 3751: 	alert('$error2');
 3752: 	return;
 3753:     }
 3754:     vf.submit();
 3755:   }
 3756:   function flip(vf,tf) {
 3757:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3758:     var i;
 3759:     for (i=0;i<=vf.nfields.value;i++) {
 3760:       //can not pick the same destination field for both name and domain
 3761:       if (((i ==0)||(i ==1)) && 
 3762:           ((tf==0)||(tf==1)) && 
 3763:           (i!=tf) &&
 3764:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3765:         eval('vf.f'+i+'.selectedIndex=0;')
 3766:       }
 3767:     }
 3768:   }
 3769: ENDPICK
 3770: }
 3771: 
 3772: sub csvupload_javascript_forward_associate {
 3773:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3774:     my $error2=&mt('You need to specify at least one grading field');
 3775:   return(<<ENDPICK);
 3776:   function verify(vf) {
 3777:     var foundsomething=0;
 3778:     var founduname=0;
 3779:     var foundID=0;
 3780:     for (i=0;i<=vf.nfields.value;i++) {
 3781:       tw=eval('vf.f'+i+'.selectedIndex');
 3782:       if (tw==1) { foundID=1; }
 3783:       if (tw==2) { founduname=1; }
 3784:       if (tw>3) { foundsomething=1; }
 3785:     }
 3786:     if (founduname==0 && foundID==0) {
 3787: 	alert('$error1');
 3788: 	return;
 3789:     }
 3790:     if (foundsomething==0) {
 3791: 	alert('$error2');
 3792: 	return;
 3793:     }
 3794:     vf.submit();
 3795:   }
 3796:   function flip(vf,tf) {
 3797:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3798:     var i;
 3799:     //can not pick the same destination field twice
 3800:     for (i=0;i<=vf.nfields.value;i++) {
 3801:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3802:         eval('vf.f'+i+'.selectedIndex=0;')
 3803:       }
 3804:     }
 3805:   }
 3806: ENDPICK
 3807: }
 3808: 
 3809: sub csvuploadmap_header {
 3810:     my ($request,$symb,$datatoken,$distotal)= @_;
 3811:     my $javascript;
 3812:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3813: 	$javascript=&csvupload_javascript_reverse_associate();
 3814:     } else {
 3815: 	$javascript=&csvupload_javascript_forward_associate();
 3816:     }
 3817: 
 3818:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3819:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3820:     my $ignore=&mt('Ignore First Line');
 3821:     $symb = &Apache::lonenc::check_encrypt($symb);
 3822:     $request->print(<<ENDPICK);
 3823: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3824: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3825: $result
 3826: <hr />
 3827: <h3>Identify fields</h3>
 3828: Total number of records found in file: $distotal <hr />
 3829: Enter as many fields as you can. The system will inform you and bring you back
 3830: to this page if the data selected is insufficient to run your class.<hr />
 3831: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3832: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3833: <input type="hidden" name="associate"  value="" />
 3834: <input type="hidden" name="phase"      value="three" />
 3835: <input type="hidden" name="datatoken"  value="$datatoken" />
 3836: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3837: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3838: <input type="hidden" name="upfile_associate" 
 3839:                                        value="$env{'form.upfile_associate'}" />
 3840: <input type="hidden" name="symb"       value="$symb" />
 3841: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3842: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3843: <input type="hidden" name="command"    value="csvuploadoptions" />
 3844: <hr />
 3845: <script type="text/javascript" language="Javascript">
 3846: $javascript
 3847: </script>
 3848: ENDPICK
 3849:     return '';
 3850: 
 3851: }
 3852: 
 3853: sub csvupload_fields {
 3854:     my ($symb) = @_;
 3855:     my ($symb,$errorref) = @_;
 3856:     my (@parts) = &getpartlist($symb,$errorref);
 3857:     if (ref($errorref)) {
 3858:         if ($$errorref) {
 3859:             return;
 3860:         }
 3861:     }
 3862: 
 3863:     my @fields=(['ID','Student/Employee ID'],
 3864: 		['username','Student Username'],
 3865: 		['domain','Student Domain']);
 3866:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3867:     foreach my $part (sort(@parts)) {
 3868: 	my @datum;
 3869: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3870: 	my $name=$part;
 3871: 	if  (!$display) { $display = $name; }
 3872: 	@datum=($name,$display);
 3873: 	if ($name=~/^stores_(.*)_awarded/) {
 3874: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3875: 	}
 3876: 	push(@fields,\@datum);
 3877:     }
 3878:     return (@fields);
 3879: }
 3880: 
 3881: sub csvuploadmap_footer {
 3882:     my ($request,$i,$keyfields) =@_;
 3883:     $request->print(<<ENDPICK);
 3884: </table>
 3885: <input type="hidden" name="nfields" value="$i" />
 3886: <input type="hidden" name="keyfields" value="$keyfields" />
 3887: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3888: </form>
 3889: ENDPICK
 3890: }
 3891: 
 3892: sub checkforfile_js {
 3893:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3894:     my $result =<<CSVFORMJS;
 3895: <script type="text/javascript" language="javascript">
 3896:     function checkUpload(formname) {
 3897: 	if (formname.upfile.value == "") {
 3898: 	    alert("$alertmsg");
 3899: 	    return false;
 3900: 	}
 3901: 	formname.submit();
 3902:     }
 3903:     </script>
 3904: CSVFORMJS
 3905:     return $result;
 3906: }
 3907: 
 3908: sub upcsvScores_form {
 3909:     my ($request) = shift;
 3910:     my ($symb)=&get_symb($request);
 3911:     if (!$symb) {return '';}
 3912:     my $result=&checkforfile_js();
 3913:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3914:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3915:     $result.=$table;
 3916:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3917:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3918:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3919: 	'</b></td></tr>'."\n";
 3920:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3921:     my $upload=&mt("Upload Scores");
 3922:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3923:     my $ignore=&mt('Ignore First Line');
 3924:     $symb = &Apache::lonenc::check_encrypt($symb);
 3925:     $result.=<<ENDUPFORM;
 3926: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3927: <input type="hidden" name="symb" value="$symb" />
 3928: <input type="hidden" name="command" value="csvuploadmap" />
 3929: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3930: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3931: $upfile_select
 3932: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3933: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3934: </form>
 3935: ENDUPFORM
 3936:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3937:                            &mt("How do I create a CSV file from a spreadsheet"))
 3938:     .'</td></tr></table>'."\n";
 3939:     $result.='</td></tr></table><br /><br />'."\n";
 3940:     $result.=&show_grading_menu_form($symb);
 3941:     return $result;
 3942: }
 3943: 
 3944: 
 3945: sub csvuploadmap {
 3946:     my ($request)= @_;
 3947:     my ($symb)=&get_symb($request);
 3948:     if (!$symb) {return '';}
 3949: 
 3950:     my $datatoken;
 3951:     if (!$env{'form.datatoken'}) {
 3952: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3953:     } else {
 3954: 	$datatoken=$env{'form.datatoken'};
 3955: 	&Apache::loncommon::load_tmp_file($request);
 3956:     }
 3957:     my @records=&Apache::loncommon::upfile_record_sep();
 3958:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3959:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3960:     my ($i,$keyfields);
 3961:     if (@records) {
 3962:         my $fieldserror;
 3963:         my @fields=&csvupload_fields($symb,\$fieldserror);
 3964:         if ($fieldserror) {
 3965:             $request->print(&navmap_errormsg());
 3966:             return;
 3967:         }
 3968: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3969: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3970: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3971: 							  \@fields);
 3972: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3973: 	    chop($keyfields);
 3974: 	} else {
 3975: 	    unshift(@fields,['none','']);
 3976: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3977: 							    \@fields);
 3978:             foreach my $rec (@records) {
 3979:                 my %temp = &Apache::loncommon::record_sep($rec);
 3980:                 if (%temp) {
 3981:                     $keyfields=join(',',sort(keys(%temp)));
 3982:                     last;
 3983:                 }
 3984:             }
 3985: 	}
 3986:     }
 3987:     &csvuploadmap_footer($request,$i,$keyfields);
 3988:     $request->print(&show_grading_menu_form($symb));
 3989: 
 3990:     return '';
 3991: }
 3992: 
 3993: sub csvuploadoptions {
 3994:     my ($request)= @_;
 3995:     my ($symb)=&get_symb($request);
 3996:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3997:     my $ignore=&mt('Ignore First Line');
 3998:     $request->print(<<ENDPICK);
 3999: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4000: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4001: <input type="hidden" name="command"    value="csvuploadassign" />
 4002: <!--
 4003: <p>
 4004: <label>
 4005:    <input type="checkbox" name="show_full_results" />
 4006:    Show a table of all changes
 4007: </label>
 4008: </p>
 4009: -->
 4010: <p>
 4011: <label>
 4012:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4013:    Overwrite any existing score
 4014: </label>
 4015: </p>
 4016: ENDPICK
 4017:     my %fields=&get_fields();
 4018:     if (!defined($fields{'domain'})) {
 4019: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4020: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4021:     }
 4022:     foreach my $key (sort(keys(%env))) {
 4023: 	if ($key !~ /^form\.(.*)$/) { next; }
 4024: 	my $cleankey=$1;
 4025: 	if ($cleankey eq 'command') { next; }
 4026: 	$request->print('<input type="hidden" name="'.$cleankey.
 4027: 			'"  value="'.$env{$key}.'" />'."\n");
 4028:     }
 4029:     # FIXME do a check for any duplicated user ids...
 4030:     # FIXME do a check for any invalid user ids?...
 4031:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4032: <hr /></form>'."\n");
 4033:     $request->print(&show_grading_menu_form($symb));
 4034:     return '';
 4035: }
 4036: 
 4037: sub get_fields {
 4038:     my %fields;
 4039:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4040:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4041: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4042: 	    if ($env{'form.f'.$i} ne 'none') {
 4043: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4044: 	    }
 4045: 	} else {
 4046: 	    if ($env{'form.f'.$i} ne 'none') {
 4047: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4048: 	    }
 4049: 	}
 4050:     }
 4051:     return %fields;
 4052: }
 4053: 
 4054: sub csvuploadassign {
 4055:     my ($request)= @_;
 4056:     my ($symb)=&get_symb($request);
 4057:     if (!$symb) {return '';}
 4058:     my $error_msg = '';
 4059:     &Apache::loncommon::load_tmp_file($request);
 4060:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4061:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4062:     my %fields=&get_fields();
 4063:     $request->print('<h3>Assigning Grades</h3>');
 4064:     my $courseid=$env{'request.course.id'};
 4065:     my ($classlist) = &getclasslist('all',0);
 4066:     my @notallowed;
 4067:     my @skipped;
 4068:     my $countdone=0;
 4069:     foreach my $grade (@gradedata) {
 4070: 	my %entries=&Apache::loncommon::record_sep($grade);
 4071: 	my $domain;
 4072: 	if ($entries{$fields{'domain'}}) {
 4073: 	    $domain=$entries{$fields{'domain'}};
 4074: 	} else {
 4075: 	    $domain=$env{'form.default_domain'};
 4076: 	}
 4077: 	$domain=~s/\s//g;
 4078: 	my $username=$entries{$fields{'username'}};
 4079: 	$username=~s/\s//g;
 4080: 	if (!$username) {
 4081: 	    my $id=$entries{$fields{'ID'}};
 4082: 	    $id=~s/\s//g;
 4083: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4084: 	    $username=$ids{$id};
 4085: 	}
 4086: 	if (!exists($$classlist{"$username:$domain"})) {
 4087: 	    my $id=$entries{$fields{'ID'}};
 4088: 	    $id=~s/\s//g;
 4089: 	    if ($id) {
 4090: 		push(@skipped,"$id:$domain");
 4091: 	    } else {
 4092: 		push(@skipped,"$username:$domain");
 4093: 	    }
 4094: 	    next;
 4095: 	}
 4096: 	my $usec=$classlist->{"$username:$domain"}[5];
 4097: 	if (!&canmodify($usec)) {
 4098: 	    push(@notallowed,"$username:$domain");
 4099: 	    next;
 4100: 	}
 4101: 	my %points;
 4102: 	my %grades;
 4103: 	foreach my $dest (keys(%fields)) {
 4104: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4105: 		$dest eq 'domain') { next; }
 4106: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4107: 	    if ($dest=~/stores_(.*)_points/) {
 4108: 		my $part=$1;
 4109: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4110: 					      $symb,$domain,$username);
 4111:                 if ($wgt) {
 4112:                     $entries{$fields{$dest}}=~s/\s//g;
 4113:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4114:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4115:                                           : 'correct_by_override';
 4116:                     $grades{"resource.$part.awarded"}=$pcr;
 4117:                     $grades{"resource.$part.solved"}=$award;
 4118:                     $points{$part}=1;
 4119:                 } else {
 4120:                     $error_msg = "<br />" .
 4121:                         &mt("Some point values were assigned"
 4122:                             ." for problems with a weight "
 4123:                             ."of zero. These values were "
 4124:                             ."ignored.");
 4125:                 }
 4126: 	    } else {
 4127: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4128: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4129: 		my $store_key=$dest;
 4130: 		$store_key=~s/^stores/resource/;
 4131: 		$store_key=~s/_/\./g;
 4132: 		$grades{$store_key}=$entries{$fields{$dest}};
 4133: 	    }
 4134: 	}
 4135: 	if (! %grades) { 
 4136:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4137:         } else {
 4138: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4139: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4140: 					   $env{'request.course.id'},
 4141: 					   $domain,$username);
 4142: 	   if ($result eq 'ok') {
 4143: 	      $request->print('.');
 4144: 	   } else {
 4145: 	      $request->print("<p><span class=\"LC_error\">".
 4146:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4147:                                   "$username:$domain",$result)."</span></p>");
 4148: 	   }
 4149: 	   $request->rflush();
 4150: 	   $countdone++;
 4151:         }
 4152:     }
 4153:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4154:     if (@skipped) {
 4155: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4156:         $request->print(join(', ',@skipped));
 4157:     }
 4158:     if (@notallowed) {
 4159: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4160: 	$request->print(join(', ',@notallowed));
 4161:     }
 4162:     $request->print("<br />\n");
 4163:     $request->print(&show_grading_menu_form($symb));
 4164:     return $error_msg;
 4165: }
 4166: #------------- end of section for handling csv file upload ---------
 4167: #
 4168: #-------------------------------------------------------------------
 4169: #
 4170: #-------------- Next few routines handle grading by page/sequence
 4171: #
 4172: #--- Select a page/sequence and a student to grade
 4173: sub pickStudentPage {
 4174:     my ($request) = shift;
 4175: 
 4176:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4177:     $request->print(<<LISTJAVASCRIPT);
 4178: <script type="text/javascript" language="javascript">
 4179: 
 4180: function checkPickOne(formname) {
 4181:     if (radioSelection(formname.student) == null) {
 4182: 	alert("$alertmsg");
 4183: 	return;
 4184:     }
 4185:     ptr = pullDownSelection(formname.selectpage);
 4186:     formname.page.value = formname["page"+ptr].value;
 4187:     formname.title.value = formname["title"+ptr].value;
 4188:     formname.submit();
 4189: }
 4190: 
 4191: </script>
 4192: LISTJAVASCRIPT
 4193:     &commonJSfunctions($request);
 4194:     my ($symb) = &get_symb($request);
 4195:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4196:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4197:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4198: 
 4199:     my $result='<h3><span class="LC_info">&nbsp;'.
 4200: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4201: 
 4202:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4203:     my $map_error;
 4204:     my ($titles,$symbx) = &getSymbMap($map_error);
 4205:     if ($map_error) {
 4206:         $request->print(&navmap_errormsg());
 4207:         return;
 4208:     }
 4209:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4210: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4211: #    my $type=($curpage =~ /\.(page|sequence)/);
 4212:     my $select = '<select name="selectpage">'."\n";
 4213:     my $ctr=0;
 4214:     foreach (@$titles) {
 4215: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4216: 	$select.='<option value="'.$ctr.'" '.
 4217: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4218: 	    '>'.$showtitle.'</option>'."\n";
 4219: 	$ctr++;
 4220:     }
 4221:     $select.= '</select>';
 4222:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4223: 
 4224:     $ctr=0;
 4225:     foreach (@$titles) {
 4226: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4227: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4228: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4229: 	$ctr++;
 4230:     }
 4231:     $result.='<input type="hidden" name="page" />'."\n".
 4232: 	'<input type="hidden" name="title" />'."\n";
 4233: 
 4234:     my $options =
 4235: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4236: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4237:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4238: 
 4239:     $options =
 4240: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4241: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4242: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4243:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4244:     
 4245:     $result.=&build_section_inputs();
 4246:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4247:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4248: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4249: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4250: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4251: 
 4252:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4253: 
 4254:     $result.='&nbsp;<input type="button" '.
 4255: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4256: 
 4257:     $request->print($result);
 4258: 
 4259:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4260: 	&Apache::loncommon::start_data_table().
 4261: 	&Apache::loncommon::start_data_table_header_row().
 4262: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4263: 	'<th>'.&nameUserString('header').'</th>'.
 4264: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4265: 	'<th>'.&nameUserString('header').'</th>'.
 4266: 	&Apache::loncommon::end_data_table_header_row();
 4267:  
 4268:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4269:     my $ptr = 1;
 4270:     foreach my $student (sort 
 4271: 			 {
 4272: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4273: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4274: 			     }
 4275: 			     return $a cmp $b;
 4276: 			 } (keys(%$fullname))) {
 4277: 	my ($uname,$udom) = split(/:/,$student);
 4278: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4279:                                   : '</td>');
 4280: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4281: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4282: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4283: 	$studentTable.=
 4284: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4285:                          : '');
 4286: 	$ptr++;
 4287:     }
 4288:     if ($ptr%2 == 0) {
 4289: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4290: 	    &Apache::loncommon::end_data_table_row();
 4291:     }
 4292:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4293:     $studentTable.='<input type="button" '.
 4294: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4295: 
 4296:     $studentTable.=&show_grading_menu_form($symb);
 4297:     $request->print($studentTable);
 4298: 
 4299:     return '';
 4300: }
 4301: 
 4302: sub getSymbMap {
 4303:     my ($map_error) = @_;
 4304:     my $navmap = Apache::lonnavmaps::navmap->new();
 4305:     unless (ref($navmap)) {
 4306:         if (ref($map_error)) {
 4307:             $$map_error = 'navmap';
 4308:         }
 4309:         return;
 4310:     }
 4311:     my %symbx = ();
 4312:     my @titles = ();
 4313:     my $minder = 0;
 4314: 
 4315:     # Gather every sequence that has problems.
 4316:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4317: 					       1,0,1);
 4318:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4319: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4320: 	    my $title = $minder.'.'.
 4321: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4322: 	    push(@titles, $title); # minder in case two titles are identical
 4323: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4324: 	    $minder++;
 4325: 	}
 4326:     }
 4327:     return \@titles,\%symbx;
 4328: }
 4329: 
 4330: #
 4331: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4332: sub displayPage {
 4333:     my ($request) = shift;
 4334: 
 4335:     my ($symb) = &get_symb($request);
 4336:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4337:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4338:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4339:     my $pageTitle = $env{'form.page'};
 4340:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4341:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4342:     my $usec=$classlist->{$env{'form.student'}}[5];
 4343: 
 4344:     #need to make sure we have the correct data for later EXT calls, 
 4345:     #thus invalidate the cache
 4346:     &Apache::lonnet::devalidatecourseresdata(
 4347:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4348:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4349:     &Apache::lonnet::clear_EXT_cache_status();
 4350: 
 4351:     if (!&canview($usec)) {
 4352: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4353: 	$request->print(&show_grading_menu_form($symb));
 4354: 	return;
 4355:     }
 4356:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4357:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4358: 	'</h3>'."\n";
 4359:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4360:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4361: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4362:     } else {
 4363: 	delete($env{'form.CODE'});
 4364:     }
 4365:     &sub_page_js($request);
 4366:     $request->print($result);
 4367: 
 4368:     my $navmap = Apache::lonnavmaps::navmap->new();
 4369:     unless (ref($navmap)) {
 4370:         $request->print(&navmap_errormsg());
 4371:         $request->print(&show_grading_menu_form($symb));
 4372:         return;
 4373:     }
 4374:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4375:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4376:     if (!$map) {
 4377: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4378: 	$request->print(&show_grading_menu_form($symb));
 4379: 	return; 
 4380:     }
 4381:     my $iterator = $navmap->getIterator($map->map_start(),
 4382: 					$map->map_finish());
 4383: 
 4384:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4385: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4386: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4387: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4388: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4389: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4390: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4391: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4392: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4393: 
 4394:     if (defined($env{'form.CODE'})) {
 4395: 	$studentTable.=
 4396: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4397:     }
 4398:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4399: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4400: 
 4401:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4402: 	&Apache::loncommon::start_data_table().
 4403: 	&Apache::loncommon::start_data_table_header_row().
 4404: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4405: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4406: 	&Apache::loncommon::end_data_table_header_row();
 4407: 
 4408:     &Apache::lonxml::clear_problem_counter();
 4409:     my ($depth,$question,$prob) = (1,1,1);
 4410:     $iterator->next(); # skip the first BEGIN_MAP
 4411:     my $curRes = $iterator->next(); # for "current resource"
 4412:     while ($depth > 0) {
 4413:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4414:         if($curRes == $iterator->END_MAP) { $depth--; }
 4415: 
 4416:         if (ref($curRes) && $curRes->is_problem()) {
 4417: 	    my $parts = $curRes->parts();
 4418:             my $title = $curRes->compTitle();
 4419: 	    my $symbx = $curRes->symb();
 4420: 	    $studentTable.=
 4421: 		&Apache::loncommon::start_data_table_row().
 4422: 		'<td align="center" valign="top" >'.$prob.
 4423: 		(scalar(@{$parts}) == 1 ? '' 
 4424: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4425: 							scalar(@{$parts}))
 4426: 		 ).
 4427: 		 '</td>';
 4428: 	    $studentTable.='<td valign="top">';
 4429: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4430: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4431: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4432: 					     undef,'both',\%form);
 4433: 	    } else {
 4434: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4435: 		$companswer =~ s|<form(.*?)>||g;
 4436: 		$companswer =~ s|</form>||g;
 4437: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4438: #		    $companswer =~ s/$1/ /ms;
 4439: #		    $request->print('match='.$1."<br />\n");
 4440: #		}
 4441: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4442: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4443: 	    }
 4444: 
 4445: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4446: 
 4447: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4448: 		if ($record{'version'} eq '') {
 4449: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4450: 		} else {
 4451: 		    my %responseType = ();
 4452: 		    foreach my $partid (@{$parts}) {
 4453: 			my @responseIds =$curRes->responseIds($partid);
 4454: 			my @responseType =$curRes->responseType($partid);
 4455: 			my %responseIds;
 4456: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4457: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4458: 			}
 4459: 			$responseType{$partid} = \%responseIds;
 4460: 		    }
 4461: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4462: 
 4463: 		}
 4464: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4465: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4466: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4467: 									$env{'request.course.id'},
 4468: 									'','.submission');
 4469:  
 4470: 	    }
 4471: 	    if (&canmodify($usec)) {
 4472: 		foreach my $partid (@{$parts}) {
 4473: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4474: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4475: 		    $question++;
 4476: 		}
 4477: 		$prob++;
 4478: 	    }
 4479: 	    $studentTable.='</td></tr>';
 4480: 
 4481: 	}
 4482:         $curRes = $iterator->next();
 4483:     }
 4484: 
 4485:     $studentTable.='</table>'."\n".
 4486: 	'<input type="button" value="'.&mt('Save').'" '.
 4487: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4488: 	'</form>'."\n";
 4489:     $studentTable.=&show_grading_menu_form($symb);
 4490:     $request->print($studentTable);
 4491: 
 4492:     return '';
 4493: }
 4494: 
 4495: sub displaySubByDates {
 4496:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4497:     my $isCODE=0;
 4498:     my $isTask = ($symb =~/\.task$/);
 4499:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4500:     my $studentTable=&Apache::loncommon::start_data_table().
 4501: 	&Apache::loncommon::start_data_table_header_row().
 4502: 	'<th>'.&mt('Date/Time').'</th>'.
 4503: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4504: 	'<th>'.&mt('Submission').'</th>'.
 4505: 	'<th>'.&mt('Status').'</th>'.
 4506: 	&Apache::loncommon::end_data_table_header_row();
 4507:     my ($version);
 4508:     my %mark;
 4509:     my %orders;
 4510:     $mark{'correct_by_student'} = $checkIcon;
 4511:     if (!exists($$record{'1:timestamp'})) {
 4512: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4513:     }
 4514: 
 4515:     my $interaction;
 4516:     my $no_increment = 1;
 4517:     for ($version=1;$version<=$$record{'version'};$version++) {
 4518: 	my $timestamp = 
 4519: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4520: 	if (exists($$record{$version.':resource.0.version'})) {
 4521: 	    $interaction = $$record{$version.':resource.0.version'};
 4522: 	}
 4523: 
 4524: 	my $where = ($isTask ? "$version:resource.$interaction"
 4525: 		             : "$version:resource");
 4526: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4527: 	    '<td>'.$timestamp.'</td>';
 4528: 	if ($isCODE) {
 4529: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4530: 	}
 4531: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4532: 	my @displaySub = ();
 4533: 	foreach my $partid (@{$parts}) {
 4534: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4535: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4536: 	    
 4537: 
 4538: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4539: 	    my $display_part=&get_display_part($partid,$symb);
 4540: 	    foreach my $matchKey (@matchKey) {
 4541: 		if (exists($$record{$version.':'.$matchKey}) &&
 4542: 		    $$record{$version.':'.$matchKey} ne '') {
 4543: 
 4544: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4545: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4546: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4547: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4548: 			$responseId.')</span>&nbsp;<b>';
 4549: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4550: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4551: 		    } else {
 4552: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4553: 					    $$record{"$where.$partid.tries"});
 4554: 		    }
 4555: 		    my $responseType=($isTask ? 'Task'
 4556:                                               : $responseType->{$partid}->{$responseId});
 4557: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4558: 		    if (!exists($orders{$partid}->{$responseId})) {
 4559: 			$orders{$partid}->{$responseId}=
 4560: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4561:                                        $no_increment);
 4562: 		    }
 4563: 		    $displaySub[0].='</b>&nbsp; '.
 4564: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4565: 		}
 4566: 	    }
 4567: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4568: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4569: 				    $$record{"$where.$partid.checkedin"},
 4570: 				    $$record{"$where.$partid.checkedin.slot"}).
 4571: 					'<br />';
 4572: 	    }
 4573: 	    if (exists $$record{"$where.$partid.award"}) {
 4574: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4575: 		    lc($$record{"$where.$partid.award"}).' '.
 4576: 		    $mark{$$record{"$where.$partid.solved"}}.
 4577: 		    '<br />';
 4578: 	    }
 4579: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4580: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4581: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4582: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4583: 		$displaySub[2].=
 4584: 		    $$record{"$version:resource.$partid.regrader"}.
 4585: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4586: 	    }
 4587: 	}
 4588: 	# needed because old essay regrader has not parts info
 4589: 	if (exists $$record{"$version:resource.regrader"}) {
 4590: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4591: 	}
 4592: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4593: 	if ($displaySub[2]) {
 4594: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4595: 	}
 4596: 	$studentTable.='&nbsp;</td>'.
 4597: 	    &Apache::loncommon::end_data_table_row();
 4598:     }
 4599:     $studentTable.=&Apache::loncommon::end_data_table();
 4600:     return $studentTable;
 4601: }
 4602: 
 4603: sub updateGradeByPage {
 4604:     my ($request) = shift;
 4605: 
 4606:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4607:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4608:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4609:     my $pageTitle = $env{'form.page'};
 4610:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4611:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4612:     my $usec=$classlist->{$env{'form.student'}}[5];
 4613:     if (!&canmodify($usec)) {
 4614: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4615: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4616: 	return;
 4617:     }
 4618:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4619:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4620: 	'</h3>'."\n";
 4621: 
 4622:     $request->print($result);
 4623: 
 4624:     my $navmap = Apache::lonnavmaps::navmap->new();
 4625:     unless (ref($navmap)) {
 4626:         $request->print(&navmap_errormsg());
 4627:         return;
 4628:     }
 4629:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4630:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4631:     if (!$map) {
 4632: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4633: 	my ($symb)=&get_symb($request);
 4634: 	$request->print(&show_grading_menu_form($symb));
 4635: 	return; 
 4636:     }
 4637:     my $iterator = $navmap->getIterator($map->map_start(),
 4638: 					$map->map_finish());
 4639: 
 4640:     my $studentTable=
 4641: 	&Apache::loncommon::start_data_table().
 4642: 	&Apache::loncommon::start_data_table_header_row().
 4643: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4644: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4645: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4646: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4647: 	&Apache::loncommon::end_data_table_header_row();
 4648: 
 4649:     $iterator->next(); # skip the first BEGIN_MAP
 4650:     my $curRes = $iterator->next(); # for "current resource"
 4651:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4652:     while ($depth > 0) {
 4653:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4654:         if($curRes == $iterator->END_MAP) { $depth--; }
 4655: 
 4656:         if (ref($curRes) && $curRes->is_problem()) {
 4657: 	    my $parts = $curRes->parts();
 4658:             my $title = $curRes->compTitle();
 4659: 	    my $symbx = $curRes->symb();
 4660: 	    $studentTable.=
 4661: 		&Apache::loncommon::start_data_table_row().
 4662: 		'<td align="center" valign="top" >'.$prob.
 4663: 		(scalar(@{$parts}) == 1 ? '' 
 4664:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4665: 		.')').'</td>';
 4666: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4667: 
 4668: 	    my %newrecord=();
 4669: 	    my @displayPts=();
 4670:             my %aggregate = ();
 4671:             my $aggregateflag = 0;
 4672: 	    foreach my $partid (@{$parts}) {
 4673: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4674: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4675: 
 4676: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4677: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4678: 		my $partial = $newpts/$wgt;
 4679: 		my $score;
 4680: 		if ($partial > 0) {
 4681: 		    $score = 'correct_by_override';
 4682: 		} elsif ($newpts ne '') { #empty is taken as 0
 4683: 		    $score = 'incorrect_by_override';
 4684: 		}
 4685: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4686: 		if ($dropMenu eq 'excused') {
 4687: 		    $partial = '';
 4688: 		    $score = 'excused';
 4689: 		} elsif ($dropMenu eq 'reset status'
 4690: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4691: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4692: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4693: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4694: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4695: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4696: 		    $changeflag++;
 4697: 		    $newpts = '';
 4698:                     
 4699:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4700:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4701:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4702:                     if ($aggtries > 0) {
 4703:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4704:                         $aggregateflag = 1;
 4705:                     }
 4706: 		}
 4707: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4708: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4709: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4710: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4711: 		    '&nbsp;<br />';
 4712: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4713: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4714: 		    '&nbsp;<br />';
 4715: 		$question++;
 4716: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4717: 
 4718: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4719: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4720: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4721: 		    if (scalar(keys(%newrecord)) > 0);
 4722: 
 4723: 		$changeflag++;
 4724: 	    }
 4725: 	    if (scalar(keys(%newrecord)) > 0) {
 4726: 		my %record = 
 4727: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4728: 					     $udom,$uname);
 4729: 
 4730: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4731: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4732: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4733: 		    $newrecord{'resource.CODE'} = '';
 4734: 		}
 4735: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4736: 					$udom,$uname);
 4737: 		%record = &Apache::lonnet::restore($symbx,
 4738: 						   $env{'request.course.id'},
 4739: 						   $udom,$uname);
 4740: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4741: 					     $cdom,$cnum,$udom,$uname);
 4742: 	    }
 4743: 	    
 4744:             if ($aggregateflag) {
 4745:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4746:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4747:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4748:             }
 4749: 
 4750: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4751: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4752: 		&Apache::loncommon::end_data_table_row();
 4753: 
 4754: 	    $prob++;
 4755: 	}
 4756:         $curRes = $iterator->next();
 4757:     }
 4758: 
 4759:     $studentTable.=&Apache::loncommon::end_data_table();
 4760:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4761:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4762: 		  &mt('The scores were changed for [quant,_1,problem].',
 4763: 		  $changeflag));
 4764:     $request->print($grademsg.$studentTable);
 4765: 
 4766:     return '';
 4767: }
 4768: 
 4769: #-------- end of section for handling grading by page/sequence ---------
 4770: #
 4771: #-------------------------------------------------------------------
 4772: 
 4773: #--------------------Bubblesheet (Scantron) Grading-----------------------------------
 4774: #
 4775: #------ start of section for handling grading by page/sequence ---------
 4776: 
 4777: =pod
 4778: 
 4779: =head1 Bubble sheet grading routines
 4780: 
 4781:   For this documentation:
 4782: 
 4783:    'scanline' refers to the full line of characters
 4784:    from the file that we are parsing that represents one entire sheet
 4785: 
 4786:    'bubble line' refers to the data
 4787:    representing the line of bubbles that are on the physical bubble sheet
 4788: 
 4789: 
 4790: The overall process is that a scanned in bubble sheet data is uploaded
 4791: into a course. When a user wants to grade, they select a
 4792: sequence/folder of resources, a file of bubble sheet info, and pick
 4793: one of the predefined configurations for what each scanline looks
 4794: like.
 4795: 
 4796: Next each scanline is checked for any errors of either 'missing
 4797: bubbles' (it's an error because it may have been mis-scanned
 4798: because too light bubbling), 'double bubble' (each bubble line should
 4799: have no more that one letter picked), invalid or duplicated CODE,
 4800: invalid student/employee ID
 4801: 
 4802: If the CODE option is used that determines the randomization of the
 4803: homework problems, either way the student/employee ID is looked up into a
 4804: username:domain.
 4805: 
 4806: During the validation phase the instructor can choose to skip scanlines. 
 4807: 
 4808: After the validation phase, there are now 3 bubble sheet files
 4809: 
 4810:   scantron_original_filename (unmodified original file)
 4811:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4812:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4813: 
 4814: Also there is a separate hash nohist_scantrondata that contains extra
 4815: correction information that isn't representable in the bubble sheet
 4816: file (see &scantron_getfile() for more information)
 4817: 
 4818: After all scanlines are either valid, marked as valid or skipped, then
 4819: foreach line foreach problem in the picked sequence, an ssi request is
 4820: made that simulates a user submitting their selected letter(s) against
 4821: the homework problem.
 4822: 
 4823: =over 4
 4824: 
 4825: 
 4826: 
 4827: =item defaultFormData
 4828: 
 4829:   Returns html hidden inputs used to hold context/default values.
 4830: 
 4831:  Arguments:
 4832:    $symb - $symb of the current resource
 4833:    $map_error - ref to scalar which will container error if
 4834:                 $navmap object is unavailable in &getSymbMap().
 4835: 
 4836: =cut
 4837: 
 4838: sub defaultFormData {
 4839:     my ($symb)=@_;
 4840:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4841:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4842:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4843: }
 4844: 
 4845: 
 4846: =pod 
 4847: 
 4848: =item getSequenceDropDown
 4849: 
 4850:    Return html dropdown of possible sequences to grade
 4851:  
 4852:  Arguments:
 4853:    $symb - $symb of the current resource 
 4854: 
 4855: =cut
 4856: 
 4857: sub getSequenceDropDown {
 4858:     my ($symb,$map_error)=@_;
 4859:     my $result='<select name="selectpage">'."\n";
 4860:     my ($titles,$symbx) = &getSymbMap($map_error);
 4861:     if (ref($map_error)) {
 4862:         return if ($$map_error);
 4863:     }
 4864:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4865:     my $ctr=0;
 4866:     foreach (@$titles) {
 4867: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4868: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4869: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4870: 	    '>'.$showtitle.'</option>'."\n";
 4871: 	$ctr++;
 4872:     }
 4873:     $result.= '</select>';
 4874:     return $result;
 4875: }
 4876: 
 4877: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4878:                                    # key is zero-based index - 0, 1, 2 ...
 4879: 
 4880: my %first_bubble_line;             # First bubble line no. for each bubble.
 4881: 
 4882: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4883:                                    # matchresponse or rankresponse, where 
 4884:                                    # an individual response can have multiple 
 4885:                                    # lines
 4886: 
 4887: my %responsetype_per_response;     # responsetype for each response
 4888: 
 4889: # Save and restore the bubble lines array to the form env.
 4890: 
 4891: 
 4892: sub save_bubble_lines {
 4893:     foreach my $line (keys(%bubble_lines_per_response)) {
 4894: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4895: 	$env{"form.scantron.first_bubble_line.$line"} =
 4896: 	    $first_bubble_line{$line};
 4897:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4898:             $subdivided_bubble_lines{$line};
 4899:         $env{"form.scantron.responsetype.$line"} =
 4900:             $responsetype_per_response{$line};
 4901:     }
 4902: }
 4903: 
 4904: 
 4905: sub restore_bubble_lines {
 4906:     my $line = 0;
 4907:     %bubble_lines_per_response = ();
 4908:     while ($env{"form.scantron.bubblelines.$line"}) {
 4909: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4910: 	$bubble_lines_per_response{$line} = $value;
 4911: 	$first_bubble_line{$line}  =
 4912: 	    $env{"form.scantron.first_bubble_line.$line"};
 4913:         $subdivided_bubble_lines{$line} =
 4914:             $env{"form.scantron.sub_bubblelines.$line"};
 4915:         $responsetype_per_response{$line} =
 4916:             $env{"form.scantron.responsetype.$line"};
 4917: 	$line++;
 4918:     }
 4919: }
 4920: 
 4921: #  Given the parsed scanline, get the response for 
 4922: #  'answer' number n:
 4923: 
 4924: sub get_response_bubbles {
 4925:     my ($parsed_line, $response)  = @_;
 4926: 
 4927:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4928:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4929:     
 4930:     my $selected = "";
 4931: 
 4932:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4933: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4934: 	$bubble_line++;
 4935:     }
 4936:     return $selected;
 4937: }
 4938: 
 4939: =pod 
 4940: 
 4941: =item scantron_filenames
 4942: 
 4943:    Returns a list of the scantron files in the current course 
 4944: 
 4945: =cut
 4946: 
 4947: sub scantron_filenames {
 4948:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4949:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4950:     my $getpropath = 1;
 4951:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4952:                                        $getpropath);
 4953:     my @possiblenames;
 4954:     foreach my $filename (sort(@files)) {
 4955: 	($filename)=split(/&/,$filename);
 4956: 	if ($filename!~/^scantron_orig_/) { next ; }
 4957: 	$filename=~s/^scantron_orig_//;
 4958: 	push(@possiblenames,$filename);
 4959:     }
 4960:     return @possiblenames;
 4961: }
 4962: 
 4963: =pod 
 4964: 
 4965: =item scantron_uploads
 4966: 
 4967:    Returns  html drop-down list of scantron files in current course.
 4968: 
 4969:  Arguments:
 4970:    $file2grade - filename to set as selected in the dropdown
 4971: 
 4972: =cut
 4973: 
 4974: sub scantron_uploads {
 4975:     my ($file2grade) = @_;
 4976:     my $result=	'<select name="scantron_selectfile">';
 4977:     $result.="<option></option>";
 4978:     foreach my $filename (sort(&scantron_filenames())) {
 4979: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4980:     }
 4981:     $result.="</select>";
 4982:     return $result;
 4983: }
 4984: 
 4985: =pod 
 4986: 
 4987: =item scantron_scantab
 4988: 
 4989:   Returns html drop down of the scantron formats in the scantronformat.tab
 4990:   file.
 4991: 
 4992: =cut
 4993: 
 4994: sub scantron_scantab {
 4995:     my $result='<select name="scantron_format">'."\n";
 4996:     $result.='<option></option>'."\n";
 4997:     my @lines = &get_scantronformat_file();
 4998:     if (@lines > 0) {
 4999:         foreach my $line (@lines) {
 5000:             next if (($line =~ /^\#/) || ($line eq ''));
 5001: 	    my ($name,$descrip)=split(/:/,$line);
 5002: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5003:         }
 5004:     }
 5005:     $result.='</select>'."\n";
 5006:     return $result;
 5007: }
 5008: 
 5009: =pod
 5010: 
 5011: =item get_scantronformat_file
 5012: 
 5013:   Returns an array containing lines from the scantron format file for
 5014:   the domain of the course.
 5015: 
 5016:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5017:   lines are from this file.
 5018: 
 5019:   Otherwise, if a default.tab has been published in RES space by the 
 5020:   domainconfig user, lines are from this file.
 5021: 
 5022:   Otherwise, fall back to getting lines from the legacy file on the
 5023:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5024: 
 5025: =cut
 5026: 
 5027: sub get_scantronformat_file {
 5028:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5029:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5030:     my $gottab = 0;
 5031:     my @lines;
 5032:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5033:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5034:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5035:             if ($formatfile ne '-1') {
 5036:                 @lines = split("\n",$formatfile,-1);
 5037:                 $gottab = 1;
 5038:             }
 5039:         }
 5040:     }
 5041:     if (!$gottab) {
 5042:         my $confname = $cdom.'-domainconfig';
 5043:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5044:         my $formatfile =  &Apache::lonnet::getfile($default);
 5045:         if ($formatfile ne '-1') {
 5046:             @lines = split("\n",$formatfile,-1);
 5047:             $gottab = 1;
 5048:         }
 5049:     }
 5050:     if (!$gottab) {
 5051:         my @domains = &Apache::lonnet::current_machine_domains();
 5052:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5053:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5054:             @lines = <$fh>;
 5055:             close($fh);
 5056:         } else {
 5057:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5058:             @lines = <$fh>;
 5059:             close($fh);
 5060:         }
 5061:     }
 5062:     return @lines;
 5063: }
 5064: 
 5065: =pod 
 5066: 
 5067: =item scantron_CODElist
 5068: 
 5069:   Returns html drop down of the saved CODE lists from current course,
 5070:   generated from earlier printings.
 5071: 
 5072: =cut
 5073: 
 5074: sub scantron_CODElist {
 5075:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5076:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5077:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5078:     my $namechoice='<option></option>';
 5079:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5080: 	if ($name =~ /^error: 2 /) { next; }
 5081: 	if ($name =~ /^type\0/) { next; }
 5082: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5083:     }
 5084:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5085:     return $namechoice;
 5086: }
 5087: 
 5088: =pod 
 5089: 
 5090: =item scantron_CODEunique
 5091: 
 5092:   Returns the html for "Each CODE to be used once" radio.
 5093: 
 5094: =cut
 5095: 
 5096: sub scantron_CODEunique {
 5097:     my $result='<span class="LC_nobreak">
 5098:                  <label><input type="radio" name="scantron_CODEunique"
 5099:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5100:                 </span>
 5101:                 <span class="LC_nobreak">
 5102:                  <label><input type="radio" name="scantron_CODEunique"
 5103:                         value="no" />'.&mt('No').' </label>
 5104:                 </span>';
 5105:     return $result;
 5106: }
 5107: 
 5108: =pod 
 5109: 
 5110: =item scantron_selectphase
 5111: 
 5112:   Generates the initial screen to start the bubble sheet process.
 5113:   Allows for - starting a grading run.
 5114:              - downloading existing scan data (original, corrected
 5115:                                                 or skipped info)
 5116: 
 5117:              - uploading new scan data
 5118: 
 5119:  Arguments:
 5120:   $r          - The Apache request object
 5121:   $file2grade - name of the file that contain the scanned data to score
 5122: 
 5123: =cut
 5124: 
 5125: sub scantron_selectphase {
 5126:     my ($r,$file2grade) = @_;
 5127:     my ($symb)=&get_symb($r);
 5128:     if (!$symb) {return '';}
 5129:     my $map_error;
 5130:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5131:     if ($map_error) {
 5132:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5133:         return;
 5134:     }
 5135:     my $default_form_data=&defaultFormData($symb);
 5136:     my $grading_menu_button=&show_grading_menu_form($symb);
 5137:     my $file_selector=&scantron_uploads($file2grade);
 5138:     my $format_selector=&scantron_scantab();
 5139:     my $CODE_selector=&scantron_CODElist();
 5140:     my $CODE_unique=&scantron_CODEunique();
 5141:     my $result;
 5142: 
 5143:     $ssi_error = 0;
 5144: 
 5145:     # Chunk of form to prompt for a file to grade and how:
 5146: 
 5147:     $result.= '
 5148:     <br />
 5149:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5150:     <input type="hidden" name="command" value="scantron_warning" />
 5151:     '.$default_form_data.'
 5152:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5153:        '.&Apache::loncommon::start_data_table_header_row().'
 5154:             <th colspan="2">
 5155:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5156:             </th>
 5157:        '.&Apache::loncommon::end_data_table_header_row().'
 5158:        '.&Apache::loncommon::start_data_table_row().'
 5159:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5160:        '.&Apache::loncommon::end_data_table_row().'
 5161:        '.&Apache::loncommon::start_data_table_row().'
 5162:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5163:        '.&Apache::loncommon::end_data_table_row().'
 5164:        '.&Apache::loncommon::start_data_table_row().'
 5165:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5166:        '.&Apache::loncommon::end_data_table_row().'
 5167:        '.&Apache::loncommon::start_data_table_row().'
 5168:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5169:        '.&Apache::loncommon::end_data_table_row().'
 5170:        '.&Apache::loncommon::start_data_table_row().'
 5171:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5172:        '.&Apache::loncommon::end_data_table_row().'
 5173:        '.&Apache::loncommon::start_data_table_row().'
 5174: 	    <td> '.&mt('Options:').' </td>
 5175:             <td>
 5176: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5177:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5178:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5179: 	    </td>
 5180:        '.&Apache::loncommon::end_data_table_row().'
 5181:        '.&Apache::loncommon::start_data_table_row().'
 5182:             <td colspan="2">
 5183:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5184:             </td>
 5185:        '.&Apache::loncommon::end_data_table_row().'
 5186:     '.&Apache::loncommon::end_data_table().'
 5187:     </form>
 5188: ';
 5189:    
 5190:     $r->print($result);
 5191: 
 5192:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5193:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5194: 
 5195: 	# Chunk of form to prompt for a scantron file upload.
 5196: 
 5197:         $r->print('
 5198:     <br />
 5199:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5200:        '.&Apache::loncommon::start_data_table_header_row().'
 5201:             <th>
 5202:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5203:             </th>
 5204:        '.&Apache::loncommon::end_data_table_header_row().'
 5205:        '.&Apache::loncommon::start_data_table_row().'
 5206:             <td>
 5207: ');
 5208:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5209:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5210:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5211:     $r->print('
 5212:               <script type="text/javascript" language="javascript">
 5213:     function checkUpload(formname) {
 5214: 	if (formname.upfile.value == "") {
 5215: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5216: 	    return false;
 5217: 	}
 5218: 	formname.submit();
 5219:     }
 5220:               </script>
 5221: 
 5222:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5223:                 '.$default_form_data.'
 5224:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5225:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5226:                 <input name="command" value="scantronupload_save" type="hidden" />
 5227:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5228:                 <br />
 5229:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5230:               </form>
 5231: ');
 5232: 
 5233:         $r->print('
 5234:             </td>
 5235:        '.&Apache::loncommon::end_data_table_row().'
 5236:        '.&Apache::loncommon::end_data_table().'
 5237: ');
 5238:     }
 5239: 
 5240:     # Chunk of the form that prompts to view a scoring office file,
 5241:     # corrected file, skipped records in a file.
 5242: 
 5243:     $r->print('
 5244:    <br />
 5245:    <form action="/adm/grades" name="scantron_download">
 5246:      '.$default_form_data.'
 5247:      <input type="hidden" name="command" value="scantron_download" />
 5248:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5249:        '.&Apache::loncommon::start_data_table_header_row().'
 5250:               <th>
 5251:                 &nbsp;'.&mt('Download a scoring office file').'
 5252:               </th>
 5253:        '.&Apache::loncommon::end_data_table_header_row().'
 5254:        '.&Apache::loncommon::start_data_table_row().'
 5255:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5256:                 <br />
 5257:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5258:        '.&Apache::loncommon::end_data_table_row().'
 5259:      '.&Apache::loncommon::end_data_table().'
 5260:    </form>
 5261:    <br />
 5262: ');
 5263: 
 5264:     &Apache::lonpickcode::code_list($r,2);
 5265: 
 5266:     $r->print('<br /><form method="post" name="checkscantron">'.
 5267:              $default_form_data."\n".
 5268:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5269:              &Apache::loncommon::start_data_table_header_row()."\n".
 5270:              '<th colspan="2">
 5271:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5272:              '</th>'."\n".
 5273:               &Apache::loncommon::end_data_table_header_row()."\n".
 5274:               &Apache::loncommon::start_data_table_row()."\n".
 5275:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5276:               '<td> '.$sequence_selector.' </td>'.
 5277:               &Apache::loncommon::end_data_table_row()."\n".
 5278:               &Apache::loncommon::start_data_table_row()."\n".
 5279:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5280:               '<td> '.$file_selector.' </td>'."\n".
 5281:               &Apache::loncommon::end_data_table_row()."\n".
 5282:               &Apache::loncommon::start_data_table_row()."\n".
 5283:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5284:               '<td> '.$format_selector.' </td>'."\n".
 5285:               &Apache::loncommon::end_data_table_row()."\n".
 5286:               &Apache::loncommon::start_data_table_row()."\n".
 5287:               '<td> '.&mt('Options').' </td>'."\n".
 5288:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5289:               &Apache::loncommon::end_data_table_row()."\n".
 5290:               &Apache::loncommon::start_data_table_row()."\n".
 5291:               '<td colspan="2">'."\n".
 5292:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5293:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5294:               '</td>'."\n".
 5295:               &Apache::loncommon::end_data_table_row()."\n".
 5296:               &Apache::loncommon::end_data_table()."\n".
 5297:               '</form><br />');
 5298:     $r->print($grading_menu_button);
 5299:     return;
 5300: }
 5301: 
 5302: =pod
 5303: 
 5304: =item get_scantron_config
 5305: 
 5306:    Parse and return the scantron configuration line selected as a
 5307:    hash of configuration file fields.
 5308: 
 5309:  Arguments:
 5310:     which - the name of the configuration to parse from the file.
 5311: 
 5312: 
 5313:  Returns:
 5314:             If the named configuration is not in the file, an empty
 5315:             hash is returned.
 5316:     a hash with the fields
 5317:       name         - internal name for the this configuration setup
 5318:       description  - text to display to operator that describes this config
 5319:       CODElocation - if 0 or the string 'none'
 5320:                           - no CODE exists for this config
 5321:                      if -1 || the string 'letter'
 5322:                           - a CODE exists for this config and is
 5323:                             a string of letters
 5324:                      Unsupported value (but planned for future support)
 5325:                           if a positive integer
 5326:                                - The CODE exists as the first n items from
 5327:                                  the question section of the form
 5328:                           if the string 'number'
 5329:                                - The CODE exists for this config and is
 5330:                                  a string of numbers
 5331:       CODEstart   - (only matter if a CODE exists) column in the line where
 5332:                      the CODE starts
 5333:       CODElength  - length of the CODE
 5334:       IDstart     - column where the student/employee ID starts
 5335:       IDlength    - length of the student/employee ID info
 5336:       Qstart      - column where the information from the bubbled
 5337:                     'questions' start
 5338:       Qlength     - number of columns comprising a single bubble line from
 5339:                     the sheet. (usually either 1 or 10)
 5340:       Qon         - either a single character representing the character used
 5341:                     to signal a bubble was chosen in the positional setup, or
 5342:                     the string 'letter' if the letter of the chosen bubble is
 5343:                     in the final, or 'number' if a number representing the
 5344:                     chosen bubble is in the file (1->A 0->J)
 5345:       Qoff        - the character used to represent that a bubble was
 5346:                     left blank
 5347:       PaperID     - if the scanning process generates a unique number for each
 5348:                     sheet scanned the column that this ID number starts in
 5349:       PaperIDlength - number of columns that comprise the unique ID number
 5350:                       for the sheet of paper
 5351:       FirstName   - column that the first name starts in
 5352:       FirstNameLength - number of columns that the first name spans
 5353:  
 5354:       LastName    - column that the last name starts in
 5355:       LastNameLength - number of columns that the last name spans
 5356: 
 5357: =cut
 5358: 
 5359: sub get_scantron_config {
 5360:     my ($which) = @_;
 5361:     my @lines = &get_scantronformat_file();
 5362:     my %config;
 5363:     #FIXME probably should move to XML it has already gotten a bit much now
 5364:     foreach my $line (@lines) {
 5365: 	my ($name,$descrip)=split(/:/,$line);
 5366: 	if ($name ne $which ) { next; }
 5367: 	chomp($line);
 5368: 	my @config=split(/:/,$line);
 5369: 	$config{'name'}=$config[0];
 5370: 	$config{'description'}=$config[1];
 5371: 	$config{'CODElocation'}=$config[2];
 5372: 	$config{'CODEstart'}=$config[3];
 5373: 	$config{'CODElength'}=$config[4];
 5374: 	$config{'IDstart'}=$config[5];
 5375: 	$config{'IDlength'}=$config[6];
 5376: 	$config{'Qstart'}=$config[7];
 5377:  	$config{'Qlength'}=$config[8];
 5378: 	$config{'Qoff'}=$config[9];
 5379: 	$config{'Qon'}=$config[10];
 5380: 	$config{'PaperID'}=$config[11];
 5381: 	$config{'PaperIDlength'}=$config[12];
 5382: 	$config{'FirstName'}=$config[13];
 5383: 	$config{'FirstNamelength'}=$config[14];
 5384: 	$config{'LastName'}=$config[15];
 5385: 	$config{'LastNamelength'}=$config[16];
 5386: 	last;
 5387:     }
 5388:     return %config;
 5389: }
 5390: 
 5391: =pod 
 5392: 
 5393: =item username_to_idmap
 5394: 
 5395:     creates a hash keyed by student/employee ID with values of the corresponding
 5396:     student username:domain.
 5397: 
 5398:   Arguments:
 5399: 
 5400:     $classlist - reference to the class list hash. This is a hash
 5401:                  keyed by student name:domain  whose elements are references
 5402:                  to arrays containing various chunks of information
 5403:                  about the student. (See loncoursedata for more info).
 5404: 
 5405:   Returns
 5406:     %idmap - the constructed hash
 5407: 
 5408: =cut
 5409: 
 5410: sub username_to_idmap {
 5411:     my ($classlist)= @_;
 5412:     my %idmap;
 5413:     foreach my $student (keys(%$classlist)) {
 5414: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5415: 	    $student;
 5416:     }
 5417:     return %idmap;
 5418: }
 5419: 
 5420: =pod
 5421: 
 5422: =item scantron_fixup_scanline
 5423: 
 5424:    Process a requested correction to a scanline.
 5425: 
 5426:   Arguments:
 5427:     $scantron_config   - hash from &get_scantron_config()
 5428:     $scan_data         - hash of correction information 
 5429:                           (see &scantron_getfile())
 5430:     $line              - existing scanline
 5431:     $whichline         - line number of the passed in scanline
 5432:     $field             - type of change to process 
 5433:                          (either 
 5434:                           'ID'     -> correct the student/employee ID
 5435:                           'CODE'   -> correct the CODE
 5436:                           'answer' -> fixup the submitted answers)
 5437:     
 5438:    $args               - hash of additional info,
 5439:                           - 'ID' 
 5440:                                'newid' -> studentID to use in replacement
 5441:                                           of existing one
 5442:                           - 'CODE' 
 5443:                                'CODE_ignore_dup' - set to true if duplicates
 5444:                                                    should be ignored.
 5445: 	                       'CODE' - is new code or 'use_unfound'
 5446:                                         if the existing unfound code should
 5447:                                         be used as is
 5448:                           - 'answer'
 5449:                                'response' - new answer or 'none' if blank
 5450:                                'question' - the bubble line to change
 5451:                                'questionnum' - the question identifier,
 5452:                                                may include subquestion. 
 5453: 
 5454:   Returns:
 5455:     $line - the modified scanline
 5456: 
 5457:   Side effects: 
 5458:     $scan_data - may be updated
 5459: 
 5460: =cut
 5461: 
 5462: 
 5463: sub scantron_fixup_scanline {
 5464:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5465:     if ($field eq 'ID') {
 5466: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5467: 	    return ($line,1,'New value too large');
 5468: 	}
 5469: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5470: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5471: 				     $args->{'newid'});
 5472: 	}
 5473: 	substr($line,$$scantron_config{'IDstart'}-1,
 5474: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5475: 	if ($args->{'newid'}=~/^\s*$/) {
 5476: 	    &scan_data($scan_data,"$whichline.user",
 5477: 		       $args->{'username'}.':'.$args->{'domain'});
 5478: 	}
 5479:     } elsif ($field eq 'CODE') {
 5480: 	if ($args->{'CODE_ignore_dup'}) {
 5481: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5482: 	}
 5483: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5484: 	if ($args->{'CODE'} ne 'use_unfound') {
 5485: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5486: 		return ($line,1,'New CODE value too large');
 5487: 	    }
 5488: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5489: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5490: 	    }
 5491: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5492: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5493: 	}
 5494:     } elsif ($field eq 'answer') {
 5495: 	my $length=$scantron_config->{'Qlength'};
 5496: 	my $off=$scantron_config->{'Qoff'};
 5497: 	my $on=$scantron_config->{'Qon'};
 5498: 	my $answer=${off}x$length;
 5499: 	if ($args->{'response'} eq 'none') {
 5500: 	    &scan_data($scan_data,
 5501: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5502: 	} else {
 5503: 	    if ($on eq 'letter') {
 5504: 		my @alphabet=('A'..'Z');
 5505: 		$answer=$alphabet[$args->{'response'}];
 5506: 	    } elsif ($on eq 'number') {
 5507: 		$answer=$args->{'response'}+1;
 5508: 		if ($answer == 10) { $answer = '0'; }
 5509: 	    } else {
 5510: 		substr($answer,$args->{'response'},1)=$on;
 5511: 	    }
 5512: 	    &scan_data($scan_data,
 5513: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5514: 	}
 5515: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5516: 	substr($line,$where-1,$length)=$answer;
 5517:     }
 5518:     return $line;
 5519: }
 5520: 
 5521: =pod
 5522: 
 5523: =item scan_data
 5524: 
 5525:     Edit or look up  an item in the scan_data hash.
 5526: 
 5527:   Arguments:
 5528:     $scan_data  - The hash (see scantron_getfile)
 5529:     $key        - shorthand of the key to edit (actual key is
 5530:                   scantronfilename_key).
 5531:     $data        - New value of the hash entry.
 5532:     $delete      - If true, the entry is removed from the hash.
 5533: 
 5534:   Returns:
 5535:     The new value of the hash table field (undefined if deleted).
 5536: 
 5537: =cut
 5538: 
 5539: 
 5540: sub scan_data {
 5541:     my ($scan_data,$key,$value,$delete)=@_;
 5542:     my $filename=$env{'form.scantron_selectfile'};
 5543:     if (defined($value)) {
 5544: 	$scan_data->{$filename.'_'.$key} = $value;
 5545:     }
 5546:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5547:     return $scan_data->{$filename.'_'.$key};
 5548: }
 5549: 
 5550: # ----- These first few routines are general use routines.----
 5551: 
 5552: # Return the number of occurences of a pattern in a string.
 5553: 
 5554: sub occurence_count {
 5555:     my ($string, $pattern) = @_;
 5556: 
 5557:     my @matches = ($string =~ /$pattern/g);
 5558: 
 5559:     return scalar(@matches);
 5560: }
 5561: 
 5562: 
 5563: # Take a string known to have digits and convert all the
 5564: # digits into letters in the range J,A..I.
 5565: 
 5566: sub digits_to_letters {
 5567:     my ($input) = @_;
 5568: 
 5569:     my @alphabet = ('J', 'A'..'I');
 5570: 
 5571:     my @input    = split(//, $input);
 5572:     my $output ='';
 5573:     for (my $i = 0; $i < scalar(@input); $i++) {
 5574: 	if ($input[$i] =~ /\d/) {
 5575: 	    $output .= $alphabet[$input[$i]];
 5576: 	} else {
 5577: 	    $output .= $input[$i];
 5578: 	}
 5579:     }
 5580:     return $output;
 5581: }
 5582: 
 5583: =pod 
 5584: 
 5585: =item scantron_parse_scanline
 5586: 
 5587:   Decodes a scanline from the selected scantron file
 5588: 
 5589:  Arguments:
 5590:     line             - The text of the scantron file line to process
 5591:     whichline        - Line number
 5592:     scantron_config  - Hash describing the format of the scantron lines.
 5593:     scan_data        - Hash of extra information about the scanline
 5594:                        (see scantron_getfile for more information)
 5595:     just_header      - True if should not process question answers but only
 5596:                        the stuff to the left of the answers.
 5597:  Returns:
 5598:    Hash containing the result of parsing the scanline
 5599: 
 5600:    Keys are all proceeded by the string 'scantron.'
 5601: 
 5602:        CODE    - the CODE in use for this scanline
 5603:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5604:                  by the operator
 5605:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5606:                             CODEs were selected, but the usage has been
 5607:                             forced by the operator
 5608:        ID  - student/employee ID
 5609:        PaperID - if used, the ID number printed on the sheet when the 
 5610:                  paper was scanned
 5611:        FirstName - first name from the sheet
 5612:        LastName  - last name from the sheet
 5613: 
 5614:      if just_header was not true these key may also exist
 5615: 
 5616:        missingerror - a list of bubble ranges that are considered to be answers
 5617:                       to a single question that don't have any bubbles filled in.
 5618:                       Of the form questionnumber:firstbubblenumber:count.
 5619:        doubleerror  - a list of bubble ranges that are considered to be answers
 5620:                       to a single question that have more than one bubble filled in.
 5621:                       Of the form questionnumber::firstbubblenumber:count
 5622:    
 5623:                 In the above, count is the number of bubble responses in the
 5624:                 input line needed to represent the possible answers to the question.
 5625:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5626:                 per line would have count = 2.
 5627: 
 5628:        maxquest     - the number of the last bubble line that was parsed
 5629: 
 5630:        (<number> starts at 1)
 5631:        <number>.answer - zero or more letters representing the selected
 5632:                          letters from the scanline for the bubble line 
 5633:                          <number>.
 5634:                          if blank there was either no bubble or there where
 5635:                          multiple bubbles, (consult the keys missingerror and
 5636:                          doubleerror if this is an error condition)
 5637: 
 5638: =cut
 5639: 
 5640: sub scantron_parse_scanline {
 5641:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5642: 
 5643:     my %record;
 5644:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5645:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5646:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5647:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5648: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5649: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5650: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5651: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5652: 	    $record{'scantron.CODE'}=substr($data,
 5653: 					    $$scantron_config{'CODEstart'}-1,
 5654: 					    $$scantron_config{'CODElength'});
 5655: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5656: 		$record{'scantron.useCODE'}=1;
 5657: 	    }
 5658: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5659: 		$record{'scantron.CODE_ignore_dup'}=1;
 5660: 	    }
 5661: 	} else {
 5662: 	    #FIXME interpret first N questions
 5663: 	}
 5664:     }
 5665:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5666: 				  $$scantron_config{'IDlength'});
 5667:     $record{'scantron.PaperID'}=
 5668: 	substr($data,$$scantron_config{'PaperID'}-1,
 5669: 	       $$scantron_config{'PaperIDlength'});
 5670:     $record{'scantron.FirstName'}=
 5671: 	substr($data,$$scantron_config{'FirstName'}-1,
 5672: 	       $$scantron_config{'FirstNamelength'});
 5673:     $record{'scantron.LastName'}=
 5674: 	substr($data,$$scantron_config{'LastName'}-1,
 5675: 	       $$scantron_config{'LastNamelength'});
 5676:     if ($just_header) { return \%record; }
 5677: 
 5678:     my @alphabet=('A'..'Z');
 5679:     my $questnum=0;
 5680:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5681: 
 5682:     chomp($questions);		# Get rid of any trailing \n.
 5683:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5684:     while (length($questions)) {
 5685: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5686:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5687:                              || 1;
 5688:         $questnum++;
 5689:         my $quest_id = $questnum;
 5690:         my $currentquest = substr($questions,0,$answer_length);
 5691:         $questions       = substr($questions,$answer_length);
 5692:         if (length($currentquest) < $answer_length) { next; }
 5693: 
 5694:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5695:             my $subquestnum = 1;
 5696:             my $subquestions = $currentquest;
 5697:             my @subanswers_needed = 
 5698:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5699:             foreach my $subans (@subanswers_needed) {
 5700:                 my $subans_length =
 5701:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5702:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5703:                 $subquestions   = substr($subquestions,$subans_length);
 5704:                 $quest_id = "$questnum.$subquestnum";
 5705:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5706:                     ($$scantron_config{'Qon'} eq 'number')) {
 5707:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5708:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5709:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5710:                 } else {
 5711:                     $ansnum = &scantron_validator_positional($ansnum,
 5712:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5713:                 }
 5714:                 $subquestnum ++;
 5715:             }
 5716:         } else {
 5717:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5718:                 ($$scantron_config{'Qon'} eq 'number')) {
 5719:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5720:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5721:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5722:             } else {
 5723:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5724:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5725:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5726:             }
 5727:         }
 5728:     }
 5729:     $record{'scantron.maxquest'}=$questnum;
 5730:     return \%record;
 5731: }
 5732: 
 5733: sub scantron_validator_lettnum {
 5734:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5735:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5736: 
 5737:     # Qon 'letter' implies for each slot in currquest we have:
 5738:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5739:     #    about anything else (esp. a value of Qoff) for missing
 5740:     #    bubbles.
 5741:     #
 5742:     # Qon 'number' implies each slot gives a digit that indexes the
 5743:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5744:     #    and * or ? for double bubbles on a single line.
 5745:     #
 5746: 
 5747:     my $matchon;
 5748:     if ($$scantron_config{'Qon'} eq 'letter') {
 5749:         $matchon = '[A-Z]';
 5750:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5751:         $matchon = '\d';
 5752:     }
 5753:     my $occurrences = 0;
 5754:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5755:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5756:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5757:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5758:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5759:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5760:         my @singlelines = split('',$currquest);
 5761:         foreach my $entry (@singlelines) {
 5762:             $occurrences = &occurence_count($entry,$matchon);
 5763:             if ($occurrences > 1) {
 5764:                 last;
 5765:             }
 5766:         } 
 5767:     } else {
 5768:         $occurrences = &occurence_count($currquest,$matchon); 
 5769:     }
 5770:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5771:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5772:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5773:             my $bubble = substr($currquest,$ans,1);
 5774:             if ($bubble =~ /$matchon/ ) {
 5775:                 if ($$scantron_config{'Qon'} eq 'number') {
 5776:                     if ($bubble == 0) {
 5777:                         $bubble = 10; 
 5778:                     }
 5779:                     $record->{"scantron.$ansnum.answer"} = 
 5780:                         $alphabet->[$bubble-1];
 5781:                 } else {
 5782:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5783:                 }
 5784:             } else {
 5785:                 $record->{"scantron.$ansnum.answer"}='';
 5786:             }
 5787:             $ansnum++;
 5788:         }
 5789:     } elsif (!defined($currquest)
 5790:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5791:             || (&occurence_count($currquest,$matchon) == 0)) {
 5792:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5793:             $record->{"scantron.$ansnum.answer"}='';
 5794:             $ansnum++;
 5795:         }
 5796:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5797:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5798:         }
 5799:     } else {
 5800:         if ($$scantron_config{'Qon'} eq 'number') {
 5801:             $currquest = &digits_to_letters($currquest);            
 5802:         }
 5803:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5804:             my $bubble = substr($currquest,$ans,1);
 5805:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5806:             $ansnum++;
 5807:         }
 5808:     }
 5809:     return $ansnum;
 5810: }
 5811: 
 5812: sub scantron_validator_positional {
 5813:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5814:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5815: 
 5816:     # Otherwise there's a positional notation;
 5817:     # each bubble line requires Qlength items, and there are filled in
 5818:     # bubbles for each case where there 'Qon' characters.
 5819:     #
 5820: 
 5821:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5822: 
 5823:     # If the split only gives us one element.. the full length of the
 5824:     # answer string, no bubbles are filled in:
 5825: 
 5826:     if ($answers_needed eq '') {
 5827:         return;
 5828:     }
 5829: 
 5830:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5831:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5832:             $record->{"scantron.$ansnum.answer"}='';
 5833:             $ansnum++;
 5834:         }
 5835:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5836:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5837:         }
 5838:     } elsif (scalar(@array) == 2) {
 5839:         my $location = length($array[0]);
 5840:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5841:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5842:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5843:             if ($ans eq $line_num) {
 5844:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5845:             } else {
 5846:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5847:             }
 5848:             $ansnum++;
 5849:          }
 5850:     } else {
 5851:         #  If there's more than one instance of a bubble character
 5852:         #  That's a double bubble; with positional notation we can
 5853:         #  record all the bubbles filled in as well as the
 5854:         #  fact this response consists of multiple bubbles.
 5855:         #
 5856:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5857:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5858:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5859:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5860:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5861:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5862:             my $doubleerror = 0;
 5863:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5864:                    (!$doubleerror)) {
 5865:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5866:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5867:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5868:                if (length(@currarray) > 2) {
 5869:                    $doubleerror = 1;
 5870:                } 
 5871:             }
 5872:             if ($doubleerror) {
 5873:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5874:             }
 5875:         } else {
 5876:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5877:         }
 5878:         my $item = $ansnum;
 5879:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5880:             $record->{"scantron.$item.answer"} = '';
 5881:             $item ++;
 5882:         }
 5883: 
 5884:         my @ans=@array;
 5885:         my $i=0;
 5886:         my $increment = 0;
 5887:         while ($#ans) {
 5888:             $i+=length($ans[0]) + $increment;
 5889:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5890:             my $bubble = $i%$$scantron_config{'Qlength'};
 5891:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5892:             shift(@ans);
 5893:             $increment = 1;
 5894:         }
 5895:         $ansnum += $answers_needed;
 5896:     }
 5897:     return $ansnum;
 5898: }
 5899: 
 5900: =pod
 5901: 
 5902: =item scantron_add_delay
 5903: 
 5904:    Adds an error message that occurred during the grading phase to a
 5905:    queue of messages to be shown after grading pass is complete
 5906: 
 5907:  Arguments:
 5908:    $delayqueue  - arrary ref of hash ref of error messages
 5909:    $scanline    - the scanline that caused the error
 5910:    $errormesage - the error message
 5911:    $errorcode   - a numeric code for the error
 5912: 
 5913:  Side Effects:
 5914:    updates the $delayqueue to have a new hash ref of the error
 5915: 
 5916: =cut
 5917: 
 5918: sub scantron_add_delay {
 5919:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5920:     push(@$delayqueue,
 5921: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5922: 	  'ecode' => $errorcode }
 5923: 	 );
 5924: }
 5925: 
 5926: =pod
 5927: 
 5928: =item scantron_find_student
 5929: 
 5930:    Finds the username for the current scanline
 5931: 
 5932:   Arguments:
 5933:    $scantron_record - hash result from scantron_parse_scanline
 5934:    $scan_data       - hash of correction information 
 5935:                       (see &scantron_getfile() form more information)
 5936:    $idmap           - hash from &username_to_idmap()
 5937:    $line            - number of current scanline
 5938:  
 5939:   Returns:
 5940:    Either 'username:domain' or undef if unknown
 5941: 
 5942: =cut
 5943: 
 5944: sub scantron_find_student {
 5945:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5946:     my $scanID=$$scantron_record{'scantron.ID'};
 5947:     if ($scanID =~ /^\s*$/) {
 5948:  	return &scan_data($scan_data,"$line.user");
 5949:     }
 5950:     foreach my $id (keys(%$idmap)) {
 5951:  	if (lc($id) eq lc($scanID)) {
 5952:  	    return $$idmap{$id};
 5953:  	}
 5954:     }
 5955:     return undef;
 5956: }
 5957: 
 5958: =pod
 5959: 
 5960: =item scantron_filter
 5961: 
 5962:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5963:    hidden resources was selected
 5964: 
 5965: =cut
 5966: 
 5967: sub scantron_filter {
 5968:     my ($curres)=@_;
 5969: 
 5970:     if (ref($curres) && $curres->is_problem()) {
 5971: 	# if the user has asked to not have either hidden
 5972: 	# or 'randomout' controlled resources to be graded
 5973: 	# don't include them
 5974: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5975: 	    && $curres->randomout) {
 5976: 	    return 0;
 5977: 	}
 5978: 	return 1;
 5979:     }
 5980:     return 0;
 5981: }
 5982: 
 5983: =pod
 5984: 
 5985: =item scantron_process_corrections
 5986: 
 5987:    Gets correction information out of submitted form data and corrects
 5988:    the scanline
 5989: 
 5990: =cut
 5991: 
 5992: sub scantron_process_corrections {
 5993:     my ($r) = @_;
 5994:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5995:     my ($scanlines,$scan_data)=&scantron_getfile();
 5996:     my $classlist=&Apache::loncoursedata::get_classlist();
 5997:     my $which=$env{'form.scantron_line'};
 5998:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5999:     my ($skip,$err,$errmsg);
 6000:     if ($env{'form.scantron_skip_record'}) {
 6001: 	$skip=1;
 6002:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6003: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6004: 	    $env{'form.scantron_domain'};
 6005: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6006: 	($line,$err,$errmsg)=
 6007: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6008: 				     'ID',{'newid'=>$newid,
 6009: 				    'username'=>$env{'form.scantron_username'},
 6010: 				    'domain'=>$env{'form.scantron_domain'}});
 6011:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6012: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6013: 	my $newCODE;
 6014: 	my %args;
 6015: 	if      ($resolution eq 'use_unfound') {
 6016: 	    $newCODE='use_unfound';
 6017: 	} elsif ($resolution eq 'use_found') {
 6018: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6019: 	} elsif ($resolution eq 'use_typed') {
 6020: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6021: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6022: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6023: 	}
 6024: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6025: 	    $args{'CODE_ignore_dup'}=1;
 6026: 	}
 6027: 	$args{'CODE'}=$newCODE;
 6028: 	($line,$err,$errmsg)=
 6029: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6030: 				     'CODE',\%args);
 6031:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6032: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6033: 	    ($line,$err,$errmsg)=
 6034: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6035: 					 $which,'answer',
 6036: 					 { 'question'=>$question,
 6037: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6038:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6039: 	    if ($err) { last; }
 6040: 	}
 6041:     }
 6042:     if ($err) {
 6043: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6044:     } else {
 6045: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6046: 	&scantron_putfile($scanlines,$scan_data);
 6047:     }
 6048: }
 6049: 
 6050: =pod
 6051: 
 6052: =item reset_skipping_status
 6053: 
 6054:    Forgets the current set of remember skipped scanlines (and thus
 6055:    reverts back to considering all lines in the
 6056:    scantron_skipped_<filename> file)
 6057: 
 6058: =cut
 6059: 
 6060: sub reset_skipping_status {
 6061:     my ($scanlines,$scan_data)=&scantron_getfile();
 6062:     &scan_data($scan_data,'remember_skipping',undef,1);
 6063:     &scantron_putfile(undef,$scan_data);
 6064: }
 6065: 
 6066: =pod
 6067: 
 6068: =item start_skipping
 6069: 
 6070:    Marks a scanline to be skipped. 
 6071: 
 6072: =cut
 6073: 
 6074: sub start_skipping {
 6075:     my ($scan_data,$i)=@_;
 6076:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6077:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6078: 	$remembered{$i}=2;
 6079:     } else {
 6080: 	$remembered{$i}=1;
 6081:     }
 6082:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6083: }
 6084: 
 6085: =pod
 6086: 
 6087: =item should_be_skipped
 6088: 
 6089:    Checks whether a scanline should be skipped.
 6090: 
 6091: =cut
 6092: 
 6093: sub should_be_skipped {
 6094:     my ($scanlines,$scan_data,$i)=@_;
 6095:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6096: 	# not redoing old skips
 6097: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6098: 	return 0;
 6099:     }
 6100:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6101: 
 6102:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6103: 	return 0;
 6104:     }
 6105:     return 1;
 6106: }
 6107: 
 6108: =pod
 6109: 
 6110: =item remember_current_skipped
 6111: 
 6112:    Discovers what scanlines are in the scantron_skipped_<filename>
 6113:    file and remembers them into scan_data for later use.
 6114: 
 6115: =cut
 6116: 
 6117: sub remember_current_skipped {
 6118:     my ($scanlines,$scan_data)=&scantron_getfile();
 6119:     my %to_remember;
 6120:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6121: 	if ($scanlines->{'skipped'}[$i]) {
 6122: 	    $to_remember{$i}=1;
 6123: 	}
 6124:     }
 6125: 
 6126:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6127:     &scantron_putfile(undef,$scan_data);
 6128: }
 6129: 
 6130: =pod
 6131: 
 6132: =item check_for_error
 6133: 
 6134:     Checks if there was an error when attempting to remove a specific
 6135:     scantron_.. bubble sheet data file. Prints out an error if
 6136:     something went wrong.
 6137: 
 6138: =cut
 6139: 
 6140: sub check_for_error {
 6141:     my ($r,$result)=@_;
 6142:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6143: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6144:     }
 6145: }
 6146: 
 6147: =pod
 6148: 
 6149: =item scantron_warning_screen
 6150: 
 6151:    Interstitial screen to make sure the operator has selected the
 6152:    correct options before we start the validation phase.
 6153: 
 6154: =cut
 6155: 
 6156: sub scantron_warning_screen {
 6157:     my ($button_text)=@_;
 6158:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6159:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6160:     my $CODElist;
 6161:     if ($scantron_config{'CODElocation'} &&
 6162: 	$scantron_config{'CODEstart'} &&
 6163: 	$scantron_config{'CODElength'}) {
 6164: 	$CODElist=$env{'form.scantron_CODElist'};
 6165: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6166: 	$CODElist=
 6167: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6168: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6169:     }
 6170:     return ('
 6171: <p>
 6172: <span class="LC_warning">
 6173: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6174: </p>
 6175: <table>
 6176: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6177: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6178: '.$CODElist.'
 6179: </table>
 6180: <br />
 6181: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6182: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6183: 
 6184: <br />
 6185: ');
 6186: }
 6187: 
 6188: =pod
 6189: 
 6190: =item scantron_do_warning
 6191: 
 6192:    Check if the operator has picked something for all required
 6193:    fields. Error out if something is missing.
 6194: 
 6195: =cut
 6196: 
 6197: sub scantron_do_warning {
 6198:     my ($r)=@_;
 6199:     my ($symb)=&get_symb($r);
 6200:     if (!$symb) {return '';}
 6201:     my $default_form_data=&defaultFormData($symb);
 6202:     $r->print(&scantron_form_start().$default_form_data);
 6203:     if ( $env{'form.selectpage'} eq '' ||
 6204: 	 $env{'form.scantron_selectfile'} eq '' ||
 6205: 	 $env{'form.scantron_format'} eq '' ) {
 6206: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6207: 	if ( $env{'form.selectpage'} eq '') {
 6208: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6209: 	} 
 6210: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6211: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6212: 	} 
 6213: 	if ( $env{'form.scantron_format'} eq '') {
 6214: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6215: 	} 
 6216:     } else {
 6217: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6218: 	$r->print('
 6219: '.$warning.'
 6220: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6221: <input type="hidden" name="command" value="scantron_validate" />
 6222: ');
 6223:     }
 6224:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6225:     return '';
 6226: }
 6227: 
 6228: =pod
 6229: 
 6230: =item scantron_form_start
 6231: 
 6232:     html hidden input for remembering all selected grading options
 6233: 
 6234: =cut
 6235: 
 6236: sub scantron_form_start {
 6237:     my ($max_bubble)=@_;
 6238:     my $result= <<SCANTRONFORM;
 6239: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6240:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6241:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6242:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6243:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6244:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6245:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6246:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6247:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6248:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6249: SCANTRONFORM
 6250: 
 6251:   my $line = 0;
 6252:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6253:        my $chunk =
 6254: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6255:        $chunk .=
 6256: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6257:        $chunk .= 
 6258:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6259:        $chunk .=
 6260:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6261:        $result .= $chunk;
 6262:        $line++;
 6263:    }
 6264:     return $result;
 6265: }
 6266: 
 6267: =pod
 6268: 
 6269: =item scantron_validate_file
 6270: 
 6271:     Dispatch routine for doing validation of a bubble sheet data file.
 6272: 
 6273:     Also processes any necessary information resets that need to
 6274:     occur before validation begins (ignore previous corrections,
 6275:     restarting the skipped records processing)
 6276: 
 6277: =cut
 6278: 
 6279: sub scantron_validate_file {
 6280:     my ($r) = @_;
 6281:     my ($symb)=&get_symb($r);
 6282:     if (!$symb) {return '';}
 6283:     my $default_form_data=&defaultFormData($symb);
 6284:     
 6285:     # do the detection of only doing skipped records first befroe we delete
 6286:     # them when doing the corrections reset
 6287:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6288: 	&reset_skipping_status();
 6289:     }
 6290:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6291: 	&remember_current_skipped();
 6292: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6293:     }
 6294: 
 6295:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6296: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6297: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6298: 	&check_for_error($r,&scantron_remove_scan_data());
 6299: 	$env{'form.scantron_options_ignore'}='done';
 6300:     }
 6301: 
 6302:     if ($env{'form.scantron_corrections'}) {
 6303: 	&scantron_process_corrections($r);
 6304:     }
 6305:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6306:     #get the student pick code ready
 6307:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6308:     my $nav_error;
 6309:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6310:     if ($nav_error) {
 6311:         $r->print(&navmap_errormsg());
 6312:         return '';
 6313:     }
 6314:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6315:     $r->print($result);
 6316:     
 6317:     my @validate_phases=( 'sequence',
 6318: 			  'ID',
 6319: 			  'CODE',
 6320: 			  'doublebubble',
 6321: 			  'missingbubbles');
 6322:     if (!$env{'form.validatepass'}) {
 6323: 	$env{'form.validatepass'} = 0;
 6324:     }
 6325:     my $currentphase=$env{'form.validatepass'};
 6326: 
 6327: 
 6328:     my $stop=0;
 6329:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6330: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6331: 	$r->rflush();
 6332: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6333: 	{
 6334: 	    no strict 'refs';
 6335: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6336: 	}
 6337:     }
 6338:     if (!$stop) {
 6339: 	my $warning=&scantron_warning_screen('Start Grading');
 6340: 	$r->print(&mt('Validation process complete.').'<br />'.
 6341:                   $warning.
 6342:                   &mt('Perform verification for each student after storage of submissions?').
 6343:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6344:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6345:                   ('&nbsp;'x3).'<label>'.
 6346:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6347:                   '</label></span><br />'.
 6348:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6349:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6350:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6351:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6352:     } else {
 6353: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6354: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6355:     }
 6356:     if ($stop) {
 6357: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6358: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6359: 	    $r->print(' '.&mt('this error').' <br />');
 6360: 
 6361: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6362: 	} else {
 6363:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6364: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6365:             } else {
 6366:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6367:             }
 6368: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6369: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6370: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6371: 	}
 6372:     }
 6373:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6374:     return '';
 6375: }
 6376: 
 6377: 
 6378: =pod
 6379: 
 6380: =item scantron_remove_file
 6381: 
 6382:    Removes the requested bubble sheet data file, makes sure that
 6383:    scantron_original_<filename> is never removed
 6384: 
 6385: 
 6386: =cut
 6387: 
 6388: sub scantron_remove_file {
 6389:     my ($which)=@_;
 6390:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6392:     my $file='scantron_';
 6393:     if ($which eq 'corrected' || $which eq 'skipped') {
 6394: 	$file.=$which.'_';
 6395:     } else {
 6396: 	return 'refused';
 6397:     }
 6398:     $file.=$env{'form.scantron_selectfile'};
 6399:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6400: }
 6401: 
 6402: 
 6403: =pod
 6404: 
 6405: =item scantron_remove_scan_data
 6406: 
 6407:    Removes all scan_data correction for the requested bubble sheet
 6408:    data file.  (In the case that both the are doing skipped records we need
 6409:    to remember the old skipped lines for the time being so that element
 6410:    persists for a while.)
 6411: 
 6412: =cut
 6413: 
 6414: sub scantron_remove_scan_data {
 6415:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6416:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6417:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6418:     my @todelete;
 6419:     my $filename=$env{'form.scantron_selectfile'};
 6420:     foreach my $key (@keys) {
 6421: 	if ($key=~/^\Q$filename\E_/) {
 6422: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6423: 		$key=~/remember_skipping/) {
 6424: 		next;
 6425: 	    }
 6426: 	    push(@todelete,$key);
 6427: 	}
 6428:     }
 6429:     my $result;
 6430:     if (@todelete) {
 6431: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6432: 				       \@todelete,$cdom,$cname);
 6433:     } else {
 6434: 	$result = 'ok';
 6435:     }
 6436:     return $result;
 6437: }
 6438: 
 6439: 
 6440: =pod
 6441: 
 6442: =item scantron_getfile
 6443: 
 6444:     Fetches the requested bubble sheet data file (all 3 versions), and
 6445:     the scan_data hash
 6446:   
 6447:   Arguments:
 6448:     None
 6449: 
 6450:   Returns:
 6451:     2 hash references
 6452: 
 6453:      - first one has 
 6454:          orig      -
 6455:          corrected -
 6456:          skipped   -  each of which points to an array ref of the specified
 6457:                       file broken up into individual lines
 6458:          count     - number of scanlines
 6459:  
 6460:      - second is the scan_data hash possible keys are
 6461:        ($number refers to scanline numbered $number and thus the key affects
 6462:         only that scanline
 6463:         $bubline refers to the specific bubble line element and the aspects
 6464:         refers to that specific bubble line element)
 6465: 
 6466:        $number.user - username:domain to use
 6467:        $number.CODE_ignore_dup 
 6468:                     - ignore the duplicate CODE error 
 6469:        $number.useCODE
 6470:                     - use the CODE in the scanline as is
 6471:        $number.no_bubble.$bubline
 6472:                     - it is valid that there is no bubbled in bubble
 6473:                       at $number $bubline
 6474:        remember_skipping
 6475:                     - a frozen hash containing keys of $number and values
 6476:                       of either 
 6477:                         1 - we are on a 'do skipped records pass' and plan
 6478:                             on processing this line
 6479:                         2 - we are on a 'do skipped records pass' and this
 6480:                             scanline has been marked to skip yet again
 6481: 
 6482: =cut
 6483: 
 6484: sub scantron_getfile {
 6485:     #FIXME really would prefer a scantron directory
 6486:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6487:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6488:     my $lines;
 6489:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6490: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6491:     my %scanlines;
 6492:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6493:     my $temp=$scanlines{'orig'};
 6494:     $scanlines{'count'}=$#$temp;
 6495: 
 6496:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6497: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6498:     if ($lines eq '-1') {
 6499: 	$scanlines{'corrected'}=[];
 6500:     } else {
 6501: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6502:     }
 6503:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6504: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6505:     if ($lines eq '-1') {
 6506: 	$scanlines{'skipped'}=[];
 6507:     } else {
 6508: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6509:     }
 6510:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6511:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6512:     my %scan_data = @tmp;
 6513:     return (\%scanlines,\%scan_data);
 6514: }
 6515: 
 6516: =pod
 6517: 
 6518: =item lonnet_putfile
 6519: 
 6520:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6521: 
 6522:  Arguments:
 6523:    $contents - data to store
 6524:    $filename - filename to store $contents into
 6525: 
 6526:  Returns:
 6527:    result value from &Apache::lonnet::finishuserfileupload
 6528: 
 6529: =cut
 6530: 
 6531: sub lonnet_putfile {
 6532:     my ($contents,$filename)=@_;
 6533:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6534:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6535:     $env{'form.sillywaytopassafilearound'}=$contents;
 6536:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6537: 
 6538: }
 6539: 
 6540: =pod
 6541: 
 6542: =item scantron_putfile
 6543: 
 6544:     Stores the current version of the bubble sheet data files, and the
 6545:     scan_data hash. (Does not modify the original version only the
 6546:     corrected and skipped versions.
 6547: 
 6548:  Arguments:
 6549:     $scanlines - hash ref that looks like the first return value from
 6550:                  &scantron_getfile()
 6551:     $scan_data - hash ref that looks like the second return value from
 6552:                  &scantron_getfile()
 6553: 
 6554: =cut
 6555: 
 6556: sub scantron_putfile {
 6557:     my ($scanlines,$scan_data) = @_;
 6558:     #FIXME really would prefer a scantron directory
 6559:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6560:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6561:     if ($scanlines) {
 6562: 	my $prefix='scantron_';
 6563: # no need to update orig, shouldn't change
 6564: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6565: #		    $env{'form.scantron_selectfile'});
 6566: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6567: 			$prefix.'corrected_'.
 6568: 			$env{'form.scantron_selectfile'});
 6569: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6570: 			$prefix.'skipped_'.
 6571: 			$env{'form.scantron_selectfile'});
 6572:     }
 6573:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6574: }
 6575: 
 6576: =pod
 6577: 
 6578: =item scantron_get_line
 6579: 
 6580:    Returns the correct version of the scanline
 6581: 
 6582:  Arguments:
 6583:     $scanlines - hash ref that looks like the first return value from
 6584:                  &scantron_getfile()
 6585:     $scan_data - hash ref that looks like the second return value from
 6586:                  &scantron_getfile()
 6587:     $i         - number of the requested line (starts at 0)
 6588: 
 6589:  Returns:
 6590:    A scanline, (either the original or the corrected one if it
 6591:    exists), or undef if the requested scanline should be
 6592:    skipped. (Either because it's an skipped scanline, or it's an
 6593:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6594:    pass.
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_get_line {
 6599:     my ($scanlines,$scan_data,$i)=@_;
 6600:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6601:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6602:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6603:     return $scanlines->{'orig'}[$i]; 
 6604: }
 6605: 
 6606: =pod
 6607: 
 6608: =item scantron_todo_count
 6609: 
 6610:     Counts the number of scanlines that need processing.
 6611: 
 6612:  Arguments:
 6613:     $scanlines - hash ref that looks like the first return value from
 6614:                  &scantron_getfile()
 6615:     $scan_data - hash ref that looks like the second return value from
 6616:                  &scantron_getfile()
 6617: 
 6618:  Returns:
 6619:     $count - number of scanlines to process
 6620: 
 6621: =cut
 6622: 
 6623: sub get_todo_count {
 6624:     my ($scanlines,$scan_data)=@_;
 6625:     my $count=0;
 6626:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6627: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6628: 	if ($line=~/^[\s\cz]*$/) { next; }
 6629: 	$count++;
 6630:     }
 6631:     return $count;
 6632: }
 6633: 
 6634: =pod
 6635: 
 6636: =item scantron_put_line
 6637: 
 6638:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6639:     data file.
 6640: 
 6641:  Arguments:
 6642:     $scanlines - hash ref that looks like the first return value from
 6643:                  &scantron_getfile()
 6644:     $scan_data - hash ref that looks like the second return value from
 6645:                  &scantron_getfile()
 6646:     $i         - line number to update
 6647:     $newline   - contents of the updated scanline
 6648:     $skip      - if true make the line for skipping and update the
 6649:                  'skipped' file
 6650: 
 6651: =cut
 6652: 
 6653: sub scantron_put_line {
 6654:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6655:     if ($skip) {
 6656: 	$scanlines->{'skipped'}[$i]=$newline;
 6657: 	&start_skipping($scan_data,$i);
 6658: 	return;
 6659:     }
 6660:     $scanlines->{'corrected'}[$i]=$newline;
 6661: }
 6662: 
 6663: =pod
 6664: 
 6665: =item scantron_clear_skip
 6666: 
 6667:    Remove a line from the 'skipped' file
 6668: 
 6669:  Arguments:
 6670:     $scanlines - hash ref that looks like the first return value from
 6671:                  &scantron_getfile()
 6672:     $scan_data - hash ref that looks like the second return value from
 6673:                  &scantron_getfile()
 6674:     $i         - line number to update
 6675: 
 6676: =cut
 6677: 
 6678: sub scantron_clear_skip {
 6679:     my ($scanlines,$scan_data,$i)=@_;
 6680:     if (exists($scanlines->{'skipped'}[$i])) {
 6681: 	undef($scanlines->{'skipped'}[$i]);
 6682: 	return 1;
 6683:     }
 6684:     return 0;
 6685: }
 6686: 
 6687: =pod
 6688: 
 6689: =item scantron_filter_not_exam
 6690: 
 6691:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6692:    filter out resources that are not marked as 'exam' mode
 6693: 
 6694: =cut
 6695: 
 6696: sub scantron_filter_not_exam {
 6697:     my ($curres)=@_;
 6698:     
 6699:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6700: 	# if the user has asked to not have either hidden
 6701: 	# or 'randomout' controlled resources to be graded
 6702: 	# don't include them
 6703: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6704: 	    && $curres->randomout) {
 6705: 	    return 0;
 6706: 	}
 6707: 	return 1;
 6708:     }
 6709:     return 0;
 6710: }
 6711: 
 6712: =pod
 6713: 
 6714: =item scantron_validate_sequence
 6715: 
 6716:     Validates the selected sequence, checking for resource that are
 6717:     not set to exam mode.
 6718: 
 6719: =cut
 6720: 
 6721: sub scantron_validate_sequence {
 6722:     my ($r,$currentphase) = @_;
 6723: 
 6724:     my $navmap=Apache::lonnavmaps::navmap->new();
 6725:     unless (ref($navmap)) {
 6726:         $r->print(&navmap_errormsg());
 6727:         return (1,$currentphase);
 6728:     }
 6729:     my (undef,undef,$sequence)=
 6730: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6731: 
 6732:     my $map=$navmap->getResourceByUrl($sequence);
 6733: 
 6734:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6735:                                     value="ignore" />');
 6736:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6737: 	my @resources=
 6738: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6739: 	if (@resources) {
 6740: 	    $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>");
 6741: 	    return (1,$currentphase);
 6742: 	}
 6743:     }
 6744: 
 6745:     return (0,$currentphase+1);
 6746: }
 6747: 
 6748: 
 6749: 
 6750: sub scantron_validate_ID {
 6751:     my ($r,$currentphase) = @_;
 6752:     
 6753:     #get student info
 6754:     my $classlist=&Apache::loncoursedata::get_classlist();
 6755:     my %idmap=&username_to_idmap($classlist);
 6756: 
 6757:     #get scantron line setup
 6758:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6759:     my ($scanlines,$scan_data)=&scantron_getfile();
 6760:     
 6761:     my $nav_error;
 6762:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6763:     if ($nav_error) {
 6764:         $r->print(&navmap_errormsg());
 6765:         return(1,$currentphase);
 6766:     }
 6767: 
 6768:     my %found=('ids'=>{},'usernames'=>{});
 6769:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6770: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6771: 	if ($line=~/^[\s\cz]*$/) { next; }
 6772: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6773: 						 $scan_data);
 6774: 	my $id=$$scan_record{'scantron.ID'};
 6775: 	my $found;
 6776: 	foreach my $checkid (keys(%idmap)) {
 6777: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6778: 	}
 6779: 	if ($found) {
 6780: 	    my $username=$idmap{$found};
 6781: 	    if ($found{'ids'}{$found}) {
 6782: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6783: 					 $line,'duplicateID',$found);
 6784: 		return(1,$currentphase);
 6785: 	    } elsif ($found{'usernames'}{$username}) {
 6786: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6787: 					 $line,'duplicateID',$username);
 6788: 		return(1,$currentphase);
 6789: 	    }
 6790: 	    #FIXME store away line we previously saw the ID on to use above
 6791: 	    $found{'ids'}{$found}++;
 6792: 	    $found{'usernames'}{$username}++;
 6793: 	} else {
 6794: 	    if ($id =~ /^\s*$/) {
 6795: 		my $username=&scan_data($scan_data,"$i.user");
 6796: 		if (defined($username) && $found{'usernames'}{$username}) {
 6797: 		    &scantron_get_correction($r,$i,$scan_record,
 6798: 					     \%scantron_config,
 6799: 					     $line,'duplicateID',$username);
 6800: 		    return(1,$currentphase);
 6801: 		} elsif (!defined($username)) {
 6802: 		    &scantron_get_correction($r,$i,$scan_record,
 6803: 					     \%scantron_config,
 6804: 					     $line,'incorrectID');
 6805: 		    return(1,$currentphase);
 6806: 		}
 6807: 		$found{'usernames'}{$username}++;
 6808: 	    } else {
 6809: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6810: 					 $line,'incorrectID');
 6811: 		return(1,$currentphase);
 6812: 	    }
 6813: 	}
 6814:     }
 6815: 
 6816:     return (0,$currentphase+1);
 6817: }
 6818: 
 6819: 
 6820: sub scantron_get_correction {
 6821:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6822: #FIXME in the case of a duplicated ID the previous line, probably need
 6823: #to show both the current line and the previous one and allow skipping
 6824: #the previous one or the current one
 6825: 
 6826:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6827: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6828: 			    " for PaperID <tt>[_1]</tt>",
 6829: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6830:     } else {
 6831: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6832: 			    " in scanline [_1] <pre>[_2]</pre>",
 6833: 			    $i,$line)."</p> \n");
 6834:     }
 6835:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6836: 			  "The name on the paper is [_2],[_3]",
 6837: 			  $$scan_record{'scantron.ID'},
 6838: 			  $$scan_record{'scantron.LastName'},
 6839: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6840: 
 6841:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6842:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6843:                            # Array populated for doublebubble or
 6844:     my @lines_to_correct;  # missingbubble errors to build javascript
 6845:                            # to validate radio button checking   
 6846: 
 6847:     if ($error =~ /ID$/) {
 6848: 	if ($error eq 'incorrectID') {
 6849: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6850: 		      "</p>\n");
 6851: 	} elsif ($error eq 'duplicateID') {
 6852: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6853: 	}
 6854: 	$r->print($message);
 6855: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6856: 	$r->print("\n<ul><li> ");
 6857: 	#FIXME it would be nice if this sent back the user ID and
 6858: 	#could do partial userID matches
 6859: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6860: 				       'scantron_username','scantron_domain'));
 6861: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6862: 	$r->print("\n@".
 6863: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6864: 
 6865: 	$r->print('</li>');
 6866:     } elsif ($error =~ /CODE$/) {
 6867: 	if ($error eq 'incorrectCODE') {
 6868: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6869: 	} elsif ($error eq 'duplicateCODE') {
 6870: 	    $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");
 6871: 	}
 6872: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6873: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6874: 	$r->print($message);
 6875: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6876: 	$r->print("\n<br /> ");
 6877: 	my $i=0;
 6878: 	if ($error eq 'incorrectCODE' 
 6879: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6880: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6881: 	    if ($closest > 0) {
 6882: 		foreach my $testcode (@{$closest}) {
 6883: 		    my $checked='';
 6884: 		    if (!$i) { $checked=' checked="checked"'; }
 6885: 		    $r->print("
 6886:    <label>
 6887:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6888:        ".&mt("Use the similar CODE [_1] instead.",
 6889: 	    "<b><tt>".$testcode."</tt></b>")."
 6890:     </label>
 6891:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6892: 		    $r->print("\n<br />");
 6893: 		    $i++;
 6894: 		}
 6895: 	    }
 6896: 	}
 6897: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6898: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6899: 	    $r->print("
 6900:     <label>
 6901:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6902:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6903: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6904:     </label>");
 6905: 	    $r->print("\n<br />");
 6906: 	}
 6907: 
 6908: 	$r->print(<<ENDSCRIPT);
 6909: <script type="text/javascript">
 6910: function change_radio(field) {
 6911:     var slct=document.scantronupload.scantron_CODE_resolution;
 6912:     var i;
 6913:     for (i=0;i<slct.length;i++) {
 6914:         if (slct[i].value==field) { slct[i].checked=true; }
 6915:     }
 6916: }
 6917: </script>
 6918: ENDSCRIPT
 6919: 	my $href="/adm/pickcode?".
 6920: 	   "form=".&escape("scantronupload").
 6921: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6922: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6923: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6924: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6925: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6926: 	    $r->print("
 6927:     <label>
 6928:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6929:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6930: 	     "<a target='_blank' href='$href'>","</a>")."
 6931:     </label> 
 6932:     ".&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\')" />'));
 6933: 	    $r->print("\n<br />");
 6934: 	}
 6935: 	$r->print("
 6936:     <label>
 6937:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6938:        ".&mt("Use [_1] as the CODE.",
 6939: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6940: 	$r->print("\n<br /><br />");
 6941:     } elsif ($error eq 'doublebubble') {
 6942: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6943: 
 6944: 	# The form field scantron_questions is acutally a list of line numbers.
 6945: 	# represented by this form so:
 6946: 
 6947: 	my $line_list = &questions_to_line_list($arg);
 6948: 
 6949: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6950: 		  $line_list.'" />');
 6951: 	$r->print($message);
 6952: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6953: 	foreach my $question (@{$arg}) {
 6954: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6955:                                                    $scan_record, $error);
 6956:             push(@lines_to_correct,@linenums);
 6957: 	}
 6958:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6959:     } elsif ($error eq 'missingbubble') {
 6960: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6961: 	$r->print($message);
 6962: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6963: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6964: 
 6965: 	# The form field scantron_questions is actually a list of line numbers not
 6966: 	# a list of question numbers. Therefore:
 6967: 	#
 6968: 	
 6969: 	my $line_list = &questions_to_line_list($arg);
 6970: 
 6971: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6972: 		  $line_list.'" />');
 6973: 	foreach my $question (@{$arg}) {
 6974: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6975:                                                    $scan_record, $error);
 6976:             push(@lines_to_correct,@linenums);
 6977: 	}
 6978:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6979:     } else {
 6980: 	$r->print("\n<ul>");
 6981:     }
 6982:     $r->print("\n</li></ul>");
 6983: }
 6984: 
 6985: sub verify_bubbles_checked {
 6986:     my (@ansnums) = @_;
 6987:     my $ansnumstr = join('","',@ansnums);
 6988:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6989:     my $output = (<<ENDSCRIPT);
 6990: <script type="text/javascript">
 6991: function verify_bubble_radio(form) {
 6992:     var ansnumArray = new Array ("$ansnumstr");
 6993:     var need_bubble_count = 0;
 6994:     for (var i=0; i<ansnumArray.length; i++) {
 6995:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6996:             var bubble_picked = 0; 
 6997:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6998:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6999:                     bubble_picked = 1;
 7000:                 }
 7001:             }
 7002:             if (bubble_picked == 0) {
 7003:                 need_bubble_count ++;
 7004:             }
 7005:         }
 7006:     }
 7007:     if (need_bubble_count) {
 7008:         alert("$warning");
 7009:         return;
 7010:     }
 7011:     form.submit(); 
 7012: }
 7013: </script>
 7014: ENDSCRIPT
 7015:     return $output;
 7016: }
 7017: 
 7018: =pod
 7019: 
 7020: =item  questions_to_line_list
 7021: 
 7022: Converts a list of questions into a string of comma separated
 7023: line numbers in the answer sheet used by the questions.  This is
 7024: used to fill in the scantron_questions form field.
 7025: 
 7026:   Arguments:
 7027:      questions    - Reference to an array of questions.
 7028: 
 7029: =cut
 7030: 
 7031: 
 7032: sub questions_to_line_list {
 7033:     my ($questions) = @_;
 7034:     my @lines;
 7035: 
 7036:     foreach my $item (@{$questions}) {
 7037:         my $question = $item;
 7038:         my ($first,$count,$last);
 7039:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7040:             $question = $1;
 7041:             my $subquestion = $2;
 7042:             $first = $first_bubble_line{$question-1} + 1;
 7043:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7044:             my $subcount = 1;
 7045:             while ($subcount<$subquestion) {
 7046:                 $first += $subans[$subcount-1];
 7047:                 $subcount ++;
 7048:             }
 7049:             $count = $subans[$subquestion-1];
 7050:         } else {
 7051: 	    $first   = $first_bubble_line{$question-1} + 1;
 7052: 	    $count   = $bubble_lines_per_response{$question-1};
 7053:         }
 7054:         $last = $first+$count-1;
 7055:         push(@lines, ($first..$last));
 7056:     }
 7057:     return join(',', @lines);
 7058: }
 7059: 
 7060: =pod 
 7061: 
 7062: =item prompt_for_corrections
 7063: 
 7064: Prompts for a potentially multiline correction to the
 7065: user's bubbling (factors out common code from scantron_get_correction
 7066: for multi and missing bubble cases).
 7067: 
 7068:  Arguments:
 7069:    $r           - Apache request object.
 7070:    $question    - The question number to prompt for.
 7071:    $scan_config - The scantron file configuration hash.
 7072:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7073:    $error       - Type of error
 7074: 
 7075:  Implicit inputs:
 7076:    %bubble_lines_per_response   - Starting line numbers for each question.
 7077:                                   Numbered from 0 (but question numbers are from
 7078:                                   1.
 7079:    %first_bubble_line           - Starting bubble line for each question.
 7080:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7081:                                   type problems render as separate sub-questions, 
 7082:                                   in exam mode. This hash contains a 
 7083:                                   comma-separated list of the lines per 
 7084:                                   sub-question.
 7085:    %responsetype_per_response   - essayresponse, formularesponse,
 7086:                                   stringresponse, imageresponse, reactionresponse,
 7087:                                   and organicresponse type problem parts can have
 7088:                                   multiple lines per response if the weight
 7089:                                   assigned exceeds 10.  In this case, only
 7090:                                   one bubble per line is permitted, but more 
 7091:                                   than one line might contain bubbles, e.g.
 7092:                                   bubbling of: line 1 - J, line 2 - J, 
 7093:                                   line 3 - B would assign 22 points.  
 7094: 
 7095: =cut
 7096: 
 7097: sub prompt_for_corrections {
 7098:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7099:     my ($current_line,$lines);
 7100:     my @linenums;
 7101:     my $questionnum = $question;
 7102:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7103:         $question = $1;
 7104:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7105:         my $subquestion = $2;
 7106:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7107:         my $subcount = 1;
 7108:         while ($subcount<$subquestion) {
 7109:             $current_line += $subans[$subcount-1];
 7110:             $subcount ++;
 7111:         }
 7112:         $lines = $subans[$subquestion-1];
 7113:     } else {
 7114:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7115:         $lines        = $bubble_lines_per_response{$question-1};
 7116:     }
 7117:     if ($lines > 1) {
 7118:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7119:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7120:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7121:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7122:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7123:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7124:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7125:             $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 />');
 7126:         } else {
 7127:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7128:         }
 7129:     }
 7130:     for (my $i =0; $i < $lines; $i++) {
 7131:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7132: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7133: 	        		  $questionnum,$error,split('', $selected));
 7134:         push(@linenums,$current_line);
 7135: 	$current_line++;
 7136:     }
 7137:     if ($lines > 1) {
 7138: 	$r->print("<hr /><br />");
 7139:     }
 7140:     return @linenums;
 7141: }
 7142: 
 7143: =pod
 7144: 
 7145: =item scantron_bubble_selector
 7146:   
 7147:    Generates the html radiobuttons to correct a single bubble line
 7148:    possibly showing the existing the selected bubbles if known
 7149: 
 7150:  Arguments:
 7151:     $r           - Apache request object
 7152:     $scan_config - hash from &get_scantron_config()
 7153:     $line        - Number of the line being displayed.
 7154:     $questionnum - Question number (may include subquestion)
 7155:     $error       - Type of error.
 7156:     @selected    - Array of bubbles picked on this line.
 7157: 
 7158: =cut
 7159: 
 7160: sub scantron_bubble_selector {
 7161:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7162:     my $max=$$scan_config{'Qlength'};
 7163: 
 7164:     my $scmode=$$scan_config{'Qon'};
 7165:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7166: 
 7167:     my @alphabet=('A'..'Z');
 7168:     $r->print(&Apache::loncommon::start_data_table().
 7169:               &Apache::loncommon::start_data_table_row());
 7170:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7171:     for (my $i=0;$i<$max+1;$i++) {
 7172: 	$r->print("\n".'<td align="center">');
 7173: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7174: 	else { $r->print('&nbsp;'); }
 7175: 	$r->print('</td>');
 7176:     }
 7177:     $r->print(&Apache::loncommon::end_data_table_row().
 7178:               &Apache::loncommon::start_data_table_row());
 7179:     for (my $i=0;$i<$max;$i++) {
 7180: 	$r->print("\n".
 7181: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7182: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7183:     }
 7184:     my $nobub_checked = ' ';
 7185:     if ($error eq 'missingbubble') {
 7186:         $nobub_checked = ' checked = "checked" ';
 7187:     }
 7188:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7189: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7190:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7191:               $line.'" value="'.$questionnum.'" /></td>');
 7192:     $r->print(&Apache::loncommon::end_data_table_row().
 7193:               &Apache::loncommon::end_data_table());
 7194: }
 7195: 
 7196: =pod
 7197: 
 7198: =item num_matches
 7199: 
 7200:    Counts the number of characters that are the same between the two arguments.
 7201: 
 7202:  Arguments:
 7203:    $orig - CODE from the scanline
 7204:    $code - CODE to match against
 7205: 
 7206:  Returns:
 7207:    $count - integer count of the number of same characters between the
 7208:             two arguments
 7209: 
 7210: =cut
 7211: 
 7212: sub num_matches {
 7213:     my ($orig,$code) = @_;
 7214:     my @code=split(//,$code);
 7215:     my @orig=split(//,$orig);
 7216:     my $same=0;
 7217:     for (my $i=0;$i<scalar(@code);$i++) {
 7218: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7219:     }
 7220:     return $same;
 7221: }
 7222: 
 7223: =pod
 7224: 
 7225: =item scantron_get_closely_matching_CODEs
 7226: 
 7227:    Cycles through all CODEs and finds the set that has the greatest
 7228:    number of same characters as the provided CODE
 7229: 
 7230:  Arguments:
 7231:    $allcodes - hash ref returned by &get_codes()
 7232:    $CODE     - CODE from the current scanline
 7233: 
 7234:  Returns:
 7235:    2 element list
 7236:     - first elements is number of how closely matching the best fit is 
 7237:       (5 means best set has 5 matching characters)
 7238:     - second element is an arrary ref containing the set of valid CODEs
 7239:       that best fit the passed in CODE
 7240: 
 7241: =cut
 7242: 
 7243: sub scantron_get_closely_matching_CODEs {
 7244:     my ($allcodes,$CODE)=@_;
 7245:     my @CODEs;
 7246:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7247: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7248:     }
 7249: 
 7250:     return ($#CODEs,$CODEs[-1]);
 7251: }
 7252: 
 7253: =pod
 7254: 
 7255: =item get_codes
 7256: 
 7257:    Builds a hash which has keys of all of the valid CODEs from the selected
 7258:    set of remembered CODEs.
 7259: 
 7260:  Arguments:
 7261:   $old_name - name of the set of remembered CODEs
 7262:   $cdom     - domain of the course
 7263:   $cnum     - internal course name
 7264: 
 7265:  Returns:
 7266:   %allcodes - keys are the valid CODEs, values are all 1
 7267: 
 7268: =cut
 7269: 
 7270: sub get_codes {
 7271:     my ($old_name, $cdom, $cnum) = @_;
 7272:     if (!$old_name) {
 7273: 	$old_name=$env{'form.scantron_CODElist'};
 7274:     }
 7275:     if (!$cdom) {
 7276: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7277:     }
 7278:     if (!$cnum) {
 7279: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7280:     }
 7281:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7282: 				    $cdom,$cnum);
 7283:     my %allcodes;
 7284:     if ($result{"type\0$old_name"} eq 'number') {
 7285: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7286:     } else {
 7287: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7288:     }
 7289:     return %allcodes;
 7290: }
 7291: 
 7292: =pod
 7293: 
 7294: =item scantron_validate_CODE
 7295: 
 7296:    Validates all scanlines in the selected file to not have any
 7297:    invalid or underspecified CODEs and that none of the codes are
 7298:    duplicated if this was requested.
 7299: 
 7300: =cut
 7301: 
 7302: sub scantron_validate_CODE {
 7303:     my ($r,$currentphase) = @_;
 7304:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7305:     if ($scantron_config{'CODElocation'} &&
 7306: 	$scantron_config{'CODEstart'} &&
 7307: 	$scantron_config{'CODElength'}) {
 7308: 	if (!defined($env{'form.scantron_CODElist'})) {
 7309: 	    &FIXME_blow_up()
 7310: 	}
 7311:     } else {
 7312: 	return (0,$currentphase+1);
 7313:     }
 7314:     
 7315:     my %usedCODEs;
 7316: 
 7317:     my %allcodes=&get_codes();
 7318: 
 7319:     my $nav_error;
 7320:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7321:     if ($nav_error) {
 7322:         $r->print(&navmap_errormsg());
 7323:         return(1,$currentphase);
 7324:     }
 7325: 
 7326:     my ($scanlines,$scan_data)=&scantron_getfile();
 7327:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7328: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7329: 	if ($line=~/^[\s\cz]*$/) { next; }
 7330: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7331: 						 $scan_data);
 7332: 	my $CODE=$$scan_record{'scantron.CODE'};
 7333: 	my $error=0;
 7334: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7335: 	    &scantron_get_correction($r,$i,$scan_record,
 7336: 				     \%scantron_config,
 7337: 				     $line,'incorrectCODE',\%allcodes);
 7338: 	    return(1,$currentphase);
 7339: 	}
 7340: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7341: 	    && !$$scan_record{'scantron.useCODE'}) {
 7342: 	    &scantron_get_correction($r,$i,$scan_record,
 7343: 				     \%scantron_config,
 7344: 				     $line,'incorrectCODE',\%allcodes);
 7345: 	    return(1,$currentphase);
 7346: 	}
 7347: 	if (exists($usedCODEs{$CODE}) 
 7348: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7349: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7350: 	    &scantron_get_correction($r,$i,$scan_record,
 7351: 				     \%scantron_config,
 7352: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7353: 	    return(1,$currentphase);
 7354: 	}
 7355: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7356:     }
 7357:     return (0,$currentphase+1);
 7358: }
 7359: 
 7360: =pod
 7361: 
 7362: =item scantron_validate_doublebubble
 7363: 
 7364:    Validates all scanlines in the selected file to not have any
 7365:    bubble lines with multiple bubbles marked.
 7366: 
 7367: =cut
 7368: 
 7369: sub scantron_validate_doublebubble {
 7370:     my ($r,$currentphase) = @_;
 7371:     #get student info
 7372:     my $classlist=&Apache::loncoursedata::get_classlist();
 7373:     my %idmap=&username_to_idmap($classlist);
 7374: 
 7375:     #get scantron line setup
 7376:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7377:     my ($scanlines,$scan_data)=&scantron_getfile();
 7378:     my $nav_error;
 7379:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7380:     if ($nav_error) {
 7381:         $r->print(&navmap_errormsg());
 7382:         return(1,$currentphase);
 7383:     }
 7384: 
 7385:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7386: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7387: 	if ($line=~/^[\s\cz]*$/) { next; }
 7388: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7389: 						 $scan_data);
 7390: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7391: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7392: 				 'doublebubble',
 7393: 				 $$scan_record{'scantron.doubleerror'});
 7394:     	return (1,$currentphase);
 7395:     }
 7396:     return (0,$currentphase+1);
 7397: }
 7398: 
 7399: 
 7400: sub scantron_get_maxbubble {
 7401:     my ($nav_error) = @_;
 7402: 
 7403:     if (defined($env{'form.scantron_maxbubble'}) &&
 7404: 	$env{'form.scantron_maxbubble'}) {
 7405: 	&restore_bubble_lines();
 7406: 	return $env{'form.scantron_maxbubble'};
 7407:     }
 7408: 
 7409:     my (undef, undef, $sequence) =
 7410: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7411: 
 7412:     my $navmap=Apache::lonnavmaps::navmap->new();
 7413:     unless (ref($navmap)) {
 7414:         if (ref($nav_error)) {
 7415:             $$nav_error = 1;
 7416:         }
 7417:         return;
 7418:     }
 7419:     my $map=$navmap->getResourceByUrl($sequence);
 7420:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7421: 
 7422:     &Apache::lonxml::clear_problem_counter();
 7423: 
 7424:     my $uname       = $env{'user.name'};
 7425:     my $udom        = $env{'user.domain'};
 7426:     my $cid         = $env{'request.course.id'};
 7427:     my $total_lines = 0;
 7428:     %bubble_lines_per_response = ();
 7429:     %first_bubble_line         = ();
 7430:     %subdivided_bubble_lines   = ();
 7431:     %responsetype_per_response = ();
 7432: 
 7433:     my $response_number = 0;
 7434:     my $bubble_line     = 0;
 7435:     foreach my $resource (@resources) {
 7436:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7437:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7438: 	    foreach my $part_id (@{$parts}) {
 7439:                 my $lines;
 7440: 
 7441: 	        # TODO - make this a persistent hash not an array.
 7442: 
 7443:                 # optionresponse, matchresponse and rankresponse type items 
 7444:                 # render as separate sub-questions in exam mode.
 7445:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7446:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7447:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7448:                     my ($numbub,$numshown);
 7449:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7450:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7451:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7452:                         }
 7453:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7454:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7455:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7456:                         }
 7457:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7458:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7459:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7460:                         }
 7461:                     }
 7462:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7463:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7464:                     }
 7465:                     my $bubbles_per_line = 10;
 7466:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7467:                     if (($numbub % $bubbles_per_line) != 0) {
 7468:                         $inner_bubble_lines++;
 7469:                     }
 7470:                     for (my $i=0; $i<$numshown; $i++) {
 7471:                         $subdivided_bubble_lines{$response_number} .= 
 7472:                             $inner_bubble_lines.',';
 7473:                     }
 7474:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7475:                     $lines = $numshown * $inner_bubble_lines;
 7476:                 } else {
 7477:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7478:                 } 
 7479: 
 7480:                 $first_bubble_line{$response_number} = $bubble_line;
 7481: 	        $bubble_lines_per_response{$response_number} = $lines;
 7482:                 $responsetype_per_response{$response_number} = 
 7483:                     $analysis->{$part_id.'.type'};
 7484: 	        $response_number++;
 7485: 
 7486: 	        $bubble_line +=  $lines;
 7487: 	        $total_lines +=  $lines;
 7488: 	    }
 7489:         }
 7490:     }
 7491:     &Apache::lonnet::delenv('scantron.');
 7492: 
 7493:     &save_bubble_lines();
 7494:     $env{'form.scantron_maxbubble'} =
 7495: 	$total_lines;
 7496:     return $env{'form.scantron_maxbubble'};
 7497: }
 7498: 
 7499: sub scantron_validate_missingbubbles {
 7500:     my ($r,$currentphase) = @_;
 7501:     #get student info
 7502:     my $classlist=&Apache::loncoursedata::get_classlist();
 7503:     my %idmap=&username_to_idmap($classlist);
 7504: 
 7505:     #get scantron line setup
 7506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7507:     my ($scanlines,$scan_data)=&scantron_getfile();
 7508:     my $nav_error;
 7509:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7510:     if ($nav_error) {
 7511:         return(1,$currentphase);
 7512:     }
 7513:     if (!$max_bubble) { $max_bubble=2**31; }
 7514:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7515: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7516: 	if ($line=~/^[\s\cz]*$/) { next; }
 7517: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7518: 						 $scan_data);
 7519: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7520: 	my @to_correct;
 7521: 	
 7522: 	# Probably here's where the error is...
 7523: 
 7524: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7525:             my $lastbubble;
 7526:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7527:                my $question = $1;
 7528:                my $subquestion = $2;
 7529:                if (!defined($first_bubble_line{$question -1})) { next; }
 7530:                my $first = $first_bubble_line{$question-1};
 7531:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7532:                my $subcount = 1;
 7533:                while ($subcount<$subquestion) {
 7534:                    $first += $subans[$subcount-1];
 7535:                    $subcount ++;
 7536:                }
 7537:                my $count = $subans[$subquestion-1];
 7538:                $lastbubble = $first + $count;
 7539:             } else {
 7540:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7541:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7542:             }
 7543:             if ($lastbubble > $max_bubble) { next; }
 7544: 	    push(@to_correct,$missing);
 7545: 	}
 7546: 	if (@to_correct) {
 7547: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7548: 				     $line,'missingbubble',\@to_correct);
 7549: 	    return (1,$currentphase);
 7550: 	}
 7551: 
 7552:     }
 7553:     return (0,$currentphase+1);
 7554: }
 7555: 
 7556: 
 7557: sub scantron_process_students {
 7558:     my ($r) = @_;
 7559: 
 7560:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7561:     my ($symb)=&get_symb($r);
 7562:     if (!$symb) {
 7563: 	return '';
 7564:     }
 7565:     my $default_form_data=&defaultFormData($symb);
 7566: 
 7567:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7568:     my ($scanlines,$scan_data)=&scantron_getfile();
 7569:     my $classlist=&Apache::loncoursedata::get_classlist();
 7570:     my %idmap=&username_to_idmap($classlist);
 7571:     my $navmap=Apache::lonnavmaps::navmap->new();
 7572:     unless (ref($navmap)) {
 7573:         $r->print(&navmap_errormsg());
 7574:         return '';
 7575:     }  
 7576:     my $map=$navmap->getResourceByUrl($sequence);
 7577:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7578:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7579:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7580:                             \%grader_randomlists_by_symb);
 7581:     my $resource_error;
 7582:     foreach my $resource (@resources) {
 7583:         my $ressymb;
 7584:         if (ref($resource)) {
 7585:             $ressymb = $resource->symb();
 7586:         } else {
 7587:             $resource_error = 1;
 7588:             last;
 7589:         }
 7590:         my ($analysis,$parts) =
 7591:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7592:                                       $env{'user.name'},$env{'user.domain'},1);
 7593:         $grader_partids_by_symb{$ressymb} = $parts;
 7594:         if (ref($analysis) eq 'HASH') {
 7595:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7596:                 $grader_randomlists_by_symb{$ressymb} = 
 7597:                     $analysis->{'parts_withrandomlist'};
 7598:             }
 7599:         }
 7600:     }
 7601:     if ($resource_error) {
 7602:         $r->print(&navmap_errormsg());
 7603:         return '';
 7604:     }
 7605: 
 7606:     my ($uname,$udom);
 7607:     my $result= <<SCANTRONFORM;
 7608: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7609:   <input type="hidden" name="command" value="scantron_configphase" />
 7610:   $default_form_data
 7611: SCANTRONFORM
 7612:     $r->print($result);
 7613: 
 7614:     my @delayqueue;
 7615:     my (%completedstudents,%scandata);
 7616:     
 7617:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7618:     my $count=&get_todo_count($scanlines,$scan_data);
 7619:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7620:  				    'Bubblesheet Progress',$count,
 7621: 				    'inline',undef,'scantronupload');
 7622:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7623: 					  'Processing first student');
 7624:     $r->print('<br />');
 7625:     my $start=&Time::HiRes::time();
 7626:     my $i=-1;
 7627:     my $started;
 7628: 
 7629:     my $nav_error;
 7630:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7631:     if ($nav_error) {
 7632:         $r->print(&navmap_errormsg());
 7633:         return '';
 7634:     }
 7635: 
 7636:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7637:     # the user and return.
 7638: 
 7639:     if ($ssi_error) {
 7640: 	$r->print("</form>");
 7641: 	&ssi_print_error($r);
 7642: 	$r->print(&show_grading_menu_form($symb));
 7643:         &Apache::lonnet::remove_lock($lock);
 7644: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7645:     }
 7646: 
 7647:     my %lettdig = &letter_to_digits();
 7648:     my $numletts = scalar(keys(%lettdig));
 7649: 
 7650:     while ($i<$scanlines->{'count'}) {
 7651:  	($uname,$udom)=('','');
 7652:  	$i++;
 7653:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7654:  	if ($line=~/^[\s\cz]*$/) { next; }
 7655: 	if ($started) {
 7656: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7657: 						     'last student');
 7658: 	}
 7659: 	$started=1;
 7660:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7661:  						 $scan_data);
 7662:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7663:  					      \%idmap,$i)) {
 7664:   	    &scantron_add_delay(\@delayqueue,$line,
 7665:  				'Unable to find a student that matches',1);
 7666:  	    next;
 7667:   	}
 7668:  	if (exists $completedstudents{$uname}) {
 7669:  	    &scantron_add_delay(\@delayqueue,$line,
 7670:  				'Student '.$uname.' has multiple sheets',2);
 7671:  	    next;
 7672:  	}
 7673:   	($uname,$udom)=split(/:/,$uname);
 7674: 
 7675:         my (%partids_by_symb,$res_error);
 7676:         foreach my $resource (@resources) {
 7677:             my $ressymb;
 7678:             if (ref($resource)) {
 7679:                 $ressymb = $resource->symb();
 7680:             } else {
 7681:                 $res_error = 1;
 7682:                 last;
 7683:             }
 7684:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7685:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7686:                 my ($analysis,$parts) =
 7687:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7688:                 $partids_by_symb{$ressymb} = $parts;
 7689:             } else {
 7690:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7691:             }
 7692:         }
 7693: 
 7694:         if ($res_error) {
 7695:             &scantron_add_delay(\@delayqueue,$line,
 7696:                                 'An error occurred while grading student '.$uname,2);
 7697:             next;
 7698:         }
 7699: 
 7700: 	&Apache::lonxml::clear_problem_counter();
 7701:   	&Apache::lonnet::appenv($scan_record);
 7702: 
 7703: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7704: 	    &scantron_putfile($scanlines,$scan_data);
 7705: 	}
 7706: 	
 7707:         my $scancode;
 7708:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7709:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7710:             $scancode = $scan_record->{'scantron.CODE'};
 7711:         } else {
 7712:             $scancode = '';
 7713:         }
 7714: 
 7715:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7716:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7717:             $ssi_error = 0; # So end of handler error message does not trigger.
 7718:             $r->print("</form>");
 7719:             &ssi_print_error($r);
 7720:             $r->print(&show_grading_menu_form($symb));
 7721:             &Apache::lonnet::remove_lock($lock);
 7722:             return '';      # Why return ''?  Beats me.
 7723:         }
 7724: 
 7725: 	$completedstudents{$uname}={'line'=>$line};
 7726:         if ($env{'form.verifyrecord'}) {
 7727:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7728:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7729:             chomp($studentdata);
 7730:             $studentdata =~ s/\r$//;
 7731:             my $studentrecord = '';
 7732:             my $counter = -1;
 7733:             foreach my $resource (@resources) {
 7734:                 my $ressymb = $resource->symb();
 7735:                 ($counter,my $recording) =
 7736:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7737:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7738:                                              \%scantron_config,\%lettdig,$numletts);
 7739:                 $studentrecord .= $recording;
 7740:             }
 7741:             if ($studentrecord ne $studentdata) {
 7742:                 &Apache::lonxml::clear_problem_counter();
 7743:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7744:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7745:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7746:                     $r->print("</form>");
 7747:                     &ssi_print_error($r);
 7748:                     $r->print(&show_grading_menu_form($symb));
 7749:                     &Apache::lonnet::remove_lock($lock);
 7750:                     delete($completedstudents{$uname});
 7751:                     return '';
 7752:                 }
 7753:                 $counter = -1;
 7754:                 $studentrecord = '';
 7755:                 foreach my $resource (@resources) {
 7756:                     my $ressymb = $resource->symb();
 7757:                     ($counter,my $recording) =
 7758:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7759:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7760:                                                  \%scantron_config,\%lettdig,$numletts);
 7761:                     $studentrecord .= $recording;
 7762:                 }
 7763:                 if ($studentrecord ne $studentdata) {
 7764:                     $r->print('<p><span class="LC_error">');
 7765:                     if ($scancode eq '') {
 7766:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7767:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7768:                     } else {
 7769:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7770:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7771:                     }
 7772:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7773:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7774:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7775:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7776:                               &Apache::loncommon::start_data_table_row().
 7777:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7778:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7779:                               &Apache::loncommon::end_data_table_row().
 7780:                               &Apache::loncommon::start_data_table_row().
 7781:                               '<td>Stored submissions</td>'.
 7782:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7783:                               &Apache::loncommon::end_data_table_row().
 7784:                               &Apache::loncommon::end_data_table().'</p>');
 7785:                 } else {
 7786:                     $r->print('<br /><span class="LC_warning">'.
 7787:                              &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 />'.
 7788:                              &mt("As a consequence, this user's submission history records two tries.").
 7789:                                  '</span><br />');
 7790:                 }
 7791:             }
 7792:         }
 7793:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7794:     } continue {
 7795: 	&Apache::lonxml::clear_problem_counter();
 7796: 	&Apache::lonnet::delenv('scantron.');
 7797:     }
 7798:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7799:     &Apache::lonnet::remove_lock($lock);
 7800: #    my $lasttime = &Time::HiRes::time()-$start;
 7801: #    $r->print("<p>took $lasttime</p>");
 7802: 
 7803:     $r->print("</form>");
 7804:     $r->print(&show_grading_menu_form($symb));
 7805:     return '';
 7806: }
 7807: 
 7808: sub graders_resources_pass {
 7809:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7810:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7811:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7812:         foreach my $resource (@{$resources}) {
 7813:             my $ressymb = $resource->symb();
 7814:             my ($analysis,$parts) =
 7815:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7816:                                           $env{'user.name'},$env{'user.domain'},1);
 7817:             $grader_partids_by_symb->{$ressymb} = $parts;
 7818:             if (ref($analysis) eq 'HASH') {
 7819:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7820:                     $grader_randomlists_by_symb->{$ressymb} =
 7821:                         $analysis->{'parts_withrandomlist'};
 7822:                 }
 7823:             }
 7824:         }
 7825:     }
 7826:     return;
 7827: }
 7828: 
 7829: sub grade_student_bubbles {
 7830:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7831:     if (ref($resources) eq 'ARRAY') {
 7832:         my $count = 0;
 7833:         foreach my $resource (@{$resources}) {
 7834:             my $ressymb = $resource->symb();
 7835:             my %form = ('submitted'      => 'scantron',
 7836:                         'grade_target'   => 'grade',
 7837:                         'grade_username' => $uname,
 7838:                         'grade_domain'   => $udom,
 7839:                         'grade_courseid' => $env{'request.course.id'},
 7840:                         'grade_symb'     => $ressymb,
 7841:                         'CODE'           => $scancode
 7842:                        );
 7843:             if (ref($parts) eq 'HASH') {
 7844:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7845:                     foreach my $part (@{$parts->{$ressymb}}) {
 7846:                         $form{'scantron_questnum_start.'.$part} =
 7847:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7848:                         $count++;
 7849:                     }
 7850:                 }
 7851:             }
 7852:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7853:             return 'ssi_error' if ($ssi_error);
 7854:             last if (&Apache::loncommon::connection_aborted($r));
 7855:         }
 7856:     }
 7857:     return;
 7858: }
 7859: 
 7860: sub scantron_upload_scantron_data {
 7861:     my ($r)=@_;
 7862:     my $dom = $env{'request.role.domain'};
 7863:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7864:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7865:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7866: 							  'domainid',
 7867: 							  'coursename',$dom);
 7868:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7869:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7870:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7871:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7872:     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.");
 7873:     $r->print('
 7874: <script type="text/javascript" language="javascript">
 7875:     function checkUpload(formname) {
 7876: 	if (formname.upfile.value == "") {
 7877: 	    alert("'.$nofile_alert.'");
 7878: 	    return false;
 7879: 	}
 7880:         if (formname.courseid.value == "") {
 7881:             alert("'.$nocourseid_alert.'");
 7882:             return false;
 7883:         }
 7884: 	formname.submit();
 7885:     }
 7886: 
 7887:     function ToSyllabus() {
 7888:         var cdom = '."'$dom'".';
 7889:         var cnum = document.rules.courseid.value;
 7890:         if (cdom == "" || cdom == null) {
 7891:             return;
 7892:         }
 7893:         if (cnum == "" || cnum == null) {
 7894:            return;
 7895:         }
 7896:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7897:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7898:         return;
 7899:     }
 7900: 
 7901: </script>
 7902: 
 7903: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7904: 
 7905: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7906: '.$default_form_data.
 7907:   &Apache::lonhtmlcommon::start_pick_box().
 7908:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7909:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7910:   &Apache::lonhtmlcommon::row_closure().
 7911:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7912:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7913:   &Apache::lonhtmlcommon::row_closure().
 7914:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7915:   '<input name="domainid" type="hidden" />'.$domdesc.
 7916:   &Apache::lonhtmlcommon::row_closure().
 7917:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7918:   '<input type="file" name="upfile" size="50" />'.
 7919:   &Apache::lonhtmlcommon::row_closure(1).
 7920:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7921: 
 7922: <input name="command" value="scantronupload_save" type="hidden" />
 7923: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7924: </form>
 7925: ');
 7926:     return '';
 7927: }
 7928: 
 7929: 
 7930: sub scantron_upload_scantron_data_save {
 7931:     my($r)=@_;
 7932:     my ($symb)=&get_symb($r,1);
 7933:     my $doanotherupload=
 7934: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7935: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7936: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7937: 	'</form>'."\n";
 7938:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7939: 	!&Apache::lonnet::allowed('usc',
 7940: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7941: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7942: 	if ($symb) {
 7943: 	    $r->print(&show_grading_menu_form($symb));
 7944: 	} else {
 7945: 	    $r->print($doanotherupload);
 7946: 	}
 7947: 	return '';
 7948:     }
 7949:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7950:     my $uploadedfile;
 7951:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7952:     if (length($env{'form.upfile'}) < 2) {
 7953:         $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>'));
 7954:     } else {
 7955:         my $result = 
 7956:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7957:                                             $env{'form.courseid'},$env{'form.domainid'});
 7958: 	if ($result =~ m{^/uploaded/}) {
 7959: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7960:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7961: 			  '<span class="LC_filename">'.$result.'</span>'));
 7962:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7963:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7964:                                                        $env{'form.courseid'},$uploadedfile));
 7965: 	} else {
 7966: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7967:                           '<span class="LC_error">','</span>',$result,
 7968: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7969: 	}
 7970:     }
 7971:     if ($symb) {
 7972: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7973:     } else {
 7974: 	$r->print($doanotherupload);
 7975:     }
 7976:     return '';
 7977: }
 7978: 
 7979: sub validate_uploaded_scantron_file {
 7980:     my ($cdom,$cname,$fname) = @_;
 7981:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7982:     my @lines;
 7983:     if ($scanlines ne '-1') {
 7984:         @lines=split("\n",$scanlines,-1);
 7985:     }
 7986:     my $output;
 7987:     if (@lines) {
 7988:         my (%counts,$max_match_format);
 7989:         my ($max_match_count,$max_match_pct) = (0,0);
 7990:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7991:         my %idmap = &username_to_idmap($classlist);
 7992:         foreach my $key (keys(%idmap)) {
 7993:             my $lckey = lc($key);
 7994:             $idmap{$lckey} = $idmap{$key};
 7995:         }
 7996:         my %unique_formats;
 7997:         my @formatlines = &get_scantronformat_file();
 7998:         foreach my $line (@formatlines) {
 7999:             chomp($line);
 8000:             my @config = split(/:/,$line);
 8001:             my $idstart = $config[5];
 8002:             my $idlength = $config[6];
 8003:             if (($idstart ne '') && ($idlength > 0)) {
 8004:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8005:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8006:                 } else {
 8007:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8008:                 }
 8009:             }
 8010:         }
 8011:         foreach my $key (keys(%unique_formats)) {
 8012:             my ($idstart,$idlength) = split(':',$key);
 8013:             %{$counts{$key}} = (
 8014:                                'found'   => 0,
 8015:                                'total'   => 0,
 8016:                               );
 8017:             foreach my $line (@lines) {
 8018:                 next if ($line =~ /^#/);
 8019:                 next if ($line =~ /^[\s\cz]*$/);
 8020:                 my $id = substr($line,$idstart-1,$idlength);
 8021:                 $id = lc($id);
 8022:                 if (exists($idmap{$id})) {
 8023:                     $counts{$key}{'found'} ++;
 8024:                 }
 8025:                 $counts{$key}{'total'} ++;
 8026:             }
 8027:             if ($counts{$key}{'total'}) {
 8028:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8029:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8030:                     $max_match_pct = $percent_match;
 8031:                     $max_match_format = $key;
 8032:                     $max_match_count = $counts{$key}{'total'};
 8033:                 }
 8034:             }
 8035:         }
 8036:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8037:             my $format_descs;
 8038:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8039:             for (my $i=0; $i<$numwithformat; $i++) {
 8040:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8041:                 if ($i<$numwithformat-2) {
 8042:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8043:                 } elsif ($i==$numwithformat-2) {
 8044:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8045:                 } elsif ($i==$numwithformat-1) {
 8046:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8047:                 }
 8048:             }
 8049:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8050:             $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).
 8051:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8052:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8053:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8054:                                   '<i>'.$cdom.'</i>').'</li>'.
 8055:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8056:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8057:                        '</ul>';
 8058:         }
 8059:     } else {
 8060:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8061:     }
 8062:     return $output;
 8063: }
 8064: 
 8065: sub valid_file {
 8066:     my ($requested_file)=@_;
 8067:     foreach my $filename (sort(&scantron_filenames())) {
 8068: 	if ($requested_file eq $filename) { return 1; }
 8069:     }
 8070:     return 0;
 8071: }
 8072: 
 8073: sub scantron_download_scantron_data {
 8074:     my ($r)=@_;
 8075:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8076:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8077:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8078:     my $file=$env{'form.scantron_selectfile'};
 8079:     if (! &valid_file($file)) {
 8080: 	$r->print('
 8081: 	<p>
 8082: 	    '.&mt('The requested file name was invalid.').'
 8083:         </p>
 8084: ');
 8085: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8086: 	return;
 8087:     }
 8088:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8089:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8090:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8091:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8092:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8093:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8094:     $r->print('
 8095:     <p>
 8096: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8097: 	      '<a href="'.$orig.'">','</a>').'
 8098:     </p>
 8099:     <p>
 8100: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8101: 	      '<a href="'.$corrected.'">','</a>').'
 8102:     </p>
 8103:     <p>
 8104: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8105: 	      '<a href="'.$skipped.'">','</a>').'
 8106:     </p>
 8107: ');
 8108:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8109:     return '';
 8110: }
 8111: 
 8112: sub checkscantron_results {
 8113:     my ($r) = @_;
 8114:     my ($symb)=&get_symb($r);
 8115:     if (!$symb) {return '';}
 8116:     my $grading_menu_button=&show_grading_menu_form($symb);
 8117:     my $cid = $env{'request.course.id'};
 8118:     my %lettdig = &letter_to_digits();
 8119:     my $numletts = scalar(keys(%lettdig));
 8120:     my $cnum = $env{'course.'.$cid.'.num'};
 8121:     my $cdom = $env{'course.'.$cid.'.domain'};
 8122:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8123:     my %record;
 8124:     my %scantron_config =
 8125:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8126:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8127:     my $classlist=&Apache::loncoursedata::get_classlist();
 8128:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8129:     my $navmap=Apache::lonnavmaps::navmap->new();
 8130:     unless (ref($navmap)) {
 8131:         $r->print(&navmap_errormsg());
 8132:         return '';
 8133:     }
 8134:     my $map=$navmap->getResourceByUrl($sequence);
 8135:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8136:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8137:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8138: 
 8139:     my ($uname,$udom);
 8140:     my (%scandata,%lastname,%bylast);
 8141:     $r->print('
 8142: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8143: 
 8144:     my @delayqueue;
 8145:     my %completedstudents;
 8146: 
 8147:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8148:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8149:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8150:                                     'inline',undef,'checkscantron');
 8151:     my ($username,$domain,$started);
 8152:     my $nav_error;
 8153:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8154:     if ($nav_error) {
 8155:         $r->print(&navmap_errormsg());
 8156:         return '';
 8157:     }
 8158: 
 8159:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8160:                                           'Processing first student');
 8161:     my $start=&Time::HiRes::time();
 8162:     my $i=-1;
 8163: 
 8164:     while ($i<$scanlines->{'count'}) {
 8165:         ($username,$domain,$uname)=('','','');
 8166:         $i++;
 8167:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8168:         if ($line=~/^[\s\cz]*$/) { next; }
 8169:         if ($started) {
 8170:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8171:                                                      'last student');
 8172:         }
 8173:         $started=1;
 8174:         my $scan_record=
 8175:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8176:                                                      $scan_data);
 8177:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8178:                                                               \%idmap,$i)) {
 8179:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8180:                                 'Unable to find a student that matches',1);
 8181:             next;
 8182:         }
 8183:         if (exists $completedstudents{$uname}) {
 8184:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8185:                                 'Student '.$uname.' has multiple sheets',2);
 8186:             next;
 8187:         }
 8188:         my $pid = $scan_record->{'scantron.ID'};
 8189:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8190:         push(@{$bylast{$lastname{$pid}}},$pid);
 8191:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8192:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8193:         chomp($scandata{$pid});
 8194:         $scandata{$pid} =~ s/\r$//;
 8195:         ($username,$domain)=split(/:/,$uname);
 8196:         my $counter = -1;
 8197:         foreach my $resource (@resources) {
 8198:             my $parts;
 8199:             my $ressymb = $resource->symb();
 8200:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8201:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8202:                 (my $analysis,$parts) =
 8203:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8204:             } else {
 8205:                 $parts = $grader_partids_by_symb{$ressymb};
 8206:             }
 8207:             ($counter,my $recording) =
 8208:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8209:                                          $scandata{$pid},$parts,
 8210:                                          \%scantron_config,\%lettdig,$numletts);
 8211:             $record{$pid} .= $recording;
 8212:         }
 8213:     }
 8214:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8215:     $r->print('<br />');
 8216:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8217:     $passed = 0;
 8218:     $failed = 0;
 8219:     $numstudents = 0;
 8220:     foreach my $last (sort(keys(%bylast))) {
 8221:         if (ref($bylast{$last}) eq 'ARRAY') {
 8222:             foreach my $pid (sort(@{$bylast{$last}})) {
 8223:                 my $showscandata = $scandata{$pid};
 8224:                 my $showrecord = $record{$pid};
 8225:                 $showscandata =~ s/\s/&nbsp;/g;
 8226:                 $showrecord =~ s/\s/&nbsp;/g;
 8227:                 if ($scandata{$pid} eq $record{$pid}) {
 8228:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8229:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8230: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8231: '</tr>'."\n".
 8232: '<tr class="'.$css_class.'">'."\n".
 8233: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8234:                     $passed ++;
 8235:                 } else {
 8236:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8237:                     $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".
 8238: '</tr>'."\n".
 8239: '<tr class="'.$css_class.'">'."\n".
 8240: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8241: '</tr>'."\n";
 8242:                     $failed ++;
 8243:                 }
 8244:                 $numstudents ++;
 8245:             }
 8246:         }
 8247:     }
 8248:     $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>');
 8249:     $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>');
 8250:     if ($passed) {
 8251:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8252:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8253:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8254:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8255:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8256:                  $okstudents."\n".
 8257:                  &Apache::loncommon::end_data_table().'<br />');
 8258:     }
 8259:     if ($failed) {
 8260:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8261:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8262:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8263:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8264:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8265:                  $badstudents."\n".
 8266:                  &Apache::loncommon::end_data_table()).'<br />'.
 8267:                  &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.');  
 8268:     }
 8269:     $r->print('</form><br />'.$grading_menu_button);
 8270:     return;
 8271: }
 8272: 
 8273: sub verify_scantron_grading {
 8274:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8275:         $scantron_config,$lettdig,$numletts) = @_;
 8276:     my ($record,%expected,%startpos);
 8277:     return ($counter,$record) if (!ref($resource));
 8278:     return ($counter,$record) if (!$resource->is_problem());
 8279:     my $symb = $resource->symb();
 8280:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8281:     foreach my $part_id (@{$partids}) {
 8282:         $counter ++;
 8283:         $expected{$part_id} = 0;
 8284:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8285:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8286:             foreach my $item (@sub_lines) {
 8287:                 $expected{$part_id} += $item;
 8288:             }
 8289:         } else {
 8290:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8291:         }
 8292:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8293:     }
 8294:     if ($symb) {
 8295:         my %recorded;
 8296:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8297:         if ($returnhash{'version'}) {
 8298:             my %lasthash=();
 8299:             my $version;
 8300:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8301:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8302:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8303:                 }
 8304:             }
 8305:             foreach my $key (keys(%lasthash)) {
 8306:                 if ($key =~ /\.scantron$/) {
 8307:                     my $value = &unescape($lasthash{$key});
 8308:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8309:                     if ($value eq '') {
 8310:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8311:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8312:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8313:                             }
 8314:                         }
 8315:                     } else {
 8316:                         my @tocheck;
 8317:                         my @items = split(//,$value);
 8318:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8319:                             ($scantron_config->{'Qon'} eq 'number')) {
 8320:                             if (@items < $expected{$part_id}) {
 8321:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8322:                                 my @singles = split(//,$fragment);
 8323:                                 foreach my $pos (@singles) {
 8324:                                     if ($pos eq ' ') {
 8325:                                         push(@tocheck,$pos);
 8326:                                     } else {
 8327:                                         my $next = shift(@items);
 8328:                                         push(@tocheck,$next);
 8329:                                     }
 8330:                                 }
 8331:                             } else {
 8332:                                 @tocheck = @items;
 8333:                             }
 8334:                             foreach my $letter (@tocheck) {
 8335:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8336:                                     if ($letter !~ /^[A-J]$/) {
 8337:                                         $letter = $scantron_config->{'Qoff'};
 8338:                                     }
 8339:                                     $recorded{$part_id} .= $letter;
 8340:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8341:                                     my $digit;
 8342:                                     if ($letter !~ /^[A-J]$/) {
 8343:                                         $digit = $scantron_config->{'Qoff'};
 8344:                                     } else {
 8345:                                         $digit = $lettdig->{$letter};
 8346:                                     }
 8347:                                     $recorded{$part_id} .= $digit;
 8348:                                 }
 8349:                             }
 8350:                         } else {
 8351:                             @tocheck = @items;
 8352:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8353:                                 my $curr_sub = shift(@tocheck);
 8354:                                 my $digit;
 8355:                                 if ($curr_sub =~ /^[A-J]$/) {
 8356:                                     $digit = $lettdig->{$curr_sub}-1;
 8357:                                 }
 8358:                                 if ($curr_sub eq 'J') {
 8359:                                     $digit += scalar($numletts);
 8360:                                 }
 8361:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8362:                                     if ($j == $digit) {
 8363:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8364:                                     } else {
 8365:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8366:                                     }
 8367:                                 }
 8368:                             }
 8369:                         }
 8370:                     }
 8371:                 }
 8372:             }
 8373:         }
 8374:         foreach my $part_id (@{$partids}) {
 8375:             if ($recorded{$part_id} eq '') {
 8376:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8377:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8378:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8379:                     }
 8380:                 }
 8381:             }
 8382:             $record .= $recorded{$part_id};
 8383:         }
 8384:     }
 8385:     return ($counter,$record);
 8386: }
 8387: 
 8388: sub letter_to_digits { 
 8389:     my %lettdig = (
 8390:                     A => 1,
 8391:                     B => 2,
 8392:                     C => 3,
 8393:                     D => 4,
 8394:                     E => 5,
 8395:                     F => 6,
 8396:                     G => 7,
 8397:                     H => 8,
 8398:                     I => 9,
 8399:                     J => 0,
 8400:                   );
 8401:     return %lettdig;
 8402: }
 8403: 
 8404: 
 8405: #-------- end of section for handling grading scantron forms -------
 8406: #
 8407: #-------------------------------------------------------------------
 8408: 
 8409: #-------------------------- Menu interface -------------------------
 8410: #
 8411: #--- Show a Grading Menu button - Calls the next routine ---
 8412: sub show_grading_menu_form {
 8413:     my ($symb)=@_;
 8414:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8415: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8416: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8417: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8418: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8419: 	'</form>'."\n";
 8420:     return $result;
 8421: }
 8422: 
 8423: # -- Retrieve choices for grading form
 8424: sub savedState {
 8425:     my %savedState = ();
 8426:     if ($env{'form.saveState'}) {
 8427: 	foreach (split(/:/,$env{'form.saveState'})) {
 8428: 	    my ($key,$value) = split(/=/,$_,2);
 8429: 	    $savedState{$key} = $value;
 8430: 	}
 8431:     }
 8432:     return \%savedState;
 8433: }
 8434: 
 8435: sub grading_menu {
 8436:     my ($request) = @_;
 8437:     my ($symb)=&get_symb($request);
 8438:     if (!$symb) {return '';}
 8439:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8440:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8441: 
 8442:     $request->print($table);
 8443:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8444:                   'handgrade'=>$hdgrade,
 8445:                   'probTitle'=>$probTitle,
 8446:                   'command'=>'submit_options',
 8447:                   'saveState'=>"",
 8448:                   'gradingMenu'=>1,
 8449:                   'showgrading'=>"yes");
 8450:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8451:     my @menu = ({ url => $url,
 8452:                      name => &mt('Manual Grading/View Submissions'),
 8453:                      short_description =>
 8454:     &mt('Start the process of hand grading submissions.'),
 8455:                  });
 8456:     $fields{'command'} = 'csvform';
 8457:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8458:     push(@menu, { url => $url,
 8459:                    name => &mt('Upload Scores'),
 8460:                    short_description =>
 8461:             &mt('Specify a file containing the class scores for current resource.')});
 8462:     $fields{'command'} = 'processclicker';
 8463:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8464:     push(@menu, { url => $url,
 8465:                    name => &mt('Process Clicker'),
 8466:                    short_description =>
 8467:             &mt('Specify a file containing the clicker information for this resource.')});
 8468:     $fields{'command'} = 'scantron_selectphase';
 8469:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8470:     push(@menu, { url => $url,
 8471:                    name => &mt('Grade/Manage/Review Bubblesheets'),
 8472:                    short_description =>
 8473:             &mt('Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.')});
 8474:     $fields{'command'} = 'verify';
 8475:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8476:     push(@menu, { url => "",
 8477:                    name => &mt('Verify Receipt No.'),
 8478:                    short_description =>
 8479:             &mt('')});
 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:     foreach my $menudata (@menu) {
 8492:         if ($menudata->{'name'} ne &mt('Verify Receipt No.')) {
 8493:             $Str .='    <h3><a '.
 8494:                 $menudata->{'jscript'}.
 8495:                 ' href="'.
 8496:                 $menudata->{'url'}.'" >'.
 8497:                 $menudata->{'name'}."</a></h3>\n";
 8498:         } else {
 8499:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
 8500:                 $menudata->{'jscript'}.
 8501:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8502:                 ' /> '.
 8503:                 &Apache::lonnet::recprefix($env{'request.course.id'}).
 8504:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8505:         }
 8506:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8507:             "\n";
 8508:     }
 8509:     $Str .="</form>\n";
 8510:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8511:     $request->print(<<GRADINGMENUJS);
 8512: <script type="text/javascript" language="javascript">
 8513:     function checkChoice(formname,val,cmdx) {
 8514: 	if (val <= 2) {
 8515: 	    var cmd = radioSelection(formname.radioChoice);
 8516: 	    var cmdsave = cmd;
 8517: 	} else {
 8518: 	    cmd = cmdx;
 8519: 	    cmdsave = 'submission';
 8520: 	}
 8521: 	formname.command.value = cmd;
 8522: 	if (val < 5) formname.submit();
 8523: 	if (val == 5) {
 8524: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8525: 	        return false;
 8526: 	    } else {
 8527: 	        formname.submit();
 8528: 	    }
 8529: 	}
 8530:     }
 8531: 
 8532:     function checkReceiptNo(formname,nospace) {
 8533: 	var receiptNo = formname.receipt.value;
 8534: 	var checkOpt = false;
 8535: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8536: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8537: 	if (checkOpt) {
 8538: 	    alert("$receiptalert");
 8539: 	    formname.receipt.value = "";
 8540: 	    formname.receipt.focus();
 8541: 	    return false;
 8542: 	}
 8543: 	return true;
 8544:     }
 8545: </script>
 8546: GRADINGMENUJS
 8547:     &commonJSfunctions($request);
 8548:     return $Str;    
 8549: }
 8550: 
 8551: 
 8552: #--- Displays the submissions first page -------
 8553: sub submit_options {
 8554:     my ($request) = @_;
 8555:     my ($symb)=&get_symb($request);
 8556:     if (!$symb) {return '';}
 8557:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8558: 
 8559:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8560:     $request->print(<<GRADINGMENUJS);
 8561: <script type="text/javascript" language="javascript">
 8562:     function checkChoice(formname,val,cmdx) {
 8563: 	if (val <= 2) {
 8564: 	    var cmd = radioSelection(formname.radioChoice);
 8565: 	    var cmdsave = cmd;
 8566: 	} else {
 8567: 	    cmd = cmdx;
 8568: 	    cmdsave = 'submission';
 8569: 	}
 8570: 	formname.command.value = cmd;
 8571: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8572: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8573: 	if (val < 5) formname.submit();
 8574: 	if (val == 5) {
 8575: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8576: 	    formname.submit();
 8577: 	}
 8578: 	if (val < 7) formname.submit();
 8579:     }
 8580: 
 8581:     function checkReceiptNo(formname,nospace) {
 8582: 	var receiptNo = formname.receipt.value;
 8583: 	var checkOpt = false;
 8584: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8585: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8586: 	if (checkOpt) {
 8587: 	    alert("$receiptalert");
 8588: 	    formname.receipt.value = "";
 8589: 	    formname.receipt.focus();
 8590: 	    return false;
 8591: 	}
 8592: 	return true;
 8593:     }
 8594: </script>
 8595: GRADINGMENUJS
 8596:     &commonJSfunctions($request);
 8597:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8598:     my $result;
 8599:     my (undef,$sections) = &getclasslist('all','0');
 8600:     my $savedState = &savedState();
 8601:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8602:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8603:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8604:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8605: 
 8606:     # Preselect sections
 8607:     my $selsec="";
 8608:     if (ref($sections)) {
 8609:         foreach my $section (sort(@$sections)) {
 8610:             $selsec.='<option value="'.$section.'" '.
 8611:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8612:         }
 8613:     }
 8614: 
 8615:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8616: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8617: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8618: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8619: 	'<input type="hidden" name="command"     value="" />'."\n".
 8620: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8621: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8622: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8623: 
 8624:     $result.='
 8625:     <div class="LC_grade_select_mode">
 8626:       <div class="LC_grade_select_mode_current">
 8627:         <h2>
 8628:           '.&mt('Grade Current Resource').'
 8629:         </h2>
 8630:         <div class="LC_grade_select_mode_body">
 8631:           <div class="LC_grades_resource_info">
 8632:            '.$table.'
 8633:           </div>
 8634:           <div class="LC_grade_select_mode_selector">
 8635:              <div class="LC_grade_select_mode_selector_header">
 8636:                 '.&mt('Sections').'
 8637:              </div>
 8638:              <div class="LC_grade_select_mode_selector_body">
 8639:                <select name="section" multiple="multiple" size="5">'."\n";
 8640:     if (ref($sections)) {
 8641:         foreach my $section (sort(@$sections)) {
 8642:             $result.='<option value="'.$section.'" '.
 8643:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8644:         }
 8645:     }
 8646:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8647:     $result.='
 8648:              </div>
 8649:           </div>
 8650:           <div class="LC_grade_select_mode_selector">
 8651:              <div class="LC_grade_select_mode_selector_header">
 8652:                 '.&mt('Groups').'
 8653:              </div>
 8654:              <div class="LC_grade_select_mode_selector_body">
 8655:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8656:              </div>
 8657:           </div>
 8658:           <div class="LC_grade_select_mode_selector">
 8659:              <div class="LC_grade_select_mode_selector_header">
 8660:                 '.&mt('Access Status').'
 8661:              </div>
 8662:              <div class="LC_grade_select_mode_selector_body">
 8663:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8664:              </div>
 8665:           </div>
 8666:           <div class="LC_grade_select_mode_selector">
 8667:              <div class="LC_grade_select_mode_selector_header">
 8668:                 '.&mt('Submission Status').'
 8669:              </div>
 8670:              <div class="LC_grade_select_mode_selector_body">
 8671:                <select name="submitonly" size="5">
 8672:                  <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8673:                  <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8674:                  <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8675:                  <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8676:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8677:                </select>
 8678:              </div>
 8679:           </div>
 8680:           <div class="LC_grade_select_mode_type_body">
 8681:             <div class="LC_grade_select_mode_type">
 8682:               <label>
 8683:                 <input type="radio" name="radioChoice" value="submission" '.
 8684:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8685:              &mt('Select individual students to grade and view submissions.').'
 8686:               </label>
 8687:             </div>
 8688:             <div class="LC_grade_select_mode_type">
 8689:               <label>
 8690:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8691:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8692:                     &mt('Grade all selected students in a grading table.').'
 8693:               </label>
 8694:             </div>
 8695:             <div class="LC_grade_select_mode_type">
 8696:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8697:             </div>
 8698:           </div>
 8699:         </div>
 8700:       </div>
 8701:       <div class="LC_grade_select_mode_page">
 8702:         <h2>
 8703:          '.&mt('Grade Complete Folder for One Student').'
 8704:         </h2>
 8705:         <div class="LC_grades_select_mode_body">
 8706:           <div class="LC_grade_select_mode_type_body">
 8707:             <div class="LC_grade_select_mode_type">
 8708:               <label>
 8709:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8710:           ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8711:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8712:               </label>
 8713:             </div>
 8714:             <div class="LC_grade_select_mode_type">
 8715:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8716:             </div>
 8717:           </div>
 8718:         </div>
 8719:       </div>
 8720:     </div>
 8721:   </form>';
 8722:     $result .= &show_grading_menu_form($symb);
 8723:     return $result;
 8724: }
 8725: 
 8726: sub reset_perm {
 8727:     undef(%perm);
 8728: }
 8729: 
 8730: sub init_perm {
 8731:     &reset_perm();
 8732:     foreach my $test_perm ('vgr','mgr','opa') {
 8733: 
 8734: 	my $scope = $env{'request.course.id'};
 8735: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8736: 
 8737: 	    $scope .= '/'.$env{'request.course.sec'};
 8738: 	    if ( $perm{$test_perm}=
 8739: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8740: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8741: 	    } else {
 8742: 		delete($perm{$test_perm});
 8743: 	    }
 8744: 	}
 8745:     }
 8746: }
 8747: 
 8748: sub gather_clicker_ids {
 8749:     my %clicker_ids;
 8750: 
 8751:     my $classlist = &Apache::loncoursedata::get_classlist();
 8752: 
 8753:     # Set up a couple variables.
 8754:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8755:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8756:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8757: 
 8758:     foreach my $student (keys(%$classlist)) {
 8759:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8760:         my $username = $classlist->{$student}->[$username_idx];
 8761:         my $domain   = $classlist->{$student}->[$domain_idx];
 8762:         my $clickers =
 8763: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8764:         foreach my $id (split(/\,/,$clickers)) {
 8765:             $id=~s/^[\#0]+//;
 8766:             $id=~s/[\-\:]//g;
 8767:             if (exists($clicker_ids{$id})) {
 8768: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8769:             } else {
 8770: 		$clicker_ids{$id}=$username.':'.$domain;
 8771:             }
 8772:         }
 8773:     }
 8774:     return %clicker_ids;
 8775: }
 8776: 
 8777: sub gather_adv_clicker_ids {
 8778:     my %clicker_ids;
 8779:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8780:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8781:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8782:     foreach my $element (sort(keys(%coursepersonnel))) {
 8783:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8784:             my ($puname,$pudom)=split(/\:/,$person);
 8785:             my $clickers =
 8786: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8787:             foreach my $id (split(/\,/,$clickers)) {
 8788: 		$id=~s/^[\#0]+//;
 8789:                 $id=~s/[\-\:]//g;
 8790: 		if (exists($clicker_ids{$id})) {
 8791: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8792: 		} else {
 8793: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8794: 		}
 8795:             }
 8796:         }
 8797:     }
 8798:     return %clicker_ids;
 8799: }
 8800: 
 8801: sub clicker_grading_parameters {
 8802:     return ('gradingmechanism' => 'scalar',
 8803:             'upfiletype' => 'scalar',
 8804:             'specificid' => 'scalar',
 8805:             'pcorrect' => 'scalar',
 8806:             'pincorrect' => 'scalar');
 8807: }
 8808: 
 8809: sub process_clicker {
 8810:     my ($r)=@_;
 8811:     my ($symb)=&get_symb($r);
 8812:     if (!$symb) {return '';}
 8813:     my $result=&checkforfile_js();
 8814:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8815:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8816:     $result.=$table;
 8817:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8818:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8819:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8820:         '</b></td></tr>'."\n";
 8821:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8822: # Attempt to restore parameters from last session, set defaults if not present
 8823:     my %Saveable_Parameters=&clicker_grading_parameters();
 8824:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8825:                                                  \%Saveable_Parameters);
 8826:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8827:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8828:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8829:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8830: 
 8831:     my %checked;
 8832:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8833:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8834:           $checked{$gradingmechanism}=' checked="checked"';
 8835:        }
 8836:     }
 8837: 
 8838:     my $upload=&mt("Upload File");
 8839:     my $type=&mt("Type");
 8840:     my $attendance=&mt("Award points just for participation");
 8841:     my $personnel=&mt("Correctness determined from response by course personnel");
 8842:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8843:     my $given=&mt("Correctness determined from given list of answers").' '.
 8844:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8845:     my $pcorrect=&mt("Percentage points for correct solution");
 8846:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8847:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8848: 						   ('iclicker' => 'i>clicker',
 8849:                                                     'interwrite' => 'interwrite PRS'));
 8850:     $symb = &Apache::lonenc::check_encrypt($symb);
 8851:     $result.=<<ENDUPFORM;
 8852: <script type="text/javascript">
 8853: function sanitycheck() {
 8854: // Accept only integer percentages
 8855:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8856:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8857: // Find out grading choice
 8858:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8859:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8860:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8861:       }
 8862:    }
 8863: // By default, new choice equals user selection
 8864:    newgradingchoice=gradingchoice;
 8865: // Not good to give more points for false answers than correct ones
 8866:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8867:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8868:    }
 8869: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8870:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8871:       document.forms.gradesupload.pcorrect.value=100;
 8872:       document.forms.gradesupload.pincorrect.value=100;
 8873:    }
 8874: // If the values are different, cannot be attendance only
 8875:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8876:        (gradingchoice=='attendance')) {
 8877:        newgradingchoice='personnel';
 8878:    }
 8879: // Change grading choice to new one
 8880:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8881:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8882:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8883:       } else {
 8884:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8885:       }
 8886:    }
 8887: // Remember the old state
 8888:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8889: }
 8890: </script>
 8891: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8892: <input type="hidden" name="symb" value="$symb" />
 8893: <input type="hidden" name="command" value="processclickerfile" />
 8894: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8895: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8896: <input type="file" name="upfile" size="50" />
 8897: <br /><label>$type: $selectform</label>
 8898: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8899: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8900: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8901: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8902: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8903: <br />&nbsp;&nbsp;&nbsp;
 8904: <input type="text" name="givenanswer" size="50" />
 8905: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8906: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8907: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8908: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8909: </form>
 8910: ENDUPFORM
 8911:     $result.='</td></tr></table>'."\n".
 8912:              '</td></tr></table><br /><br />'."\n";
 8913:     $result.=&show_grading_menu_form($symb);
 8914:     return $result;
 8915: }
 8916: 
 8917: sub process_clicker_file {
 8918:     my ($r)=@_;
 8919:     my ($symb)=&get_symb($r);
 8920:     if (!$symb) {return '';}
 8921: 
 8922:     my %Saveable_Parameters=&clicker_grading_parameters();
 8923:     &Apache::loncommon::store_course_settings('grades_clicker',
 8924:                                               \%Saveable_Parameters);
 8925: 
 8926:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8927:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8928: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8929: 	return $result.&show_grading_menu_form($symb);
 8930:     }
 8931:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8932:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8933:         return $result.&show_grading_menu_form($symb);
 8934:     }
 8935:     my $foundgiven=0;
 8936:     if ($env{'form.gradingmechanism'} eq 'given') {
 8937:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8938:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8939:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8940:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8941:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8942:         $foundgiven=$#answers+1;
 8943:     }
 8944:     my %clicker_ids=&gather_clicker_ids();
 8945:     my %correct_ids;
 8946:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8947: 	%correct_ids=&gather_adv_clicker_ids();
 8948:     }
 8949:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8950: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8951: 	   $correct_id=~tr/a-z/A-Z/;
 8952: 	   $correct_id=~s/\s//gs;
 8953: 	   $correct_id=~s/^[\#0]+//;
 8954:            $correct_id=~s/[\-\:]//g;
 8955:            if ($correct_id) {
 8956: 	      $correct_ids{$correct_id}='specified';
 8957:            }
 8958:         }
 8959:     }
 8960:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8961: 	$result.=&mt('Score based on attendance only');
 8962:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8963:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8964:     } else {
 8965: 	my $number=0;
 8966: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8967: 	foreach my $id (sort(keys(%correct_ids))) {
 8968: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8969: 	    if ($correct_ids{$id} eq 'specified') {
 8970: 		$result.=&mt('specified');
 8971: 	    } else {
 8972: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8973: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8974: 	    }
 8975: 	    $number++;
 8976: 	}
 8977:         $result.="</p>\n";
 8978: 	if ($number==0) {
 8979: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8980: 	    return $result.&show_grading_menu_form($symb);
 8981: 	}
 8982:     }
 8983:     if (length($env{'form.upfile'}) < 2) {
 8984:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8985: 		     '<span class="LC_error">',
 8986: 		     '</span>',
 8987: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8988:         return $result.&show_grading_menu_form($symb);
 8989:     }
 8990: 
 8991: # Were able to get all the info needed, now analyze the file
 8992: 
 8993:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8994:     $symb = &Apache::lonenc::check_encrypt($symb);
 8995:     my $heading=&mt('Scanning clicker file');
 8996:     $result.=(<<ENDHEADER);
 8997: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8998: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8999: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9000: <form method="post" action="/adm/grades" name="clickeranalysis">
 9001: <input type="hidden" name="symb" value="$symb" />
 9002: <input type="hidden" name="command" value="assignclickergrades" />
 9003: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9004: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9005: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9006: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9007: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9008: ENDHEADER
 9009:     if ($env{'form.gradingmechanism'} eq 'given') {
 9010:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9011:     } 
 9012:     my %responses;
 9013:     my @questiontitles;
 9014:     my $errormsg='';
 9015:     my $number=0;
 9016:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9017: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9018:     }
 9019:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9020:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9021:     }
 9022:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9023:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9024:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9025:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9026:              '<br />';
 9027:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9028:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9029:        return $result.&show_grading_menu_form($symb);
 9030:     } 
 9031: # Remember Question Titles
 9032: # FIXME: Possibly need delimiter other than ":"
 9033:     for (my $i=0;$i<$number;$i++) {
 9034:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9035:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9036:     }
 9037:     my $correct_count=0;
 9038:     my $student_count=0;
 9039:     my $unknown_count=0;
 9040: # Match answers with usernames
 9041: # FIXME: Possibly need delimiter other than ":"
 9042:     foreach my $id (keys(%responses)) {
 9043:        if ($correct_ids{$id}) {
 9044:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9045:           $correct_count++;
 9046:        } elsif ($clicker_ids{$id}) {
 9047:           if ($clicker_ids{$id}=~/\,/) {
 9048: # More than one user with the same clicker!
 9049:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9050:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9051:                            "<select name='multi".$id."'>";
 9052:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9053:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9054:              }
 9055:              $result.='</select>';
 9056:              $unknown_count++;
 9057:           } else {
 9058: # Good: found one and only one user with the right clicker
 9059:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9060:              $student_count++;
 9061:           }
 9062:        } else {
 9063:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9064:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9065:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9066:                    "\n".&mt("Domain").": ".
 9067:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9068:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9069:           $unknown_count++;
 9070:        }
 9071:     }
 9072:     $result.='<hr />'.
 9073:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9074:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9075:        if ($correct_count==0) {
 9076:           $errormsg.="Found no correct answers answers for grading!";
 9077:        } elsif ($correct_count>1) {
 9078:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9079:        }
 9080:     }
 9081:     if ($number<1) {
 9082:        $errormsg.="Found no questions.";
 9083:     }
 9084:     if ($errormsg) {
 9085:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9086:     } else {
 9087:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9088:     }
 9089:     $result.='</form></td></tr></table>'."\n".
 9090:              '</td></tr></table><br /><br />'."\n";
 9091:     return $result.&show_grading_menu_form($symb);
 9092: }
 9093: 
 9094: sub iclicker_eval {
 9095:     my ($questiontitles,$responses)=@_;
 9096:     my $number=0;
 9097:     my $errormsg='';
 9098:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9099:         my %components=&Apache::loncommon::record_sep($line);
 9100:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9101: 	if ($entries[0] eq 'Question') {
 9102: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9103: 		$$questiontitles[$number]=$entries[$i];
 9104: 		$number++;
 9105: 	    }
 9106: 	}
 9107: 	if ($entries[0]=~/^\#/) {
 9108: 	    my $id=$entries[0];
 9109: 	    my @idresponses;
 9110: 	    $id=~s/^[\#0]+//;
 9111: 	    for (my $i=0;$i<$number;$i++) {
 9112: 		my $idx=3+$i*6;
 9113: 		push(@idresponses,$entries[$idx]);
 9114: 	    }
 9115: 	    $$responses{$id}=join(',',@idresponses);
 9116: 	}
 9117:     }
 9118:     return ($errormsg,$number);
 9119: }
 9120: 
 9121: sub interwrite_eval {
 9122:     my ($questiontitles,$responses)=@_;
 9123:     my $number=0;
 9124:     my $errormsg='';
 9125:     my $skipline=1;
 9126:     my $questionnumber=0;
 9127:     my %idresponses=();
 9128:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9129:         my %components=&Apache::loncommon::record_sep($line);
 9130:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9131:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9132:         if ($entries[1] eq 'Response') { $skipline=1; }
 9133:         next if $skipline;
 9134:         if ($entries[0]!=$questionnumber) {
 9135:            $questionnumber=$entries[0];
 9136:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9137:            $number++;
 9138:         }
 9139:         my $id=$entries[4];
 9140:         $id=~s/^[\#0]+//;
 9141:         $id=~s/^v\d*\://i;
 9142:         $id=~s/[\-\:]//g;
 9143:         $idresponses{$id}[$number]=$entries[6];
 9144:     }
 9145:     foreach my $id (keys(%idresponses)) {
 9146:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9147:        $$responses{$id}=~s/^\s*\,//;
 9148:     }
 9149:     return ($errormsg,$number);
 9150: }
 9151: 
 9152: sub assign_clicker_grades {
 9153:     my ($r)=@_;
 9154:     my ($symb)=&get_symb($r);
 9155:     if (!$symb) {return '';}
 9156: # See which part we are saving to
 9157:     my $res_error;
 9158:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9159:     if ($res_error) {
 9160:         return &navmap_errormsg();
 9161:     }
 9162: # FIXME: This should probably look for the first handgradeable part
 9163:     my $part=$$partlist[0];
 9164: # Start screen output
 9165:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9166: 
 9167:     my $heading=&mt('Assigning grades based on clicker file');
 9168:     $result.=(<<ENDHEADER);
 9169: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9170: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9171: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9172: ENDHEADER
 9173: # Get correct result
 9174: # FIXME: Possibly need delimiter other than ":"
 9175:     my @correct=();
 9176:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9177:     my $number=$env{'form.number'};
 9178:     if ($gradingmechanism ne 'attendance') {
 9179:        foreach my $key (keys(%env)) {
 9180:           if ($key=~/^form\.correct\:/) {
 9181:              my @input=split(/\,/,$env{$key});
 9182:              for (my $i=0;$i<=$#input;$i++) {
 9183:                  if (($correct[$i]) && ($input[$i]) &&
 9184:                      ($correct[$i] ne $input[$i])) {
 9185:                     $result.='<br /><span class="LC_warning">'.
 9186:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9187:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9188:                  } elsif ($input[$i]) {
 9189:                     $correct[$i]=$input[$i];
 9190:                  }
 9191:              }
 9192:           }
 9193:        }
 9194:        for (my $i=0;$i<$number;$i++) {
 9195:           if (!$correct[$i]) {
 9196:              $result.='<br /><span class="LC_error">'.
 9197:                       &mt('No correct result given for question "[_1]"!',
 9198:                           $env{'form.question:'.$i}).'</span>';
 9199:           }
 9200:        }
 9201:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9202:     }
 9203: # Start grading
 9204:     my $pcorrect=$env{'form.pcorrect'};
 9205:     my $pincorrect=$env{'form.pincorrect'};
 9206:     my $storecount=0;
 9207:     foreach my $key (keys(%env)) {
 9208:        my $user='';
 9209:        if ($key=~/^form\.student\:(.*)$/) {
 9210:           $user=$1;
 9211:        }
 9212:        if ($key=~/^form\.unknown\:(.*)$/) {
 9213:           my $id=$1;
 9214:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9215:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9216:           } elsif ($env{'form.multi'.$id}) {
 9217:              $user=$env{'form.multi'.$id};
 9218:           }
 9219:        }
 9220:        if ($user) { 
 9221:           my @answer=split(/\,/,$env{$key});
 9222:           my $sum=0;
 9223:           my $realnumber=$number;
 9224:           for (my $i=0;$i<$number;$i++) {
 9225:              if  ($correct[$i] eq '-') {
 9226:                 $realnumber--;
 9227:              } elsif ($answer[$i]) {
 9228:                 if ($gradingmechanism eq 'attendance') {
 9229:                    $sum+=$pcorrect;
 9230:                 } elsif ($correct[$i] eq '*') {
 9231:                    $sum+=$pcorrect;
 9232:                 } else {
 9233:                    if ($answer[$i] eq $correct[$i]) {
 9234:                       $sum+=$pcorrect;
 9235:                    } else {
 9236:                       $sum+=$pincorrect;
 9237:                    }
 9238:                 }
 9239:              }
 9240:           }
 9241:           my $ave=$sum/(100*$realnumber);
 9242: # Store
 9243:           my ($username,$domain)=split(/\:/,$user);
 9244:           my %grades=();
 9245:           $grades{"resource.$part.solved"}='correct_by_override';
 9246:           $grades{"resource.$part.awarded"}=$ave;
 9247:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9248:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9249:                                                  $env{'request.course.id'},
 9250:                                                  $domain,$username);
 9251:           if ($returncode ne 'ok') {
 9252:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9253:           } else {
 9254:              $storecount++;
 9255:           }
 9256:        }
 9257:     }
 9258: # We are done
 9259:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9260:              '</td></tr></table>'."\n".
 9261:              '</td></tr></table><br /><br />'."\n";
 9262:     return $result.&show_grading_menu_form($symb);
 9263: }
 9264: 
 9265: sub navmap_errormsg {
 9266:     return '<div class="LC_error">'.
 9267:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9268:            &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>').
 9269:            '</div>';
 9270: }
 9271: 
 9272: sub handler {
 9273:     my $request=$_[0];
 9274:     &reset_caches();
 9275:     if ($env{'browser.mathml'}) {
 9276: 	&Apache::loncommon::content_type($request,'text/xml');
 9277:     } else {
 9278: 	&Apache::loncommon::content_type($request,'text/html');
 9279:     }
 9280:     $request->send_http_header;
 9281:     return '' if $request->header_only;
 9282:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9283:     my $symb=&get_symb($request,1);
 9284:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9285:     my $command=$commands[0];
 9286: 
 9287:     if ($#commands > 0) {
 9288: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9289:     }
 9290: 
 9291:     $ssi_error = 0;
 9292:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9293:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9294:                                           {'bread_crumbs' => $brcrum}));
 9295:     if ($symb eq '' && $command eq '') {
 9296: 	if ($env{'user.adv'}) {
 9297: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9298: 		($env{'form.codethree'})) {
 9299: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9300: 		    $env{'form.codethree'};
 9301: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9302: 		    &Apache::lonnet::checkin($token);
 9303: 		if ($tsymb) {
 9304: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9305: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9306: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9307: 					  ('grade_username' => $tuname,
 9308: 					   'grade_domain' => $tudom,
 9309: 					   'grade_courseid' => $tcrsid,
 9310: 					   'grade_symb' => $tsymb)));
 9311: 		    } else {
 9312: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9313: 		    }
 9314: 		} else {
 9315: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9316: 		}
 9317: 	    } else {
 9318: 		$request->print(&Apache::lonxml::tokeninputfield());
 9319: 	    }
 9320: 	}
 9321:     } else {
 9322: 	&init_perm();
 9323: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9324: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9325: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9326: 	    &pickStudentPage($request);
 9327: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9328: 	    &displayPage($request);
 9329: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9330: 	    &updateGradeByPage($request);
 9331: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9332: 	    &processGroup($request);
 9333: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9334: 	    $request->print(&grading_menu($request));
 9335: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9336: 	    $request->print(&submit_options($request));
 9337: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9338: 	    $request->print(&viewgrades($request));
 9339: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9340: 	    $request->print(&processHandGrade($request));
 9341: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9342: 	    $request->print(&editgrades($request));
 9343: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9344: 	    $request->print(&verifyreceipt($request));
 9345:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9346:             $request->print(&process_clicker($request));
 9347:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9348:             $request->print(&process_clicker_file($request));
 9349:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9350:             $request->print(&assign_clicker_grades($request));
 9351: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9352: 	    $request->print(&upcsvScores_form($request));
 9353: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9354: 	    $request->print(&csvupload($request));
 9355: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9356: 	    $request->print(&csvuploadmap($request));
 9357: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9358: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9359: 		$request->print(&csvuploadoptions($request));
 9360: 	    } else {
 9361: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9362: 		    $env{'form.upfile_associate'} = 'reverse';
 9363: 		} else {
 9364: 		    $env{'form.upfile_associate'} = 'forward';
 9365: 		}
 9366: 		$request->print(&csvuploadmap($request));
 9367: 	    }
 9368: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9369: 	    $request->print(&csvuploadassign($request));
 9370: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9371: 	    $request->print(&scantron_selectphase($request));
 9372:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9373:  	    $request->print(&scantron_do_warning($request));
 9374: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9375: 	    $request->print(&scantron_validate_file($request));
 9376: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9377: 	    $request->print(&scantron_process_students($request));
 9378:  	} elsif ($command eq 'scantronupload' && 
 9379:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9380: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9381:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9382:  	} elsif ($command eq 'scantronupload_save' &&
 9383:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9384: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9385:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9386:  	} elsif ($command eq 'scantron_download' &&
 9387: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9388:  	    $request->print(&scantron_download_scantron_data($request));
 9389:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9390:             $request->print(&checkscantron_results($request));     
 9391: 	} elsif ($command) {
 9392: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9393: 	}
 9394:     }
 9395:     if ($ssi_error) {
 9396: 	&ssi_print_error($request);
 9397:     }
 9398:     $request->print(&Apache::loncommon::end_page());
 9399:     &reset_caches();
 9400:     return '';
 9401: }
 9402: 
 9403: 1;
 9404: 
 9405: __END__;
 9406: 
 9407: 
 9408: =head1 NAME
 9409: 
 9410: Apache::grades
 9411: 
 9412: =head1 SYNOPSIS
 9413: 
 9414: Handles the viewing of grades.
 9415: 
 9416: This is part of the LearningOnline Network with CAPA project
 9417: described at http://www.lon-capa.org.
 9418: 
 9419: =head1 OVERVIEW
 9420: 
 9421: Do an ssi with retries:
 9422: While I'd love to factor out this with the vesrion in lonprintout,
 9423: 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
 9424: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9425: 
 9426: At least the logic that drives this has been pulled out into loncommon.
 9427: 
 9428: 
 9429: 
 9430: ssi_with_retries - Does the server side include of a resource.
 9431:                      if the ssi call returns an error we'll retry it up to
 9432:                      the number of times requested by the caller.
 9433:                      If we still have a proble, no text is appended to the
 9434:                      output and we set some global variables.
 9435:                      to indicate to the caller an SSI error occurred.  
 9436:                      All of this is supposed to deal with the issues described
 9437:                      in LonCAPA BZ 5631 see:
 9438:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9439:                      by informing the user that this happened.
 9440: 
 9441: Parameters:
 9442:   resource   - The resource to include.  This is passed directly, without
 9443:                interpretation to lonnet::ssi.
 9444:   form       - The form hash parameters that guide the interpretation of the resource
 9445:                
 9446:   retries    - Number of retries allowed before giving up completely.
 9447: Returns:
 9448:   On success, returns the rendered resource identified by the resource parameter.
 9449: Side Effects:
 9450:   The following global variables can be set:
 9451:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9452:                               It is up to the caller to initialize this to false
 9453:                               if desired.
 9454:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9455:                               of the resource that could not be rendered by the ssi
 9456:                               call.
 9457:    ssi_error_message   - The error string fetched from the ssi response
 9458:                               in the event of an error.
 9459: 
 9460: 
 9461: =head1 HANDLER SUBROUTINE
 9462: 
 9463: ssi_with_retries()
 9464: 
 9465: =head1 SUBROUTINES
 9466: 
 9467: =over
 9468: 
 9469: =item scantron_get_correction() : 
 9470: 
 9471:    Builds the interface screen to interact with the operator to fix a
 9472:    specific error condition in a specific scanline
 9473: 
 9474:  Arguments:
 9475:     $r           - Apache request object
 9476:     $i           - number of the current scanline
 9477:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9478:     $scan_config - hash ref as returned from &get_scantron_config()
 9479:     $line        - full contents of the current scanline
 9480:     $error       - error condition, valid values are
 9481:                    'incorrectCODE', 'duplicateCODE',
 9482:                    'doublebubble', 'missingbubble',
 9483:                    'duplicateID', 'incorrectID'
 9484:     $arg         - extra information needed
 9485:        For errors:
 9486:          - duplicateID   - paper number that this studentID was seen before on
 9487:          - duplicateCODE - array ref of the paper numbers this CODE was
 9488:                            seen on before
 9489:          - incorrectCODE - current incorrect CODE 
 9490:          - doublebubble  - array ref of the bubble lines that have double
 9491:                            bubble errors
 9492:          - missingbubble - array ref of the bubble lines that have missing
 9493:                            bubble errors
 9494: 
 9495: =item  scantron_get_maxbubble() : 
 9496: 
 9497:    Arguments:
 9498:        $nav_error  - Reference to scalar which is a flag to indicate a
 9499:                       failure to retrieve a navmap object.
 9500:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9501:        calling routine should trap the error condition and display the warning
 9502:        found in &navmap_errormsg().
 9503: 
 9504:    Returns the maximum number of bubble lines that are expected to
 9505:    occur. Does this by walking the selected sequence rendering the
 9506:    resource and then checking &Apache::lonxml::get_problem_counter()
 9507:    for what the current value of the problem counter is.
 9508: 
 9509:    Caches the results to $env{'form.scantron_maxbubble'},
 9510:    $env{'form.scantron.bubble_lines.n'}, 
 9511:    $env{'form.scantron.first_bubble_line.n'} and
 9512:    $env{"form.scantron.sub_bubblelines.n"}
 9513:    which are the total number of bubble, lines, the number of bubble
 9514:    lines for response n and number of the first bubble line for response n,
 9515:    and a comma separated list of numbers of bubble lines for sub-questions
 9516:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9517: 
 9518: 
 9519: =item  scantron_validate_missingbubbles() : 
 9520: 
 9521:    Validates all scanlines in the selected file to not have any
 9522:     answers that don't have bubbles that have not been verified
 9523:     to be bubble free.
 9524: 
 9525: =item  scantron_process_students() : 
 9526: 
 9527:    Routine that does the actual grading of the bubble sheet information.
 9528: 
 9529:    The parsed scanline hash is added to %env 
 9530: 
 9531:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9532:    foreach resource , with the form data of
 9533: 
 9534: 	'submitted'     =>'scantron' 
 9535: 	'grade_target'  =>'grade',
 9536: 	'grade_username'=> username of student
 9537: 	'grade_domain'  => domain of student
 9538: 	'grade_courseid'=> of course
 9539: 	'grade_symb'    => symb of resource to grade
 9540: 
 9541:     This triggers a grading pass. The problem grading code takes care
 9542:     of converting the bubbled letter information (now in %env) into a
 9543:     valid submission.
 9544: 
 9545: =item  scantron_upload_scantron_data() :
 9546: 
 9547:     Creates the screen for adding a new bubble sheet data file to a course.
 9548: 
 9549: =item  scantron_upload_scantron_data_save() : 
 9550: 
 9551:    Adds a provided bubble information data file to the course if user
 9552:    has the correct privileges to do so. 
 9553: 
 9554: =item  valid_file() :
 9555: 
 9556:    Validates that the requested bubble data file exists in the course.
 9557: 
 9558: =item  scantron_download_scantron_data() : 
 9559: 
 9560:    Shows a list of the three internal files (original, corrected,
 9561:    skipped) for a specific bubble sheet data file that exists in the
 9562:    course.
 9563: 
 9564: =item  scantron_validate_ID() : 
 9565: 
 9566:    Validates all scanlines in the selected file to not have any
 9567:    invalid or underspecified student/employee IDs
 9568: 
 9569: =item navmap_errormsg() :
 9570: 
 9571:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9572:    Should be called whenever the request to instantiate a navmap object fails.  
 9573: 
 9574: =back
 9575: 
 9576: =cut

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