File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.574.2.8: download - view: text, annotated - select for diffs
Wed Jan 27 06:28:35 2010 UTC (14 years, 3 months ago) by raeburn
Branches: version_2_9_X
- Backport 1.586, 1.591.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.574.2.8 2010/01/27 06:28:35 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.');
  835:     } else {
  836: 	$string = &jscriptNform($symb).$title.
  837: 	    '<p>'.
  838: 	    &mt('The above receipt 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: 
 1758: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1759:     $result .= 
 1760: 	    '<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>';
 1761:     $result.='</tr></table>'."\n";
 1762:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1763: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1764: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1765: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1766:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1767:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1768:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1769:         $aggtries.'" />'."\n";
 1770:     my $res_error;
 1771:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
 1772:     if ($res_error) {
 1773:         return &navmap_errormsg();
 1774:     }
 1775:     return $result;
 1776: }
 1777: 
 1778: sub handback_box {
 1779:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
 1780:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
 1781:     my (@respids);
 1782:     my @part_response_id = &flatten_responseType($responseType);
 1783:     foreach my $part_response_id (@part_response_id) {
 1784:     	my ($part,$resp) = @{ $part_response_id };
 1785:         if ($part eq $partid) {
 1786:             push(@respids,$resp);
 1787:         }
 1788:     }
 1789:     my $result;
 1790:     foreach my $respid (@respids) {
 1791: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1792: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1793: 	next if (!@$files);
 1794: 	my $file_counter = 1;
 1795: 	foreach my $file (@$files) {
 1796: 	    if ($file =~ /\/portfolio\//) {
 1797:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1798:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1799:     	        $file_disp = "$name.$ext";
 1800:     	        $file = $file_path.$file_disp;
 1801:     	        $result.=&mt('Return commented version of [_1] to student.',
 1802:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1803:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1804:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1805:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1806:     	        $file_counter++;
 1807: 	    }
 1808: 	}
 1809:     }
 1810:     return $result;    
 1811: }
 1812: 
 1813: sub show_problem {
 1814:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1815:     my $rendered;
 1816:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1817:     &Apache::lonxml::remember_problem_counter();
 1818:     if ($mode eq 'both' or $mode eq 'text') {
 1819: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1820: 						       $env{'request.course.id'},
 1821: 						       undef,\%form);
 1822:     }
 1823:     if ($removeform) {
 1824: 	$rendered=~s|<form(.*?)>||g;
 1825: 	$rendered=~s|</form>||g;
 1826: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1827:     }
 1828:     my $companswer;
 1829:     if ($mode eq 'both' or $mode eq 'answer') {
 1830: 	&Apache::lonxml::restore_problem_counter();
 1831: 	$companswer=
 1832: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1833: 						    $env{'request.course.id'},
 1834: 						    %form);
 1835:     }
 1836:     if ($removeform) {
 1837: 	$companswer=~s|<form(.*?)>||g;
 1838: 	$companswer=~s|</form>||g;
 1839: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1840:     }
 1841:     $rendered=
 1842: 	'<div class="LC_grade_show_problem_header">'.
 1843: 	&mt('View of the problem').
 1844: 	'</div><div class="LC_grade_show_problem_problem">'.
 1845: 	$rendered.
 1846: 	'</div>';
 1847:     $companswer=
 1848: 	'<div class="LC_grade_show_problem_header">'.
 1849: 	&mt('Correct answer').
 1850: 	'</div><div class="LC_grade_show_problem_problem">'.
 1851: 	$companswer.
 1852: 	'</div>';
 1853:     my $result;
 1854:     if ($mode eq 'both') {
 1855: 	$result=$rendered.$companswer;
 1856:     } elsif ($mode eq 'text') {
 1857: 	$result=$rendered;
 1858:     } elsif ($mode eq 'answer') {
 1859: 	$result=$companswer;
 1860:     }
 1861:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1862:     return $result;
 1863: }
 1864: 
 1865: sub files_exist {
 1866:     my ($r, $symb) = @_;
 1867:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1868: 
 1869:     foreach my $student (@students) {
 1870:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1871:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1872: 					      $udom,$uname);
 1873:         my ($string,$timestamp)= &get_last_submission(\%record);
 1874:         foreach my $submission (@$string) {
 1875:             my ($partid,$respid) =
 1876: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1877:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1878: 					   \%record);
 1879:             return 1 if (@$files);
 1880:         }
 1881:     }
 1882:     return 0;
 1883: }
 1884: 
 1885: sub download_all_link {
 1886:     my ($r,$symb) = @_;
 1887:     my $all_students = 
 1888: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1889: 
 1890:     my $parts =
 1891: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1892: 
 1893:     my $identifier = &Apache::loncommon::get_cgi_id();
 1894:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1895:                              'cgi.'.$identifier.'.symb' => $symb,
 1896:                              'cgi.'.$identifier.'.parts' => $parts,});
 1897:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1898: 	      &mt('Download All Submitted Documents').'</a>');
 1899:     return
 1900: }
 1901: 
 1902: sub build_section_inputs {
 1903:     my $section_inputs;
 1904:     if ($env{'form.section'} eq '') {
 1905:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1906:     } else {
 1907:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1908:         foreach my $section (@sections) {
 1909:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1910:         }
 1911:     }
 1912:     return $section_inputs;
 1913: }
 1914: 
 1915: # --------------------------- show submissions of a student, option to grade 
 1916: sub submission {
 1917:     my ($request,$counter,$total) = @_;
 1918:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1919:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1920:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1921:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1922:     my $symb = &get_symb($request); 
 1923:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1924: 
 1925:     if (!&canview($usec)) {
 1926: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1927: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1928: 			$env{'request.course.id'}.')</span>');
 1929: 	$request->print(&show_grading_menu_form($symb));
 1930: 	return;
 1931:     }
 1932: 
 1933:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1934:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1935:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1936:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1937:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1938: 	'" src="'.$request->dir_config('lonIconsURL').
 1939: 	'/check.gif" height="16" border="0" />';
 1940: 
 1941:     my %old_essays;
 1942:     # header info
 1943:     if ($counter == 0) {
 1944: 	&sub_page_js($request);
 1945: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1946: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1947: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1948: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1949: 	    &download_all_link($request, $symb);
 1950: 	}
 1951: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1952: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1953: 
 1954: 	# option to display problem, only once else it cause problems 
 1955:         # with the form later since the problem has a form.
 1956: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1957: 	    my $mode;
 1958: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1959: 		$mode='both';
 1960: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1961: 		$mode='text';
 1962: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1963: 		$mode='answer';
 1964: 	    }
 1965: 	    &Apache::lonxml::clear_problem_counter();
 1966: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1967: 	}
 1968: 
 1969: 	# kwclr is the only variable that is guaranteed to be non blank 
 1970:         # if this subroutine has been called once.
 1971: 	my %keyhash = ();
 1972: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1973: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1974: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1975: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1976: 
 1977: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1978: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1979: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1980: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1981: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1982: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1983: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1984: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1985: 	}
 1986: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1987: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1988: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1989: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1990: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1991: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1992: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1993: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1994: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1995: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1996: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1997: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1998: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1999: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2000: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2001: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2002: 			&build_section_inputs().
 2003: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2004: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2005: 			'<input type="hidden" name="NCT"'.
 2006: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2007: 	if ($env{'form.handgrade'} eq 'yes') {
 2008: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2009: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2010: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2011: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2012: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2013: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2014: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2015: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2016: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2017: 	    }
 2018: 	}
 2019: 	
 2020: 	my ($cts,$prnmsg) = (1,'');
 2021: 	while ($cts <= $env{'form.savemsgN'}) {
 2022: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2023: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2024: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2025: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2026: 		'" />'."\n".
 2027: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2028: 	    $cts++;
 2029: 	}
 2030: 	$request->print($prnmsg);
 2031: 
 2032: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2033: #
 2034: # Print out the keyword options line
 2035: #
 2036: 	    $request->print(<<KEYWORDS);
 2037: &nbsp;<b>Keyword Options:</b>&nbsp;
 2038: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2039: <a href="#" onMouseDown="javascript:getSel(); return false"
 2040:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2041: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2042: KEYWORDS
 2043: #
 2044: # Load the other essays for similarity check
 2045: #
 2046:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2047: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2048: 	    $apath=&escape($apath);
 2049: 	    $apath=~s/\W/\_/gs;
 2050: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2051:         }
 2052:     }
 2053: 
 2054: # This is where output for one specific student would start
 2055:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2056:     $request->print("\n\n".
 2057:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2058: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2059: 		    '<div class="LC_grade_show_user_body">'."\n");
 2060: 
 2061:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2062: 	my $mode;
 2063: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2064: 	    $mode='both';
 2065: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2066: 	    $mode='text';
 2067: 	} elsif ($env{'form.vAns'} eq 'all') {
 2068: 	    $mode='answer';
 2069: 	}
 2070: 	&Apache::lonxml::clear_problem_counter();
 2071: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2072:     }
 2073: 
 2074:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2075:     my $res_error;
 2076:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2077:     if ($res_error) {
 2078:         $request->print(&navmap_errormsg());
 2079:         return;
 2080:     }
 2081: 
 2082:     # Display student info
 2083:     $request->print(($counter == 0 ? '' : '<br />'));
 2084:     my $result='<div class="LC_grade_submissions">';
 2085:     
 2086:     $result.='<div class="LC_grade_submissions_header">';
 2087:     $result.= &mt('Submissions');
 2088:     $result.='<input type="hidden" name="name'.$counter.
 2089: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2090:     if ($env{'form.handgrade'} eq 'no') {
 2091: 	$result.='<span class="LC_grade_check_note">'.
 2092: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2093: 
 2094:     }
 2095: 
 2096: 
 2097: 
 2098:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2099:     my $fullname;
 2100:     my $col_fullnames = [];
 2101:     if ($env{'form.handgrade'} eq 'yes') {
 2102: 	(my $sub_result,$fullname,$col_fullnames)=
 2103: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2104: 				 $counter);
 2105: 	$result.=$sub_result;
 2106:     }
 2107:     $request->print($result."\n");
 2108:     $request->print('</div>'."\n");
 2109:     # print student answer/submission
 2110:     # Options are (1) Handgaded submission only
 2111:     #             (2) Last submission, includes submission that is not handgraded 
 2112:     #                  (for multi-response type part)
 2113:     #             (3) Last submission plus the parts info
 2114:     #             (4) The whole record for this student
 2115:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2116: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2117: 	
 2118: 	my $lastsubonly;
 2119: 
 2120: 	if ($$timestamp eq '') {
 2121: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2122: 	} else {
 2123: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2124: 
 2125: 	    my %seenparts;
 2126: 	    my @part_response_id = &flatten_responseType($responseType);
 2127: 	    foreach my $part (@part_response_id) {
 2128: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2129: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2130: 
 2131: 		my ($partid,$respid) = @{ $part };
 2132: 		my $display_part=&get_display_part($partid,$symb);
 2133: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2134: 		    if (exists($seenparts{$partid})) { next; }
 2135: 		    $seenparts{$partid}=1;
 2136: 		    my $submitby='<b>Part:</b> '.$display_part.
 2137: 			' <b>Collaborative submission by:</b> '.
 2138: 			'<a href="javascript:viewSubmitter(\''.
 2139: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2140: 			'\');" target="_self">'.
 2141: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2142: 		    $request->print($submitby);
 2143: 		    next;
 2144: 		}
 2145: 		my $responsetype = $responseType->{$partid}->{$respid};
 2146: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2147: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2148: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2149: 			' )</span>&nbsp; &nbsp;'.
 2150: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2151: 		    next;
 2152: 		}
 2153: 		foreach my $submission (@$string) {
 2154: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2155: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2156: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2157: 		    # Similarity check
 2158: 		    my $similar='';
 2159: 		    if($env{'form.checkPlag'}){
 2160: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2161: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2162: 			if ($osim) {
 2163: 			    $osim=int($osim*100.0);
 2164: 			    my %old_course_desc = 
 2165: 				&Apache::lonnet::coursedescription($ocrsid,
 2166: 								   {'one_time' => 1});
 2167: 
 2168: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2169: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
 2170: 				    $osim,
 2171: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
 2172: 				    $old_course_desc{'description'},
 2173: 				    $old_course_desc{'num'},
 2174: 				    $old_course_desc{'domain'}).
 2175: 				'</span></h3><blockquote><i>'.
 2176: 				&keywords_highlight($oessay).
 2177: 				'</i></blockquote><hr />';
 2178: 			}
 2179: 		    }
 2180: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2181: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2182: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2183: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2184: 			my $display_part=&get_display_part($partid,$symb);
 2185: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2186: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2187: 			    ' )</span>&nbsp; &nbsp;';
 2188: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2189: 			if (@$files) {
 2190: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2191: 			    my $file_counter = 0;
 2192: 			    foreach my $file (@$files) {
 2193: 			        $file_counter++;
 2194: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2195: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
 2196: 			    }
 2197: 			    $lastsubonly.='<br />';
 2198: 			}
 2199: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2200: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2201: 					 $respid,\%record,$order,undef,$uname,$udom);
 2202: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2203: 			$lastsubonly.='</div>';
 2204: 		    }
 2205: 		}
 2206: 	    }
 2207: 	    $lastsubonly.='</div>'."\n";
 2208: 	}
 2209: 	$request->print($lastsubonly);
 2210:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2211: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2212: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2213:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2214: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2215: 								 $env{'request.course.id'},
 2216: 								 $last,'.submission',
 2217: 								 'Apache::grades::keywords_highlight'));
 2218:     }
 2219: 
 2220:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2221: 	.$udom.'" />'."\n");
 2222:     # return if view submission with no grading option
 2223:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2224: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2225: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2226: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2227: 	$toGrade.='</div>'."\n";
 2228: 	if (($env{'form.command'} eq 'submission') || 
 2229: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2230: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2231: 	}
 2232: 	$request->print($toGrade);
 2233: 	return;
 2234:     } else {
 2235: 	$request->print('</div>'."\n");
 2236:     }
 2237: 
 2238:     # essay grading message center
 2239:     if ($env{'form.handgrade'} eq 'yes') {
 2240: 	my $result='<div class="LC_grade_message_center">';
 2241:     
 2242: 	$result.='<div class="LC_grade_message_center_header">'.
 2243: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2244: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2245: 	my $msgfor = $givenn.' '.$lastname;
 2246: 	if (scalar(@$col_fullnames) > 0) {
 2247: 	    my $lastone = pop(@$col_fullnames);
 2248: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2249: 	}
 2250: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2251: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2252: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2253: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2254: 	    ',\''.$msgfor.'\');" target="_self">'.
 2255: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2256: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2257: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2258: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2259: 	    '<br />&nbsp;('.
 2260: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2261: 	$result.='</div></div>';
 2262: 	$request->print($result);
 2263:     }
 2264: 
 2265:     my %seen = ();
 2266:     my @partlist;
 2267:     my @gradePartRespid;
 2268:     my @part_response_id = &flatten_responseType($responseType);
 2269:     $request->print('<div class="LC_grade_assign">'.
 2270: 		    
 2271: 		    '<div class="LC_grade_assign_header">'.
 2272: 		    &mt('Assign Grades').'</div>'.
 2273: 		    '<div class="LC_grade_assign_body">');
 2274:     foreach my $part_response_id (@part_response_id) {
 2275:     	my ($partid,$respid) = @{ $part_response_id };
 2276: 	my $part_resp = join('_',@{ $part_response_id });
 2277: 	next if ($seen{$partid} > 0);
 2278: 	$seen{$partid}++;
 2279: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2280: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2281: 	push(@partlist,$partid);
 2282: 	push(@gradePartRespid,$partid.'.'.$respid);
 2283: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2284:     }
 2285:     $request->print('</div></div>');
 2286: 
 2287:     $request->print('<div class="LC_grade_info_links">');
 2288:     if ($perm{'vgr'}) {
 2289: 	$request->print(
 2290: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2291: 						   $uname,$udom,'check'));
 2292:     }
 2293:     if ($perm{'opa'}) {
 2294: 	$request->print(
 2295: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2296: 					 $uname,$udom,$symb,'check'));
 2297:     }
 2298:     $request->print('</div>');
 2299: 
 2300:     $result='<input type="hidden" name="partlist'.$counter.
 2301: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2302:     $result.='<input type="hidden" name="gradePartRespid'.
 2303: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2304:     my $ctr = 0;
 2305:     while ($ctr < scalar(@partlist)) {
 2306: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2307: 	    $partlist[$ctr].'" />'."\n";
 2308: 	$ctr++;
 2309:     }
 2310:     $request->print($result.''."\n");
 2311: 
 2312: # Done with printing info for one student
 2313: 
 2314:     $request->print('</div>');#LC_grade_show_user_body
 2315:     $request->print('</div>');#LC_grade_show_user
 2316: 
 2317: 
 2318:     # print end of form
 2319:     if ($counter == $total) {
 2320: 	my $endform='<table border="0"><tr><td>'."\n";
 2321: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2322: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2323: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2324: 	my $ntstu ='<select name="NTSTU">'.
 2325: 	    '<option>1</option><option>2</option>'.
 2326: 	    '<option>3</option><option>5</option>'.
 2327: 	    '<option>7</option><option>10</option></select>'."\n";
 2328: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2329: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2330:         $endform.=&mt('[_1]student(s)',$ntstu);
 2331: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2332: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2333: 	    '<input type="button" value="'.&mt('Next').'" '.
 2334: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2335: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2336:         $endform.="<input type='hidden' value='".&get_increment().
 2337:             "' name='increment' />";
 2338: 	$endform.='</td></tr></table></form>';
 2339: 	$endform.=&show_grading_menu_form($symb);
 2340: 	$request->print($endform);
 2341:     }
 2342:     return '';
 2343: }
 2344: 
 2345: sub check_collaborators {
 2346:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2347:     my ($result,@col_fullnames);
 2348:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2349:     foreach my $part (keys(%$handgrade)) {
 2350: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2351: 					'.maxcollaborators',
 2352: 					$symb,$udom,$uname);
 2353: 	next if ($ncol <= 0);
 2354: 	$part =~ s/\_/\./g;
 2355: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2356: 	my (@good_collaborators, @bad_collaborators);
 2357: 	foreach my $possible_collaborator
 2358: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2359: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2360: 	    next if ($possible_collaborator eq '');
 2361: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2362: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2363: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2364: 	    # Doing this grep allows 'fuzzy' specification
 2365: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2366: 			       keys(%$classlist));
 2367: 	    if (! scalar(@matches)) {
 2368: 		push(@bad_collaborators, $possible_collaborator);
 2369: 	    } else {
 2370: 		push(@good_collaborators, @matches);
 2371: 	    }
 2372: 	}
 2373: 	if (scalar(@good_collaborators) != 0) {
 2374: 	    $result.='<br />'.&mt('Collaborators: ');
 2375: 	    foreach my $name (@good_collaborators) {
 2376: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2377: 		push(@col_fullnames, $givenn.' '.$lastname);
 2378: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2379: 	    }
 2380: 	    $result.='<br />'."\n";
 2381: 	    my ($part)=split(/\./,$part);
 2382: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2383: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2384: 		"\n";
 2385: 	}
 2386: 	if (scalar(@bad_collaborators) > 0) {
 2387: 	    $result.='<div class="LC_warning">';
 2388: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2389: 	    $result .= '</div>';
 2390: 	}         
 2391: 	if (scalar(@bad_collaborators > $ncol)) {
 2392: 	    $result .= '<div class="LC_warning">';
 2393: 	    $result .= &mt('This student has submitted too many '.
 2394: 		'collaborators.  Maximum is [_1].',$ncol);
 2395: 	    $result .= '</div>';
 2396: 	}
 2397:     }
 2398:     return ($result,$fullname,\@col_fullnames);
 2399: }
 2400: 
 2401: #--- Retrieve the last submission for all the parts
 2402: sub get_last_submission {
 2403:     my ($returnhash)=@_;
 2404:     my (@string,$timestamp);
 2405:     if ($$returnhash{'version'}) {
 2406: 	my %lasthash=();
 2407: 	my ($version);
 2408: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2409: 	    foreach my $key (sort(split(/\:/,
 2410: 					$$returnhash{$version.':keys'}))) {
 2411: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2412: 		$timestamp = 
 2413: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2414: 	    }
 2415: 	}
 2416: 	foreach my $key (keys(%lasthash)) {
 2417: 	    next if ($key !~ /\.submission$/);
 2418: 
 2419: 	    my ($partid,$foo) = split(/submission$/,$key);
 2420: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2421: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2422: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2423: 	}
 2424:     }
 2425:     if (!@string) {
 2426: 	$string[0] =
 2427: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2428:     }
 2429:     return (\@string,\$timestamp);
 2430: }
 2431: 
 2432: #--- High light keywords, with style choosen by user.
 2433: sub keywords_highlight {
 2434:     my $string    = shift;
 2435:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2436:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2437:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2438:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2439:     foreach my $keyword (@keylist) {
 2440: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2441:     }
 2442:     return $string;
 2443: }
 2444: 
 2445: #--- Called from submission routine
 2446: sub processHandGrade {
 2447:     my ($request) = shift;
 2448:     my $symb   = &get_symb($request);
 2449:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2450:     my $button = $env{'form.gradeOpt'};
 2451:     my $ngrade = $env{'form.NCT'};
 2452:     my $ntstu  = $env{'form.NTSTU'};
 2453:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2454:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2455: 
 2456:     if ($button eq 'Save & Next') {
 2457: 	my $ctr = 0;
 2458: 	while ($ctr < $ngrade) {
 2459: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2460: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2461: 	    if ($errorflag eq 'no_score') {
 2462: 		$ctr++;
 2463: 		next;
 2464: 	    }
 2465: 	    if ($errorflag eq 'not_allowed') {
 2466: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2467: 		$ctr++;
 2468: 		next;
 2469: 	    }
 2470: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2471: 	    my ($subject,$message,$msgstatus) = ('','','');
 2472: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2473:             my ($feedurl,$showsymb) =
 2474: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2475: 	    my $messagetail;
 2476: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2477: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2478: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2479: 		$subject.=' ['.$restitle.']';
 2480: 		my (@msgnum) = split(/,/,$includemsg);
 2481: 		foreach (@msgnum) {
 2482: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2483: 		}
 2484: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2485: 		if ($env{'form.withgrades'.$ctr}) {
 2486: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2487: 		    $messagetail = " for <a href=\"".
 2488: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2489: 		}
 2490: 		$msgstatus = 
 2491:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2492: 						     $message.$messagetail,
 2493:                                                      undef,$feedurl,undef,
 2494:                                                      undef,undef,$showsymb,
 2495:                                                      $restitle);
 2496: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
 2497: 				$msgstatus);
 2498: 	    }
 2499: 	    if ($env{'form.collaborator'.$ctr}) {
 2500: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2501: 		foreach my $collabstr (@collabstrs) {
 2502: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2503: 		    foreach my $collaborator (@collaborators) {
 2504: 			my ($errorflag,$pts,$wgt) = 
 2505: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2506: 					   $env{'form.unamedom'.$ctr},$part);
 2507: 			if ($errorflag eq 'not_allowed') {
 2508: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2509: 			    next;
 2510: 			} elsif ($message ne '') {
 2511: 			    my ($baseurl,$showsymb) = 
 2512: 				&get_feedurl_and_symb($symb,$collaborator,
 2513: 						      $udom);
 2514: 			    if ($env{'form.withgrades'.$ctr}) {
 2515: 				$messagetail = " for <a href=\"".
 2516:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2517: 			    }
 2518: 			    $msgstatus = 
 2519: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2520: 			}
 2521: 		    }
 2522: 		}
 2523: 	    }
 2524: 	    $ctr++;
 2525: 	}
 2526:     }
 2527: 
 2528:     if ($env{'form.handgrade'} eq 'yes') {
 2529: 	# Keywords sorted in alphabatical order
 2530: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2531: 	my %keyhash = ();
 2532: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2533: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2534: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2535: 	$env{'form.keywords'} = join(' ',@keywords);
 2536: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2537: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2538: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2539: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2540: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2541: 
 2542: 	# message center - Order of message gets changed. Blank line is eliminated.
 2543: 	# New messages are saved in env for the next student.
 2544: 	# All messages are saved in nohist_handgrade.db
 2545: 	my ($ctr,$idx) = (1,1);
 2546: 	while ($ctr <= $env{'form.savemsgN'}) {
 2547: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2548: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2549: 		$idx++;
 2550: 	    }
 2551: 	    $ctr++;
 2552: 	}
 2553: 	$ctr = 0;
 2554: 	while ($ctr < $ngrade) {
 2555: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2556: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2557: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2558: 		$idx++;
 2559: 	    }
 2560: 	    $ctr++;
 2561: 	}
 2562: 	$env{'form.savemsgN'} = --$idx;
 2563: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2564: 	my $putresult = &Apache::lonnet::put
 2565: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2566:     }
 2567:     # Called by Save & Refresh from Highlight Attribute Window
 2568:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2569:     if ($env{'form.refresh'} eq 'on') {
 2570: 	my ($ctr,$total) = (0,0);
 2571: 	while ($ctr < $ngrade) {
 2572: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2573: 	    $ctr++;
 2574: 	}
 2575: 	$env{'form.NTSTU'}=$ngrade;
 2576: 	$ctr = 0;
 2577: 	while ($ctr < $total) {
 2578: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2579: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2580: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2581: 	    &submission($request,$ctr,$total-1);
 2582: 	    $ctr++;
 2583: 	}
 2584: 	return '';
 2585:     }
 2586: 
 2587: # Go directly to grade student - from submission or link from chart page
 2588:     if ($button eq 'Grade Student') {
 2589: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2590: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2591: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2592: 	$env{'form.fullname'} = $$fullname{$processUser};
 2593: 	&submission($request,0,0);
 2594: 	return '';
 2595:     }
 2596: 
 2597:     # Get the next/previous one or group of students
 2598:     my $firststu = $env{'form.unamedom0'};
 2599:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2600:     my $ctr = 2;
 2601:     while ($laststu eq '') {
 2602: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2603: 	$ctr++;
 2604: 	$laststu = $firststu if ($ctr > $ngrade);
 2605:     }
 2606: 
 2607:     my (@parsedlist,@nextlist);
 2608:     my ($nextflg) = 0;
 2609:     foreach my $item (sort 
 2610: 	     {
 2611: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2612: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2613: 		 }
 2614: 		 return $a cmp $b;
 2615: 	     } (keys(%$fullname))) {
 2616: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2617: 	    push(@parsedlist,$item);
 2618: 	}
 2619: 	$nextflg = 1 if ($item eq $laststu);
 2620: 	if ($button eq 'Previous') {
 2621: 	    last if ($item eq $firststu);
 2622: 	    push(@parsedlist,$item);
 2623: 	}
 2624:     }
 2625:     $ctr = 0;
 2626:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2627:     my $res_error;
 2628:     my ($partlist) = &response_type($symb,\$res_error);
 2629:     if ($res_error) {
 2630:         $request->print(&navmap_errormsg());
 2631:         return;
 2632:     }
 2633:     foreach my $student (@parsedlist) {
 2634: 	my $submitonly=$env{'form.submitonly'};
 2635: 	my ($uname,$udom) = split(/:/,$student);
 2636: 	
 2637: 	if ($submitonly eq 'queued') {
 2638: 	    my %queue_status = 
 2639: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2640: 							$udom,$uname);
 2641: 	    next if (!defined($queue_status{'gradingqueue'}));
 2642: 	}
 2643: 
 2644: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2645: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2646: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2647: 	    my $submitted = 0;
 2648: 	    my $ungraded = 0;
 2649: 	    my $incorrect = 0;
 2650: 	    foreach my $item (keys(%status)) {
 2651: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2652: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2653: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2654: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2655: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2656: 		    $submitted = 0;
 2657: 		}
 2658: 	    }
 2659: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2660: 				     $submitonly eq 'incorrect' ||
 2661: 				     $submitonly eq 'graded'));
 2662: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2663: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2664: 	}
 2665: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2666: 	last if ($ctr == $ntstu);
 2667: 	$ctr++;
 2668:     }
 2669: 
 2670:     $ctr = 0;
 2671:     my $total = scalar(@nextlist)-1;
 2672: 
 2673:     foreach (sort(@nextlist)) {
 2674: 	my ($uname,$udom,$submitter) = split(/:/);
 2675: 	$env{'form.student'}  = $uname;
 2676: 	$env{'form.userdom'}  = $udom;
 2677: 	$env{'form.fullname'} = $$fullname{$_};
 2678: 	&submission($request,$ctr,$total);
 2679: 	$ctr++;
 2680:     }
 2681:     if ($total < 0) {
 2682: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2683: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2684: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2685: 	$the_end.=&show_grading_menu_form($symb);
 2686: 	$request->print($the_end);
 2687:     }
 2688:     return '';
 2689: }
 2690: 
 2691: #---- Save the score and award for each student, if changed
 2692: sub saveHandGrade {
 2693:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2694:     my @version_parts;
 2695:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2696: 					   $env{'request.course.id'});
 2697:     if (!&canmodify($usec)) { return('not_allowed'); }
 2698:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2699:     my @parts_graded;
 2700:     my %newrecord  = ();
 2701:     my ($pts,$wgt) = ('','');
 2702:     my %aggregate = ();
 2703:     my $aggregateflag = 0;
 2704:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2705:     foreach my $new_part (@parts) {
 2706: 	#collaborator ($submi may vary for different parts
 2707: 	if ($submitter && $new_part ne $part) { next; }
 2708: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2709: 	if ($dropMenu eq 'excused') {
 2710: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2711: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2712: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2713: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2714: 		}
 2715: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2716: 	    }
 2717: 	} elsif ($dropMenu eq 'reset status'
 2718: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2719: 	    foreach my $key (keys(%record)) {
 2720: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2721: 	    }
 2722: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2723: 		"$env{'user.name'}:$env{'user.domain'}";
 2724:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2725: 
 2726:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2727: 					       [$new_part]);
 2728:             my $aggtries =$totaltries;
 2729:             if ($last_resets{$new_part}) {
 2730:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2731: 					   $new_part);
 2732:             }
 2733: 
 2734:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2735:             if ($aggtries > 0) {
 2736:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2737:                 $aggregateflag = 1;
 2738:             }
 2739: 	} elsif ($dropMenu eq '') {
 2740: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2741: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2742: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2743: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2744: 		next;
 2745: 	    }
 2746: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2747: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2748: 	    my $partial= $pts/$wgt;
 2749: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2750: 		#do not update score for part if not changed.
 2751:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2752: 		next;
 2753: 	    } else {
 2754: 	        push(@parts_graded,$new_part);
 2755: 	    }
 2756: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2757: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2758: 	    }
 2759: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2760: 	    if ($partial == 0) {
 2761: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2762: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2763: 		}
 2764: 	    } else {
 2765: 		if ($record{$reckey} ne 'correct_by_override') {
 2766: 		    $newrecord{$reckey} = 'correct_by_override';
 2767: 		}
 2768: 	    }	    
 2769: 	    if ($submitter && 
 2770: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2771: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2772: 	    }
 2773: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2774: 		"$env{'user.name'}:$env{'user.domain'}";
 2775: 	}
 2776: 	# unless problem has been graded, set flag to version the submitted files
 2777: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2778: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2779: 	        $dropMenu eq 'reset status')
 2780: 	   {
 2781: 	    push(@version_parts,$new_part);
 2782: 	}
 2783:     }
 2784:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2785:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2786: 
 2787:     if (%newrecord) {
 2788:         if (@version_parts) {
 2789:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2790:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2791: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2792: 	    foreach my $new_part (@version_parts) {
 2793: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2794: 				$new_part,\%newrecord);
 2795: 	    }
 2796:         }
 2797: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2798: 				$env{'request.course.id'},$domain,$stuname);
 2799: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2800: 				     $cdom,$cnum,$domain,$stuname);
 2801:     }
 2802:     if ($aggregateflag) {
 2803:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2804: 			      $cdom,$cnum);
 2805:     }
 2806:     return ('',$pts,$wgt);
 2807: }
 2808: 
 2809: sub check_and_remove_from_queue {
 2810:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2811:     my @ungraded_parts;
 2812:     foreach my $part (@{$parts}) {
 2813: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2814: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2815: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2816: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2817: 		) {
 2818: 	    push(@ungraded_parts, $part);
 2819: 	}
 2820:     }
 2821:     if ( !@ungraded_parts ) {
 2822: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2823: 					       $cnum,$domain,$stuname);
 2824:     }
 2825: }
 2826: 
 2827: sub handback_files {
 2828:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2829:     my $portfolio_root = '/userfiles/portfolio';
 2830:     my $res_error;
 2831:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 2832:     if ($res_error) {
 2833:         $request->print('<br />'.&navmap_errormsg().'<br />');
 2834:         return;
 2835:     }
 2836:     my @part_response_id = &flatten_responseType($responseType);
 2837:     foreach my $part_response_id (@part_response_id) {
 2838:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2839: 	my $part_resp = join('_',@{ $part_response_id });
 2840:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2841:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2842:                 my $file_counter = 1;
 2843: 		my $file_msg;
 2844:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2845:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2846:                     my ($directory,$answer_file) = 
 2847:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2848:                     my ($answer_name,$answer_ver,$answer_ext) =
 2849: 		        &file_name_version_ext($answer_file);
 2850: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2851:                     my $getpropath = 1;
 2852: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2853: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2854:                     # fix file name
 2855:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2856:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2857:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2858:             	                                $save_file_name);
 2859:                     if ($result !~ m|^/uploaded/|) {
 2860:                         $request->print('<br /><span class="LC_error">'.
 2861:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2862:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2863:                                         '</span>');
 2864:                     } else {
 2865:                         # mark the file as read only
 2866:                         my @files = ($save_file_name);
 2867:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2868:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2869: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2870: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2871: 			}
 2872:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2873: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2874: 
 2875:                     }
 2876:                     $request->print("<br />".$fname." will be the uploaded file name");
 2877:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2878:                     $file_counter++;
 2879:                 }
 2880: 		my $subject = "File Handed Back by Instructor ";
 2881: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2882: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2883: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2884: 		$message .= " and can be found in your portfolio space.";
 2885: 		my ($feedurl,$showsymb) = 
 2886: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2887:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2888: 		my $msgstatus = 
 2889:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2890: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2891:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2892:             }
 2893:         }
 2894:     return;
 2895: }
 2896: 
 2897: sub get_feedurl_and_symb {
 2898:     my ($symb,$uname,$udom) = @_;
 2899:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2900:     $url = &Apache::lonnet::clutter($url);
 2901:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2902: 					$symb,$udom,$uname);
 2903:     if ($encrypturl =~ /^yes$/i) {
 2904: 	&Apache::lonenc::encrypted(\$url,1);
 2905: 	&Apache::lonenc::encrypted(\$symb,1);
 2906:     }
 2907:     return ($url,$symb);
 2908: }
 2909: 
 2910: sub get_submitted_files {
 2911:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2912:     my @files;
 2913:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2914:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2915:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2916:     	    push(@files,$file_url.$file);
 2917:         }
 2918:     }
 2919:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2920:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2921:     }
 2922:     return (\@files);
 2923: }
 2924: 
 2925: # ----------- Provides number of tries since last reset.
 2926: sub get_num_tries {
 2927:     my ($record,$last_reset,$part) = @_;
 2928:     my $timestamp = '';
 2929:     my $num_tries = 0;
 2930:     if ($$record{'version'}) {
 2931:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2932:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2933:                 $timestamp = $$record{$version.':timestamp'};
 2934:                 if ($timestamp > $last_reset) {
 2935:                     $num_tries ++;
 2936:                 } else {
 2937:                     last;
 2938:                 }
 2939:             }
 2940:         }
 2941:     }
 2942:     return $num_tries;
 2943: }
 2944: 
 2945: # ----------- Determine decrements required in aggregate totals 
 2946: sub decrement_aggs {
 2947:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2948:     my %decrement = (
 2949:                         attempts => 0,
 2950:                         users => 0,
 2951:                         correct => 0
 2952:                     );
 2953:     $decrement{'attempts'} = $aggtries;
 2954:     if ($solvedstatus =~ /^correct/) {
 2955:         $decrement{'correct'} = 1;
 2956:     }
 2957:     if ($aggtries == $totaltries) {
 2958:         $decrement{'users'} = 1;
 2959:     }
 2960:     foreach my $type (keys(%decrement)) {
 2961:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2962:     }
 2963:     return;
 2964: }
 2965: 
 2966: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2967: sub get_last_resets {
 2968:     my ($symb,$courseid,$partids) =@_;
 2969:     my %last_resets;
 2970:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2971:     my $cname = $env{'course.'.$courseid.'.num'};
 2972:     my @keys;
 2973:     foreach my $part (@{$partids}) {
 2974: 	push(@keys,"$symb\0$part\0resettime");
 2975:     }
 2976:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2977: 				     $cdom,$cname);
 2978:     foreach my $part (@{$partids}) {
 2979: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2980:     }
 2981:     return %last_resets;
 2982: }
 2983: 
 2984: # ----------- Handles creating versions for portfolio files as answers
 2985: sub version_portfiles {
 2986:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2987:     my $version_parts = join('|',@$v_flag);
 2988:     my @returned_keys;
 2989:     my $parts = join('|', @$parts_graded);
 2990:     my $portfolio_root = '/userfiles/portfolio';
 2991:     foreach my $key (keys(%$record)) {
 2992:         my $new_portfiles;
 2993:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2994:             my @versioned_portfiles;
 2995:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2996:             foreach my $file (@portfiles) {
 2997:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2998:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2999: 		my ($answer_name,$answer_ver,$answer_ext) =
 3000: 		    &file_name_version_ext($answer_file);
 3001:                 my $getpropath = 1;    
 3002:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3003:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3004:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3005:                 if ($new_answer ne 'problem getting file') {
 3006:                     push(@versioned_portfiles, $directory.$new_answer);
 3007:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3008:                         [$directory.$new_answer],
 3009:                         [$symb,$env{'request.course.id'},'graded']);
 3010:                 }
 3011:             }
 3012:             $$record{$key} = join(',',@versioned_portfiles);
 3013:             push(@returned_keys,$key);
 3014:         }
 3015:     } 
 3016:     return (@returned_keys);   
 3017: }
 3018: 
 3019: sub get_next_version {
 3020:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3021:     my $version;
 3022:     foreach my $row (@$dir_list) {
 3023:         my ($file) = split(/\&/,$row,2);
 3024:         my ($file_name,$file_version,$file_ext) =
 3025: 	    &file_name_version_ext($file);
 3026:         if (($file_name eq $answer_name) && 
 3027: 	    ($file_ext eq $answer_ext)) {
 3028:                 # gets here if filename and extension match, regardless of version
 3029:                 if ($file_version ne '') {
 3030:                 # a versioned file is found  so save it for later
 3031:                 if ($file_version > $version) {
 3032: 		    $version = $file_version;
 3033: 	        }
 3034:             }
 3035:         }
 3036:     } 
 3037:     $version ++;
 3038:     return($version);
 3039: }
 3040: 
 3041: sub version_selected_portfile {
 3042:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3043:     my ($answer_name,$answer_ver,$answer_ext) =
 3044:         &file_name_version_ext($file_name);
 3045:     my $new_answer;
 3046:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3047:     if($env{'form.copy'} eq '-1') {
 3048:         $new_answer = 'problem getting file';
 3049:     } else {
 3050:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3051:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3052:                             $stu_name,$domain,'copy',
 3053: 		        '/portfolio'.$directory.$new_answer);
 3054:     }    
 3055:     return ($new_answer);
 3056: }
 3057: 
 3058: sub file_name_version_ext {
 3059:     my ($file)=@_;
 3060:     my @file_parts = split(/\./, $file);
 3061:     my ($name,$version,$ext);
 3062:     if (@file_parts > 1) {
 3063: 	$ext=pop(@file_parts);
 3064: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3065: 	    $version=pop(@file_parts);
 3066: 	}
 3067: 	$name=join('.',@file_parts);
 3068:     } else {
 3069: 	$name=join('.',@file_parts);
 3070:     }
 3071:     return($name,$version,$ext);
 3072: }
 3073: 
 3074: #--------------------------------------------------------------------------------------
 3075: #
 3076: #-------------------------- Next few routines handles grading by section or whole class
 3077: #
 3078: #--- Javascript to handle grading by section or whole class
 3079: sub viewgrades_js {
 3080:     my ($request) = shift;
 3081: 
 3082:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3083:     $request->print(<<VIEWJAVASCRIPT);
 3084: <script type="text/javascript" language="javascript">
 3085:    function writePoint(partid,weight,point) {
 3086: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3087: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3088: 	if (point == "textval") {
 3089: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3090: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3091: 		alert("$alertmsg"+parseFloat(point));
 3092: 		var resetbox = false;
 3093: 		for (var i=0; i<radioButton.length; i++) {
 3094: 		    if (radioButton[i].checked) {
 3095: 			textbox.value = i;
 3096: 			resetbox = true;
 3097: 		    }
 3098: 		}
 3099: 		if (!resetbox) {
 3100: 		    textbox.value = "";
 3101: 		}
 3102: 		return;
 3103: 	    }
 3104: 	    if (parseFloat(point) > parseFloat(weight)) {
 3105: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3106: 				   ") greater than the weight for the part. Accept?");
 3107: 		if (resp == false) {
 3108: 		    textbox.value = "";
 3109: 		    return;
 3110: 		}
 3111: 	    }
 3112: 	    for (var i=0; i<radioButton.length; i++) {
 3113: 		radioButton[i].checked=false;
 3114: 		if (parseFloat(point) == i) {
 3115: 		    radioButton[i].checked=true;
 3116: 		}
 3117: 	    }
 3118: 
 3119: 	} else {
 3120: 	    textbox.value = parseFloat(point);
 3121: 	}
 3122: 	for (i=0;i<document.classgrade.total.value;i++) {
 3123: 	    var user = document.classgrade["ctr"+i].value;
 3124: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3125: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3126: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3127: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3128: 	    if (saveval != "correct") {
 3129: 		scorename.value = point;
 3130: 		if (selname[0].selected != true) {
 3131: 		    selname[0].selected = true;
 3132: 		}
 3133: 	    }
 3134: 	}
 3135: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3136:     }
 3137: 
 3138:     function writeRadText(partid,weight) {
 3139: 	var selval   = document.classgrade["SELVAL_"+partid];
 3140: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3141:         var override = document.classgrade["FORCE_"+partid].checked;
 3142: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3143: 	if (selval[1].selected || selval[2].selected) {
 3144: 	    for (var i=0; i<radioButton.length; i++) {
 3145: 		radioButton[i].checked=false;
 3146: 
 3147: 	    }
 3148: 	    textbox.value = "";
 3149: 
 3150: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3151: 		var user = document.classgrade["ctr"+i].value;
 3152: 		user = user.replace(new RegExp(':', 'g'),"_");
 3153: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3154: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3155: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3156: 		if ((saveval != "correct") || override) {
 3157: 		    scorename.value = "";
 3158: 		    if (selval[1].selected) {
 3159: 			selname[1].selected = true;
 3160: 		    } else {
 3161: 			selname[2].selected = true;
 3162: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3163: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3164: 		    }
 3165: 		}
 3166: 	    }
 3167: 	} else {
 3168: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3169: 		var user = document.classgrade["ctr"+i].value;
 3170: 		user = user.replace(new RegExp(':', 'g'),"_");
 3171: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3172: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3173: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3174: 		if ((saveval != "correct") || override) {
 3175: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3176: 		    selname[0].selected = true;
 3177: 		}
 3178: 	    }
 3179: 	}	    
 3180:     }
 3181: 
 3182:     function changeSelect(partid,user) {
 3183: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3184: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3185: 	var point  = textbox.value;
 3186: 	var weight = document.classgrade["weight_"+partid].value;
 3187: 
 3188: 	if (isNaN(point) || parseFloat(point) < 0) {
 3189: 	    alert("$alertmsg"+parseFloat(point));
 3190: 	    textbox.value = "";
 3191: 	    return;
 3192: 	}
 3193: 	if (parseFloat(point) > parseFloat(weight)) {
 3194: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3195: 			       ") greater than the weight of the part. Accept?");
 3196: 	    if (resp == false) {
 3197: 		textbox.value = "";
 3198: 		return;
 3199: 	    }
 3200: 	}
 3201: 	selval[0].selected = true;
 3202:     }
 3203: 
 3204:     function changeOneScore(partid,user) {
 3205: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3206: 	if (selval[1].selected || selval[2].selected) {
 3207: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3208: 	    if (selval[2].selected) {
 3209: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3210: 	    }
 3211:         }
 3212:     }
 3213: 
 3214:     function resetEntry(numpart) {
 3215: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3216: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3217: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3218: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3219: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3220: 	    for (var i=0; i<radioButton.length; i++) {
 3221: 		radioButton[i].checked=false;
 3222: 
 3223: 	    }
 3224: 	    textbox.value = "";
 3225: 	    selval[0].selected = true;
 3226: 
 3227: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3228: 		var user = document.classgrade["ctr"+i].value;
 3229: 		user = user.replace(new RegExp(':', 'g'),"_");
 3230: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3231: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3232: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3233: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3234: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3235: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3236: 		if (saveselval == "excused") {
 3237: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3238: 		} else {
 3239: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3240: 		}
 3241: 	    }
 3242: 	}
 3243:     }
 3244: 
 3245: </script>
 3246: VIEWJAVASCRIPT
 3247: }
 3248: 
 3249: #--- show scores for a section or whole class w/ option to change/update a score
 3250: sub viewgrades {
 3251:     my ($request) = shift;
 3252:     &viewgrades_js($request);
 3253: 
 3254:     my ($symb) = &get_symb($request);
 3255:     #need to make sure we have the correct data for later EXT calls, 
 3256:     #thus invalidate the cache
 3257:     &Apache::lonnet::devalidatecourseresdata(
 3258:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3259:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3260:     &Apache::lonnet::clear_EXT_cache_status();
 3261: 
 3262:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3263:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3264: 
 3265:     #view individual student submission form - called using Javascript viewOneStudent
 3266:     $result.=&jscriptNform($symb);
 3267: 
 3268:     #beginning of class grading form
 3269:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3270:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3271: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3272: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3273: 	&build_section_inputs().
 3274: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3275: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3276: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3277: 
 3278:     my ($common_header,$specific_header);
 3279:     if ($env{'form.section'} eq 'all') {
 3280: 	$common_header = &mt('Assign Common Grade to Class');
 3281:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3282:     } elsif ($env{'form.section'} eq 'none') {
 3283:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3284: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
 3285:     } else {
 3286:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3287:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3288: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3289:     }
 3290:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3291:     #radio buttons/text box for assigning points for a section or class.
 3292:     #handles different parts of a problem
 3293:     my $res_error;
 3294:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 3295:     if ($res_error) {
 3296:         return &navmap_errormsg();
 3297:     }
 3298:     my %weight = ();
 3299:     my $ctsparts = 0;
 3300:     my %seen = ();
 3301:     my @part_response_id = &flatten_responseType($responseType);
 3302:     foreach my $part_response_id (@part_response_id) {
 3303:     	my ($partid,$respid) = @{ $part_response_id };
 3304: 	my $part_resp = join('_',@{ $part_response_id });
 3305: 	next if $seen{$partid};
 3306: 	$seen{$partid}++;
 3307: 	my $handgrade=$$handgrade{$part_resp};
 3308: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3309: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3310: 
 3311: 	my $display_part=&get_display_part($partid,$symb);
 3312: 	my $radio.='<table border="0"><tr>';  
 3313: 	my $ctr = 0;
 3314: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3315: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3316: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3317: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3318: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3319: 	    $ctr++;
 3320: 	}
 3321: 	$radio.='</tr></table>';
 3322: 	my $line = '<input type="text" name="TEXTVAL_'.
 3323: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3324: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3325: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3326: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3327: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3328: 		$weight{$partid}.')"> '.
 3329: 	    '<option selected="selected"> </option>'.
 3330: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3331: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3332: 	    '</select></td>'.
 3333:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3334: 	$line.='<input type="hidden" name="partid_'.
 3335: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3336: 	$line.='<input type="hidden" name="weight_'.
 3337: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3338: 
 3339: 	$result.=
 3340: 	    &Apache::loncommon::start_data_table_row()."\n".
 3341: 	    '<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>'.
 3342: 	    &Apache::loncommon::end_data_table_row()."\n";
 3343: 	$ctsparts++;
 3344:     }
 3345:     $result.=&Apache::loncommon::end_data_table()."\n".
 3346: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3347:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3348: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3349: 
 3350:     #table listing all the students in a section/class
 3351:     #header of table
 3352:     $result.= '<h3>'.$specific_header.'</h3>'.
 3353:               &Apache::loncommon::start_data_table().
 3354: 	      &Apache::loncommon::start_data_table_header_row().
 3355: 	      '<th>'.&mt('No.').'</th>'.
 3356: 	      '<th>'.&nameUserString('header')."</th>\n";
 3357:     my $partserror;
 3358:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3359:     if ($partserror) {
 3360:         return &navmap_errormsg();
 3361:     }
 3362:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3363:     my @partids = ();
 3364:     foreach my $part (@parts) {
 3365: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3366:         my $narrowtext = &mt('Tries');
 3367: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3368: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3369: 	my ($partid) = &split_part_type($part);
 3370:         push(@partids,$partid);
 3371: 	my $display_part=&get_display_part($partid,$symb);
 3372: 	if ($display =~ /^Partial Credit Factor/) {
 3373: 	    $result.='<th>'.
 3374: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3375: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3376: 	    next;
 3377: 	    
 3378: 	} else {
 3379: 	    if ($display =~ /Problem Status/) {
 3380: 		my $grade_status_mt = &mt('Grade Status');
 3381: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3382: 	    }
 3383: 	    my $part_mt = &mt('Part:');
 3384: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3385: 	}
 3386: 
 3387: 	$result.='<th>'.$display.'</th>'."\n";
 3388:     }
 3389:     $result.=&Apache::loncommon::end_data_table_header_row();
 3390: 
 3391:     my %last_resets = 
 3392: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3393: 
 3394:     #get info for each student
 3395:     #list all the students - with points and grade status
 3396:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3397:     my $ctr = 0;
 3398:     foreach (sort 
 3399: 	     {
 3400: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3401: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3402: 		 }
 3403: 		 return $a cmp $b;
 3404: 	     } (keys(%$fullname))) {
 3405: 	$ctr++;
 3406: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3407: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3408:     }
 3409:     $result.=&Apache::loncommon::end_data_table();
 3410:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3411:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3412: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3413:     if (scalar(%$fullname) eq 0) {
 3414: 	my $colspan=3+scalar(@parts);
 3415: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3416:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3417: 	$result='<span class="LC_warning">'.
 3418: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3419: 	        $section_display, $stu_status).
 3420: 	    '</span>';
 3421:     }
 3422:     $result.=&show_grading_menu_form($symb);
 3423:     return $result;
 3424: }
 3425: 
 3426: #--- call by previous routine to display each student
 3427: sub viewstudentgrade {
 3428:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3429:     my ($uname,$udom) = split(/:/,$student);
 3430:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3431:     my %aggregates = (); 
 3432:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3433: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3434: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3435: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3436: 	'\');" target="_self">'.$fullname.'</a> '.
 3437: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3438:     $student=~s/:/_/; # colon doen't work in javascript for names
 3439:     foreach my $apart (@$parts) {
 3440: 	my ($part,$type) = &split_part_type($apart);
 3441: 	my $score=$record{"resource.$part.$type"};
 3442:         $result.='<td align="center">';
 3443:         my ($aggtries,$totaltries);
 3444:         unless (exists($aggregates{$part})) {
 3445: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3446: 
 3447: 	    $aggtries = $totaltries;
 3448:             if ($$last_resets{$part}) {  
 3449:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3450: 					   $part);
 3451:             }
 3452:             $result.='<input type="hidden" name="'.
 3453:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3454:             $result.='<input type="hidden" name="'.
 3455:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3456:             $aggregates{$part} = 1;
 3457:         }
 3458: 	if ($type eq 'awarded') {
 3459: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3460: 	    $result.='<input type="hidden" name="'.
 3461: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3462: 	    $result.='<input type="text" name="'.
 3463: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3464: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3465: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3466: 	} elsif ($type eq 'solved') {
 3467: 	    my ($status,$foo)=split(/_/,$score,2);
 3468: 	    $status = 'nothing' if ($status eq '');
 3469: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3470: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3471: 	    $result.='&nbsp;<select name="'.
 3472: 		'GD_'.$student.'_'.$part.'_solved" '.
 3473: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3474: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3475: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3476: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3477: 	    $result.="</select>&nbsp;</td>\n";
 3478: 	} else {
 3479: 	    $result.='<input type="hidden" name="'.
 3480: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3481: 		    "\n";
 3482: 	    $result.='<input type="text" name="'.
 3483: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3484: 		'value="'.$score.'" size="4" /></td>'."\n";
 3485: 	}
 3486:     }
 3487:     $result.=&Apache::loncommon::end_data_table_row();
 3488:     return $result;
 3489: }
 3490: 
 3491: #--- change scores for all the students in a section/class
 3492: #    record does not get update if unchanged
 3493: sub editgrades {
 3494:     my ($request) = @_;
 3495: 
 3496:     my $symb=&get_symb($request);
 3497:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3498:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3499:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3500:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3501: 
 3502:     my $result= &Apache::loncommon::start_data_table().
 3503: 	&Apache::loncommon::start_data_table_header_row().
 3504: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3505: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3506:     my %scoreptr = (
 3507: 		    'correct'  =>'correct_by_override',
 3508: 		    'incorrect'=>'incorrect_by_override',
 3509: 		    'excused'  =>'excused',
 3510: 		    'ungraded' =>'ungraded_attempted',
 3511: 		    'nothing'  => '',
 3512: 		    );
 3513:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3514: 
 3515:     my (@partid);
 3516:     my %weight = ();
 3517:     my %columns = ();
 3518:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3519: 
 3520:     my $partserror;
 3521:     my (@parts) = sort(&getpartlist($symb,\$partserror));
 3522:     if ($partserror) {
 3523:         return &navmap_errormsg();
 3524:     }
 3525:     my $header;
 3526:     while ($ctr < $env{'form.totalparts'}) {
 3527: 	my $partid = $env{'form.partid_'.$ctr};
 3528: 	push(@partid,$partid);
 3529: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3530: 	$ctr++;
 3531:     }
 3532:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3533:     foreach my $partid (@partid) {
 3534: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3535: 	    '<th align="center">'.&mt('New Score').'</th>';
 3536: 	$columns{$partid}=2;
 3537: 	foreach my $stores (@parts) {
 3538: 	    my ($part,$type) = &split_part_type($stores);
 3539: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3540: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3541: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3542: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3543:             my $narrowtext = &mt('Tries');
 3544: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3545: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3546: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3547: 	    $columns{$partid}+=2;
 3548: 	}
 3549:     }
 3550:     foreach my $partid (@partid) {
 3551: 	my $display_part=&get_display_part($partid,$symb);
 3552: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3553: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3554: 	    '</th>';
 3555: 
 3556:     }
 3557:     $result .= &Apache::loncommon::end_data_table_header_row().
 3558: 	&Apache::loncommon::start_data_table_header_row().
 3559: 	$header.
 3560: 	&Apache::loncommon::end_data_table_header_row();
 3561:     my @noupdate;
 3562:     my ($updateCtr,$noupdateCtr) = (1,1);
 3563:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3564: 	my $line;
 3565: 	my $user = $env{'form.ctr'.$i};
 3566: 	my ($uname,$udom)=split(/:/,$user);
 3567: 	my %newrecord;
 3568: 	my $updateflag = 0;
 3569: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3570: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3571: 	if (!&canmodify($usec)) {
 3572: 	    my $numcols=scalar(@partid)*4+2;
 3573: 	    push(@noupdate,
 3574: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3575: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3576: 	    next;
 3577: 	}
 3578:         my %aggregate = ();
 3579:         my $aggregateflag = 0;
 3580: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3581: 	foreach (@partid) {
 3582: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3583: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3584: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3585: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3586: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3587: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3588: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3589: 	    my $score;
 3590: 	    if ($partial eq '') {
 3591: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3592: 	    } elsif ($partial > 0) {
 3593: 		$score = 'correct_by_override';
 3594: 	    } elsif ($partial == 0) {
 3595: 		$score = 'incorrect_by_override';
 3596: 	    }
 3597: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3598: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3599: 
 3600: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3601: 		"$env{'user.name'}:$env{'user.domain'}";
 3602: 	    if ($dropMenu eq 'reset status' &&
 3603: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3604: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3605: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3606: 		$newrecord{'resource.'.$_.'.award'} = '';
 3607: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3608: 		$updateflag = 1;
 3609:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3610:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3611:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3612:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3613:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3614:                     $aggregateflag = 1;
 3615:                 }
 3616: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3617: 		$updateflag = 1;
 3618: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3619: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3620: 		$rec_update++;
 3621: 	    }
 3622: 
 3623: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3624: 		'<td align="center">'.$awarded.
 3625: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3626: 
 3627: 
 3628: 	    my $partid=$_;
 3629: 	    foreach my $stores (@parts) {
 3630: 		my ($part,$type) = &split_part_type($stores);
 3631: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3632: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3633: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3634: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3635: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3636: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3637: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3638: 		    $updateflag=1;
 3639: 		}
 3640: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3641: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3642: 	    }
 3643: 	}
 3644: 	$line.="\n";
 3645: 
 3646: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3647: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3648: 
 3649: 	if ($updateflag) {
 3650: 	    $count++;
 3651: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3652: 				    $udom,$uname);
 3653: 
 3654: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3655: 					      $cnum,$udom,$uname)) {
 3656: 		# need to figure out if should be in queue.
 3657: 		my %record =  
 3658: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3659: 					     $udom,$uname);
 3660: 		my $all_graded = 1;
 3661: 		my $none_graded = 1;
 3662: 		foreach my $part (@parts) {
 3663: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3664: 			$all_graded = 0;
 3665: 		    } else {
 3666: 			$none_graded = 0;
 3667: 		    }
 3668: 		}
 3669: 
 3670: 		if ($all_graded || $none_graded) {
 3671: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3672: 							   $symb,$cdom,$cnum,
 3673: 							   $udom,$uname);
 3674: 		}
 3675: 	    }
 3676: 
 3677: 	    $result.=&Apache::loncommon::start_data_table_row().
 3678: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3679: 		&Apache::loncommon::end_data_table_row();
 3680: 	    $updateCtr++;
 3681: 	} else {
 3682: 	    push(@noupdate,
 3683: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3684: 	    $noupdateCtr++;
 3685: 	}
 3686:         if ($aggregateflag) {
 3687:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3688: 				  $cdom,$cnum);
 3689:         }
 3690:     }
 3691:     if (@noupdate) {
 3692: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3693: 	my $numcols=scalar(@partid)*4+2;
 3694: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3695: 	    '<td align="center" colspan="'.$numcols.'">'.
 3696: 	    &mt('No Changes Occurred For the Students Below').
 3697: 	    '</td>'.
 3698: 	    &Apache::loncommon::end_data_table_row();
 3699: 	foreach my $line (@noupdate) {
 3700: 	    $result.=
 3701: 		&Apache::loncommon::start_data_table_row().
 3702: 		$line.
 3703: 		&Apache::loncommon::end_data_table_row();
 3704: 	}
 3705:     }
 3706:     $result .= &Apache::loncommon::end_data_table().
 3707: 	&show_grading_menu_form($symb);
 3708:     my $msg = '<p><b>'.
 3709: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3710: 	    $rec_update,$count).'</b><br />'.
 3711: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3712: 	'</b></p>';
 3713:     return $title.$msg.$result;
 3714: }
 3715: 
 3716: sub split_part_type {
 3717:     my ($partstr) = @_;
 3718:     my ($temp,@allparts)=split(/_/,$partstr);
 3719:     my $type=pop(@allparts);
 3720:     my $part=join('_',@allparts);
 3721:     return ($part,$type);
 3722: }
 3723: 
 3724: #------------- end of section for handling grading by section/class ---------
 3725: #
 3726: #----------------------------------------------------------------------------
 3727: 
 3728: 
 3729: #----------------------------------------------------------------------------
 3730: #
 3731: #-------------------------- Next few routines handles grading by csv upload
 3732: #
 3733: #--- Javascript to handle csv upload
 3734: sub csvupload_javascript_reverse_associate {
 3735:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3736:     my $error2=&mt('You need to specify at least one grading field');
 3737:   return(<<ENDPICK);
 3738:   function verify(vf) {
 3739:     var foundsomething=0;
 3740:     var founduname=0;
 3741:     var foundID=0;
 3742:     for (i=0;i<=vf.nfields.value;i++) {
 3743:       tw=eval('vf.f'+i+'.selectedIndex');
 3744:       if (i==0 && tw!=0) { foundID=1; }
 3745:       if (i==1 && tw!=0) { founduname=1; }
 3746:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3747:     }
 3748:     if (founduname==0 && foundID==0) {
 3749: 	alert('$error1');
 3750: 	return;
 3751:     }
 3752:     if (foundsomething==0) {
 3753: 	alert('$error2');
 3754: 	return;
 3755:     }
 3756:     vf.submit();
 3757:   }
 3758:   function flip(vf,tf) {
 3759:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3760:     var i;
 3761:     for (i=0;i<=vf.nfields.value;i++) {
 3762:       //can not pick the same destination field for both name and domain
 3763:       if (((i ==0)||(i ==1)) && 
 3764:           ((tf==0)||(tf==1)) && 
 3765:           (i!=tf) &&
 3766:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3767:         eval('vf.f'+i+'.selectedIndex=0;')
 3768:       }
 3769:     }
 3770:   }
 3771: ENDPICK
 3772: }
 3773: 
 3774: sub csvupload_javascript_forward_associate {
 3775:     my $error1=&mt('You need to specify the username or the student/employee ID');
 3776:     my $error2=&mt('You need to specify at least one grading field');
 3777:   return(<<ENDPICK);
 3778:   function verify(vf) {
 3779:     var foundsomething=0;
 3780:     var founduname=0;
 3781:     var foundID=0;
 3782:     for (i=0;i<=vf.nfields.value;i++) {
 3783:       tw=eval('vf.f'+i+'.selectedIndex');
 3784:       if (tw==1) { foundID=1; }
 3785:       if (tw==2) { founduname=1; }
 3786:       if (tw>3) { foundsomething=1; }
 3787:     }
 3788:     if (founduname==0 && foundID==0) {
 3789: 	alert('$error1');
 3790: 	return;
 3791:     }
 3792:     if (foundsomething==0) {
 3793: 	alert('$error2');
 3794: 	return;
 3795:     }
 3796:     vf.submit();
 3797:   }
 3798:   function flip(vf,tf) {
 3799:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3800:     var i;
 3801:     //can not pick the same destination field twice
 3802:     for (i=0;i<=vf.nfields.value;i++) {
 3803:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3804:         eval('vf.f'+i+'.selectedIndex=0;')
 3805:       }
 3806:     }
 3807:   }
 3808: ENDPICK
 3809: }
 3810: 
 3811: sub csvuploadmap_header {
 3812:     my ($request,$symb,$datatoken,$distotal)= @_;
 3813:     my $javascript;
 3814:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3815: 	$javascript=&csvupload_javascript_reverse_associate();
 3816:     } else {
 3817: 	$javascript=&csvupload_javascript_forward_associate();
 3818:     }
 3819: 
 3820:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3821:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3822:     my $ignore=&mt('Ignore First Line');
 3823:     $symb = &Apache::lonenc::check_encrypt($symb);
 3824:     $request->print(<<ENDPICK);
 3825: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3826: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3827: $result
 3828: <hr />
 3829: <h3>Identify fields</h3>
 3830: Total number of records found in file: $distotal <hr />
 3831: Enter as many fields as you can. The system will inform you and bring you back
 3832: to this page if the data selected is insufficient to run your class.<hr />
 3833: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3834: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3835: <input type="hidden" name="associate"  value="" />
 3836: <input type="hidden" name="phase"      value="three" />
 3837: <input type="hidden" name="datatoken"  value="$datatoken" />
 3838: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3839: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3840: <input type="hidden" name="upfile_associate" 
 3841:                                        value="$env{'form.upfile_associate'}" />
 3842: <input type="hidden" name="symb"       value="$symb" />
 3843: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3844: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3845: <input type="hidden" name="command"    value="csvuploadoptions" />
 3846: <hr />
 3847: <script type="text/javascript" language="Javascript">
 3848: $javascript
 3849: </script>
 3850: ENDPICK
 3851:     return '';
 3852: 
 3853: }
 3854: 
 3855: sub csvupload_fields {
 3856:     my ($symb) = @_;
 3857:     my ($symb,$errorref) = @_;
 3858:     my (@parts) = &getpartlist($symb,$errorref);
 3859:     if (ref($errorref)) {
 3860:         if ($$errorref) {
 3861:             return;
 3862:         }
 3863:     }
 3864: 
 3865:     my @fields=(['ID','Student/Employee ID'],
 3866: 		['username','Student Username'],
 3867: 		['domain','Student Domain']);
 3868:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3869:     foreach my $part (sort(@parts)) {
 3870: 	my @datum;
 3871: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3872: 	my $name=$part;
 3873: 	if  (!$display) { $display = $name; }
 3874: 	@datum=($name,$display);
 3875: 	if ($name=~/^stores_(.*)_awarded/) {
 3876: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3877: 	}
 3878: 	push(@fields,\@datum);
 3879:     }
 3880:     return (@fields);
 3881: }
 3882: 
 3883: sub csvuploadmap_footer {
 3884:     my ($request,$i,$keyfields) =@_;
 3885:     $request->print(<<ENDPICK);
 3886: </table>
 3887: <input type="hidden" name="nfields" value="$i" />
 3888: <input type="hidden" name="keyfields" value="$keyfields" />
 3889: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3890: </form>
 3891: ENDPICK
 3892: }
 3893: 
 3894: sub checkforfile_js {
 3895:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3896:     my $result =<<CSVFORMJS;
 3897: <script type="text/javascript" language="javascript">
 3898:     function checkUpload(formname) {
 3899: 	if (formname.upfile.value == "") {
 3900: 	    alert("$alertmsg");
 3901: 	    return false;
 3902: 	}
 3903: 	formname.submit();
 3904:     }
 3905:     </script>
 3906: CSVFORMJS
 3907:     return $result;
 3908: }
 3909: 
 3910: sub upcsvScores_form {
 3911:     my ($request) = shift;
 3912:     my ($symb)=&get_symb($request);
 3913:     if (!$symb) {return '';}
 3914:     my $result=&checkforfile_js();
 3915:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3916:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3917:     $result.=$table;
 3918:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3919:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3920:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3921: 	'</b></td></tr>'."\n";
 3922:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3923:     my $upload=&mt("Upload Scores");
 3924:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3925:     my $ignore=&mt('Ignore First Line');
 3926:     $symb = &Apache::lonenc::check_encrypt($symb);
 3927:     $result.=<<ENDUPFORM;
 3928: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3929: <input type="hidden" name="symb" value="$symb" />
 3930: <input type="hidden" name="command" value="csvuploadmap" />
 3931: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3932: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3933: $upfile_select
 3934: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3935: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3936: </form>
 3937: ENDUPFORM
 3938:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3939:                            &mt("How do I create a CSV file from a spreadsheet"))
 3940:     .'</td></tr></table>'."\n";
 3941:     $result.='</td></tr></table><br /><br />'."\n";
 3942:     $result.=&show_grading_menu_form($symb);
 3943:     return $result;
 3944: }
 3945: 
 3946: 
 3947: sub csvuploadmap {
 3948:     my ($request)= @_;
 3949:     my ($symb)=&get_symb($request);
 3950:     if (!$symb) {return '';}
 3951: 
 3952:     my $datatoken;
 3953:     if (!$env{'form.datatoken'}) {
 3954: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3955:     } else {
 3956: 	$datatoken=$env{'form.datatoken'};
 3957: 	&Apache::loncommon::load_tmp_file($request);
 3958:     }
 3959:     my @records=&Apache::loncommon::upfile_record_sep();
 3960:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3961:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3962:     my ($i,$keyfields);
 3963:     if (@records) {
 3964:         my $fieldserror;
 3965:         my @fields=&csvupload_fields($symb,\$fieldserror);
 3966:         if ($fieldserror) {
 3967:             $request->print(&navmap_errormsg());
 3968:             return;
 3969:         }
 3970: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3971: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3972: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3973: 							  \@fields);
 3974: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3975: 	    chop($keyfields);
 3976: 	} else {
 3977: 	    unshift(@fields,['none','']);
 3978: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3979: 							    \@fields);
 3980:             foreach my $rec (@records) {
 3981:                 my %temp = &Apache::loncommon::record_sep($rec);
 3982:                 if (%temp) {
 3983:                     $keyfields=join(',',sort(keys(%temp)));
 3984:                     last;
 3985:                 }
 3986:             }
 3987: 	}
 3988:     }
 3989:     &csvuploadmap_footer($request,$i,$keyfields);
 3990:     $request->print(&show_grading_menu_form($symb));
 3991: 
 3992:     return '';
 3993: }
 3994: 
 3995: sub csvuploadoptions {
 3996:     my ($request)= @_;
 3997:     my ($symb)=&get_symb($request);
 3998:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3999:     my $ignore=&mt('Ignore First Line');
 4000:     $request->print(<<ENDPICK);
 4001: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4002: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4003: <input type="hidden" name="command"    value="csvuploadassign" />
 4004: <!--
 4005: <p>
 4006: <label>
 4007:    <input type="checkbox" name="show_full_results" />
 4008:    Show a table of all changes
 4009: </label>
 4010: </p>
 4011: -->
 4012: <p>
 4013: <label>
 4014:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4015:    Overwrite any existing score
 4016: </label>
 4017: </p>
 4018: ENDPICK
 4019:     my %fields=&get_fields();
 4020:     if (!defined($fields{'domain'})) {
 4021: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4022: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4023:     }
 4024:     foreach my $key (sort(keys(%env))) {
 4025: 	if ($key !~ /^form\.(.*)$/) { next; }
 4026: 	my $cleankey=$1;
 4027: 	if ($cleankey eq 'command') { next; }
 4028: 	$request->print('<input type="hidden" name="'.$cleankey.
 4029: 			'"  value="'.$env{$key}.'" />'."\n");
 4030:     }
 4031:     # FIXME do a check for any duplicated user ids...
 4032:     # FIXME do a check for any invalid user ids?...
 4033:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4034: <hr /></form>'."\n");
 4035:     $request->print(&show_grading_menu_form($symb));
 4036:     return '';
 4037: }
 4038: 
 4039: sub get_fields {
 4040:     my %fields;
 4041:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4042:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4043: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4044: 	    if ($env{'form.f'.$i} ne 'none') {
 4045: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4046: 	    }
 4047: 	} else {
 4048: 	    if ($env{'form.f'.$i} ne 'none') {
 4049: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4050: 	    }
 4051: 	}
 4052:     }
 4053:     return %fields;
 4054: }
 4055: 
 4056: sub csvuploadassign {
 4057:     my ($request)= @_;
 4058:     my ($symb)=&get_symb($request);
 4059:     if (!$symb) {return '';}
 4060:     my $error_msg = '';
 4061:     &Apache::loncommon::load_tmp_file($request);
 4062:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4063:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4064:     my %fields=&get_fields();
 4065:     $request->print('<h3>Assigning Grades</h3>');
 4066:     my $courseid=$env{'request.course.id'};
 4067:     my ($classlist) = &getclasslist('all',0);
 4068:     my @notallowed;
 4069:     my @skipped;
 4070:     my $countdone=0;
 4071:     foreach my $grade (@gradedata) {
 4072: 	my %entries=&Apache::loncommon::record_sep($grade);
 4073: 	my $domain;
 4074: 	if ($entries{$fields{'domain'}}) {
 4075: 	    $domain=$entries{$fields{'domain'}};
 4076: 	} else {
 4077: 	    $domain=$env{'form.default_domain'};
 4078: 	}
 4079: 	$domain=~s/\s//g;
 4080: 	my $username=$entries{$fields{'username'}};
 4081: 	$username=~s/\s//g;
 4082: 	if (!$username) {
 4083: 	    my $id=$entries{$fields{'ID'}};
 4084: 	    $id=~s/\s//g;
 4085: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4086: 	    $username=$ids{$id};
 4087: 	}
 4088: 	if (!exists($$classlist{"$username:$domain"})) {
 4089: 	    my $id=$entries{$fields{'ID'}};
 4090: 	    $id=~s/\s//g;
 4091: 	    if ($id) {
 4092: 		push(@skipped,"$id:$domain");
 4093: 	    } else {
 4094: 		push(@skipped,"$username:$domain");
 4095: 	    }
 4096: 	    next;
 4097: 	}
 4098: 	my $usec=$classlist->{"$username:$domain"}[5];
 4099: 	if (!&canmodify($usec)) {
 4100: 	    push(@notallowed,"$username:$domain");
 4101: 	    next;
 4102: 	}
 4103: 	my %points;
 4104: 	my %grades;
 4105: 	foreach my $dest (keys(%fields)) {
 4106: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4107: 		$dest eq 'domain') { next; }
 4108: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4109: 	    if ($dest=~/stores_(.*)_points/) {
 4110: 		my $part=$1;
 4111: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4112: 					      $symb,$domain,$username);
 4113:                 if ($wgt) {
 4114:                     $entries{$fields{$dest}}=~s/\s//g;
 4115:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4116:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4117:                                           : 'correct_by_override';
 4118:                     $grades{"resource.$part.awarded"}=$pcr;
 4119:                     $grades{"resource.$part.solved"}=$award;
 4120:                     $points{$part}=1;
 4121:                 } else {
 4122:                     $error_msg = "<br />" .
 4123:                         &mt("Some point values were assigned"
 4124:                             ." for problems with a weight "
 4125:                             ."of zero. These values were "
 4126:                             ."ignored.");
 4127:                 }
 4128: 	    } else {
 4129: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4130: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4131: 		my $store_key=$dest;
 4132: 		$store_key=~s/^stores/resource/;
 4133: 		$store_key=~s/_/\./g;
 4134: 		$grades{$store_key}=$entries{$fields{$dest}};
 4135: 	    }
 4136: 	}
 4137: 	if (! %grades) { 
 4138:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4139:         } else {
 4140: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4141: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4142: 					   $env{'request.course.id'},
 4143: 					   $domain,$username);
 4144: 	   if ($result eq 'ok') {
 4145: 	      $request->print('.');
 4146: 	   } else {
 4147: 	      $request->print("<p><span class=\"LC_error\">".
 4148:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4149:                                   "$username:$domain",$result)."</span></p>");
 4150: 	   }
 4151: 	   $request->rflush();
 4152: 	   $countdone++;
 4153:         }
 4154:     }
 4155:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
 4156:     if (@skipped) {
 4157: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
 4158:         $request->print(join(', ',@skipped));
 4159:     }
 4160:     if (@notallowed) {
 4161: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
 4162: 	$request->print(join(', ',@notallowed));
 4163:     }
 4164:     $request->print("<br />\n");
 4165:     $request->print(&show_grading_menu_form($symb));
 4166:     return $error_msg;
 4167: }
 4168: #------------- end of section for handling csv file upload ---------
 4169: #
 4170: #-------------------------------------------------------------------
 4171: #
 4172: #-------------- Next few routines handle grading by page/sequence
 4173: #
 4174: #--- Select a page/sequence and a student to grade
 4175: sub pickStudentPage {
 4176:     my ($request) = shift;
 4177: 
 4178:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4179:     $request->print(<<LISTJAVASCRIPT);
 4180: <script type="text/javascript" language="javascript">
 4181: 
 4182: function checkPickOne(formname) {
 4183:     if (radioSelection(formname.student) == null) {
 4184: 	alert("$alertmsg");
 4185: 	return;
 4186:     }
 4187:     ptr = pullDownSelection(formname.selectpage);
 4188:     formname.page.value = formname["page"+ptr].value;
 4189:     formname.title.value = formname["title"+ptr].value;
 4190:     formname.submit();
 4191: }
 4192: 
 4193: </script>
 4194: LISTJAVASCRIPT
 4195:     &commonJSfunctions($request);
 4196:     my ($symb) = &get_symb($request);
 4197:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4198:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4199:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4200: 
 4201:     my $result='<h3><span class="LC_info">&nbsp;'.
 4202: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4203: 
 4204:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4205:     my $map_error;
 4206:     my ($titles,$symbx) = &getSymbMap($map_error);
 4207:     if ($map_error) {
 4208:         $request->print(&navmap_errormsg());
 4209:         return;
 4210:     }
 4211:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4212: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4213: #    my $type=($curpage =~ /\.(page|sequence)/);
 4214:     my $select = '<select name="selectpage">'."\n";
 4215:     my $ctr=0;
 4216:     foreach (@$titles) {
 4217: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4218: 	$select.='<option value="'.$ctr.'" '.
 4219: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4220: 	    '>'.$showtitle.'</option>'."\n";
 4221: 	$ctr++;
 4222:     }
 4223:     $select.= '</select>';
 4224:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4225: 
 4226:     $ctr=0;
 4227:     foreach (@$titles) {
 4228: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4229: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4230: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4231: 	$ctr++;
 4232:     }
 4233:     $result.='<input type="hidden" name="page" />'."\n".
 4234: 	'<input type="hidden" name="title" />'."\n";
 4235: 
 4236:     my $options =
 4237: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4238: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4239:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4240: 
 4241:     $options =
 4242: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4243: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4244: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4245:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4246:     
 4247:     $result.=&build_section_inputs();
 4248:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4249:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4250: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4251: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4252: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4253: 
 4254:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4255: 
 4256:     $result.='&nbsp;<input type="button" '.
 4257: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4258: 
 4259:     $request->print($result);
 4260: 
 4261:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4262: 	&Apache::loncommon::start_data_table().
 4263: 	&Apache::loncommon::start_data_table_header_row().
 4264: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4265: 	'<th>'.&nameUserString('header').'</th>'.
 4266: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4267: 	'<th>'.&nameUserString('header').'</th>'.
 4268: 	&Apache::loncommon::end_data_table_header_row();
 4269:  
 4270:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4271:     my $ptr = 1;
 4272:     foreach my $student (sort 
 4273: 			 {
 4274: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4275: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4276: 			     }
 4277: 			     return $a cmp $b;
 4278: 			 } (keys(%$fullname))) {
 4279: 	my ($uname,$udom) = split(/:/,$student);
 4280: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4281:                                   : '</td>');
 4282: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4283: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4284: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4285: 	$studentTable.=
 4286: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4287:                          : '');
 4288: 	$ptr++;
 4289:     }
 4290:     if ($ptr%2 == 0) {
 4291: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4292: 	    &Apache::loncommon::end_data_table_row();
 4293:     }
 4294:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4295:     $studentTable.='<input type="button" '.
 4296: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4297: 
 4298:     $studentTable.=&show_grading_menu_form($symb);
 4299:     $request->print($studentTable);
 4300: 
 4301:     return '';
 4302: }
 4303: 
 4304: sub getSymbMap {
 4305:     my ($map_error) = @_;
 4306:     my $navmap = Apache::lonnavmaps::navmap->new();
 4307:     unless (ref($navmap)) {
 4308:         if (ref($map_error)) {
 4309:             $$map_error = 'navmap';
 4310:         }
 4311:         return;
 4312:     }
 4313:     my %symbx = ();
 4314:     my @titles = ();
 4315:     my $minder = 0;
 4316: 
 4317:     # Gather every sequence that has problems.
 4318:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4319: 					       1,0,1);
 4320:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4321: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4322: 	    my $title = $minder.'.'.
 4323: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4324: 	    push(@titles, $title); # minder in case two titles are identical
 4325: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4326: 	    $minder++;
 4327: 	}
 4328:     }
 4329:     return \@titles,\%symbx;
 4330: }
 4331: 
 4332: #
 4333: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4334: sub displayPage {
 4335:     my ($request) = shift;
 4336: 
 4337:     my ($symb) = &get_symb($request);
 4338:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4339:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4340:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4341:     my $pageTitle = $env{'form.page'};
 4342:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4343:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4344:     my $usec=$classlist->{$env{'form.student'}}[5];
 4345: 
 4346:     #need to make sure we have the correct data for later EXT calls, 
 4347:     #thus invalidate the cache
 4348:     &Apache::lonnet::devalidatecourseresdata(
 4349:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4350:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4351:     &Apache::lonnet::clear_EXT_cache_status();
 4352: 
 4353:     if (!&canview($usec)) {
 4354: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4355: 	$request->print(&show_grading_menu_form($symb));
 4356: 	return;
 4357:     }
 4358:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4359:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4360: 	'</h3>'."\n";
 4361:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4362:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4363: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4364:     } else {
 4365: 	delete($env{'form.CODE'});
 4366:     }
 4367:     &sub_page_js($request);
 4368:     $request->print($result);
 4369: 
 4370:     my $navmap = Apache::lonnavmaps::navmap->new();
 4371:     unless (ref($navmap)) {
 4372:         $request->print(&navmap_errormsg());
 4373:         $request->print(&show_grading_menu_form($symb));
 4374:         return;
 4375:     }
 4376:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4377:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4378:     if (!$map) {
 4379: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4380: 	$request->print(&show_grading_menu_form($symb));
 4381: 	return; 
 4382:     }
 4383:     my $iterator = $navmap->getIterator($map->map_start(),
 4384: 					$map->map_finish());
 4385: 
 4386:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4387: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4388: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4389: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4390: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4391: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4392: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4393: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4394: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4395: 
 4396:     if (defined($env{'form.CODE'})) {
 4397: 	$studentTable.=
 4398: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4399:     }
 4400:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4401: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4402: 
 4403:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4404: 	&Apache::loncommon::start_data_table().
 4405: 	&Apache::loncommon::start_data_table_header_row().
 4406: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4407: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4408: 	&Apache::loncommon::end_data_table_header_row();
 4409: 
 4410:     &Apache::lonxml::clear_problem_counter();
 4411:     my ($depth,$question,$prob) = (1,1,1);
 4412:     $iterator->next(); # skip the first BEGIN_MAP
 4413:     my $curRes = $iterator->next(); # for "current resource"
 4414:     while ($depth > 0) {
 4415:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4416:         if($curRes == $iterator->END_MAP) { $depth--; }
 4417: 
 4418:         if (ref($curRes) && $curRes->is_problem()) {
 4419: 	    my $parts = $curRes->parts();
 4420:             my $title = $curRes->compTitle();
 4421: 	    my $symbx = $curRes->symb();
 4422: 	    $studentTable.=
 4423: 		&Apache::loncommon::start_data_table_row().
 4424: 		'<td align="center" valign="top" >'.$prob.
 4425: 		(scalar(@{$parts}) == 1 ? '' 
 4426: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4427: 							scalar(@{$parts}))
 4428: 		 ).
 4429: 		 '</td>';
 4430: 	    $studentTable.='<td valign="top">';
 4431: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4432: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4433: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4434: 					     undef,'both',\%form);
 4435: 	    } else {
 4436: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4437: 		$companswer =~ s|<form(.*?)>||g;
 4438: 		$companswer =~ s|</form>||g;
 4439: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4440: #		    $companswer =~ s/$1/ /ms;
 4441: #		    $request->print('match='.$1."<br />\n");
 4442: #		}
 4443: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4444: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4445: 	    }
 4446: 
 4447: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4448: 
 4449: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4450: 		if ($record{'version'} eq '') {
 4451: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4452: 		} else {
 4453: 		    my %responseType = ();
 4454: 		    foreach my $partid (@{$parts}) {
 4455: 			my @responseIds =$curRes->responseIds($partid);
 4456: 			my @responseType =$curRes->responseType($partid);
 4457: 			my %responseIds;
 4458: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4459: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4460: 			}
 4461: 			$responseType{$partid} = \%responseIds;
 4462: 		    }
 4463: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4464: 
 4465: 		}
 4466: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4467: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4468: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4469: 									$env{'request.course.id'},
 4470: 									'','.submission');
 4471:  
 4472: 	    }
 4473: 	    if (&canmodify($usec)) {
 4474: 		foreach my $partid (@{$parts}) {
 4475: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4476: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4477: 		    $question++;
 4478: 		}
 4479: 		$prob++;
 4480: 	    }
 4481: 	    $studentTable.='</td></tr>';
 4482: 
 4483: 	}
 4484:         $curRes = $iterator->next();
 4485:     }
 4486: 
 4487:     $studentTable.='</table>'."\n".
 4488: 	'<input type="button" value="'.&mt('Save').'" '.
 4489: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4490: 	'</form>'."\n";
 4491:     $studentTable.=&show_grading_menu_form($symb);
 4492:     $request->print($studentTable);
 4493: 
 4494:     return '';
 4495: }
 4496: 
 4497: sub displaySubByDates {
 4498:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4499:     my $isCODE=0;
 4500:     my $isTask = ($symb =~/\.task$/);
 4501:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4502:     my $studentTable=&Apache::loncommon::start_data_table().
 4503: 	&Apache::loncommon::start_data_table_header_row().
 4504: 	'<th>'.&mt('Date/Time').'</th>'.
 4505: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4506: 	'<th>'.&mt('Submission').'</th>'.
 4507: 	'<th>'.&mt('Status').'</th>'.
 4508: 	&Apache::loncommon::end_data_table_header_row();
 4509:     my ($version);
 4510:     my %mark;
 4511:     my %orders;
 4512:     $mark{'correct_by_student'} = $checkIcon;
 4513:     if (!exists($$record{'1:timestamp'})) {
 4514: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4515:     }
 4516: 
 4517:     my $interaction;
 4518:     my $no_increment = 1;
 4519:     for ($version=1;$version<=$$record{'version'};$version++) {
 4520: 	my $timestamp = 
 4521: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4522: 	if (exists($$record{$version.':resource.0.version'})) {
 4523: 	    $interaction = $$record{$version.':resource.0.version'};
 4524: 	}
 4525: 
 4526: 	my $where = ($isTask ? "$version:resource.$interaction"
 4527: 		             : "$version:resource");
 4528: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4529: 	    '<td>'.$timestamp.'</td>';
 4530: 	if ($isCODE) {
 4531: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4532: 	}
 4533: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4534: 	my @displaySub = ();
 4535: 	foreach my $partid (@{$parts}) {
 4536: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4537: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4538: 	    
 4539: 
 4540: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4541: 	    my $display_part=&get_display_part($partid,$symb);
 4542: 	    foreach my $matchKey (@matchKey) {
 4543: 		if (exists($$record{$version.':'.$matchKey}) &&
 4544: 		    $$record{$version.':'.$matchKey} ne '') {
 4545: 
 4546: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4547: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4548: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4549: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4550: 			$responseId.')</span>&nbsp;<b>';
 4551: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4552: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4553: 		    } else {
 4554: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4555: 					    $$record{"$where.$partid.tries"});
 4556: 		    }
 4557: 		    my $responseType=($isTask ? 'Task'
 4558:                                               : $responseType->{$partid}->{$responseId});
 4559: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4560: 		    if (!exists($orders{$partid}->{$responseId})) {
 4561: 			$orders{$partid}->{$responseId}=
 4562: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4563:                                        $no_increment);
 4564: 		    }
 4565: 		    $displaySub[0].='</b>&nbsp; '.
 4566: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4567: 		}
 4568: 	    }
 4569: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4570: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4571: 				    $$record{"$where.$partid.checkedin"},
 4572: 				    $$record{"$where.$partid.checkedin.slot"}).
 4573: 					'<br />';
 4574: 	    }
 4575: 	    if (exists $$record{"$where.$partid.award"}) {
 4576: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4577: 		    lc($$record{"$where.$partid.award"}).' '.
 4578: 		    $mark{$$record{"$where.$partid.solved"}}.
 4579: 		    '<br />';
 4580: 	    }
 4581: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4582: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4583: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4584: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4585: 		$displaySub[2].=
 4586: 		    $$record{"$version:resource.$partid.regrader"}.
 4587: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4588: 	    }
 4589: 	}
 4590: 	# needed because old essay regrader has not parts info
 4591: 	if (exists $$record{"$version:resource.regrader"}) {
 4592: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4593: 	}
 4594: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4595: 	if ($displaySub[2]) {
 4596: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4597: 	}
 4598: 	$studentTable.='&nbsp;</td>'.
 4599: 	    &Apache::loncommon::end_data_table_row();
 4600:     }
 4601:     $studentTable.=&Apache::loncommon::end_data_table();
 4602:     return $studentTable;
 4603: }
 4604: 
 4605: sub updateGradeByPage {
 4606:     my ($request) = shift;
 4607: 
 4608:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4609:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4610:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4611:     my $pageTitle = $env{'form.page'};
 4612:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4613:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4614:     my $usec=$classlist->{$env{'form.student'}}[5];
 4615:     if (!&canmodify($usec)) {
 4616: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4617: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4618: 	return;
 4619:     }
 4620:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4621:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4622: 	'</h3>'."\n";
 4623: 
 4624:     $request->print($result);
 4625: 
 4626:     my $navmap = Apache::lonnavmaps::navmap->new();
 4627:     unless (ref($navmap)) {
 4628:         $request->print(&navmap_errormsg());
 4629:         return;
 4630:     }
 4631:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4632:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4633:     if (!$map) {
 4634: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4635: 	my ($symb)=&get_symb($request);
 4636: 	$request->print(&show_grading_menu_form($symb));
 4637: 	return; 
 4638:     }
 4639:     my $iterator = $navmap->getIterator($map->map_start(),
 4640: 					$map->map_finish());
 4641: 
 4642:     my $studentTable=
 4643: 	&Apache::loncommon::start_data_table().
 4644: 	&Apache::loncommon::start_data_table_header_row().
 4645: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4646: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4647: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4648: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4649: 	&Apache::loncommon::end_data_table_header_row();
 4650: 
 4651:     $iterator->next(); # skip the first BEGIN_MAP
 4652:     my $curRes = $iterator->next(); # for "current resource"
 4653:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4654:     while ($depth > 0) {
 4655:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4656:         if($curRes == $iterator->END_MAP) { $depth--; }
 4657: 
 4658:         if (ref($curRes) && $curRes->is_problem()) {
 4659: 	    my $parts = $curRes->parts();
 4660:             my $title = $curRes->compTitle();
 4661: 	    my $symbx = $curRes->symb();
 4662: 	    $studentTable.=
 4663: 		&Apache::loncommon::start_data_table_row().
 4664: 		'<td align="center" valign="top" >'.$prob.
 4665: 		(scalar(@{$parts}) == 1 ? '' 
 4666:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4667: 		.')').'</td>';
 4668: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4669: 
 4670: 	    my %newrecord=();
 4671: 	    my @displayPts=();
 4672:             my %aggregate = ();
 4673:             my $aggregateflag = 0;
 4674: 	    foreach my $partid (@{$parts}) {
 4675: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4676: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4677: 
 4678: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4679: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4680: 		my $partial = $newpts/$wgt;
 4681: 		my $score;
 4682: 		if ($partial > 0) {
 4683: 		    $score = 'correct_by_override';
 4684: 		} elsif ($newpts ne '') { #empty is taken as 0
 4685: 		    $score = 'incorrect_by_override';
 4686: 		}
 4687: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4688: 		if ($dropMenu eq 'excused') {
 4689: 		    $partial = '';
 4690: 		    $score = 'excused';
 4691: 		} elsif ($dropMenu eq 'reset status'
 4692: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4693: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4694: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4695: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4696: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4697: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4698: 		    $changeflag++;
 4699: 		    $newpts = '';
 4700:                     
 4701:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4702:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4703:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4704:                     if ($aggtries > 0) {
 4705:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4706:                         $aggregateflag = 1;
 4707:                     }
 4708: 		}
 4709: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4710: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4711: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4712: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4713: 		    '&nbsp;<br />';
 4714: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4715: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4716: 		    '&nbsp;<br />';
 4717: 		$question++;
 4718: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4719: 
 4720: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4721: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4722: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4723: 		    if (scalar(keys(%newrecord)) > 0);
 4724: 
 4725: 		$changeflag++;
 4726: 	    }
 4727: 	    if (scalar(keys(%newrecord)) > 0) {
 4728: 		my %record = 
 4729: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4730: 					     $udom,$uname);
 4731: 
 4732: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4733: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4734: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4735: 		    $newrecord{'resource.CODE'} = '';
 4736: 		}
 4737: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4738: 					$udom,$uname);
 4739: 		%record = &Apache::lonnet::restore($symbx,
 4740: 						   $env{'request.course.id'},
 4741: 						   $udom,$uname);
 4742: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4743: 					     $cdom,$cnum,$udom,$uname);
 4744: 	    }
 4745: 	    
 4746:             if ($aggregateflag) {
 4747:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4748:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4749:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4750:             }
 4751: 
 4752: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4753: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4754: 		&Apache::loncommon::end_data_table_row();
 4755: 
 4756: 	    $prob++;
 4757: 	}
 4758:         $curRes = $iterator->next();
 4759:     }
 4760: 
 4761:     $studentTable.=&Apache::loncommon::end_data_table();
 4762:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4763:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4764: 		  &mt('The scores were changed for [quant,_1,problem].',
 4765: 		  $changeflag));
 4766:     $request->print($grademsg.$studentTable);
 4767: 
 4768:     return '';
 4769: }
 4770: 
 4771: #-------- end of section for handling grading by page/sequence ---------
 4772: #
 4773: #-------------------------------------------------------------------
 4774: 
 4775: #--------------------Bubblesheet (Scantron) Grading-----------------------------------
 4776: #
 4777: #------ start of section for handling grading by page/sequence ---------
 4778: 
 4779: =pod
 4780: 
 4781: =head1 Bubble sheet grading routines
 4782: 
 4783:   For this documentation:
 4784: 
 4785:    'scanline' refers to the full line of characters
 4786:    from the file that we are parsing that represents one entire sheet
 4787: 
 4788:    'bubble line' refers to the data
 4789:    representing the line of bubbles that are on the physical bubble sheet
 4790: 
 4791: 
 4792: The overall process is that a scanned in bubble sheet data is uploaded
 4793: into a course. When a user wants to grade, they select a
 4794: sequence/folder of resources, a file of bubble sheet info, and pick
 4795: one of the predefined configurations for what each scanline looks
 4796: like.
 4797: 
 4798: Next each scanline is checked for any errors of either 'missing
 4799: bubbles' (it's an error because it may have been mis-scanned
 4800: because too light bubbling), 'double bubble' (each bubble line should
 4801: have no more that one letter picked), invalid or duplicated CODE,
 4802: invalid student/employee ID
 4803: 
 4804: If the CODE option is used that determines the randomization of the
 4805: homework problems, either way the student/employee ID is looked up into a
 4806: username:domain.
 4807: 
 4808: During the validation phase the instructor can choose to skip scanlines. 
 4809: 
 4810: After the validation phase, there are now 3 bubble sheet files
 4811: 
 4812:   scantron_original_filename (unmodified original file)
 4813:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4814:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4815: 
 4816: Also there is a separate hash nohist_scantrondata that contains extra
 4817: correction information that isn't representable in the bubble sheet
 4818: file (see &scantron_getfile() for more information)
 4819: 
 4820: After all scanlines are either valid, marked as valid or skipped, then
 4821: foreach line foreach problem in the picked sequence, an ssi request is
 4822: made that simulates a user submitting their selected letter(s) against
 4823: the homework problem.
 4824: 
 4825: =over 4
 4826: 
 4827: 
 4828: 
 4829: =item defaultFormData
 4830: 
 4831:   Returns html hidden inputs used to hold context/default values.
 4832: 
 4833:  Arguments:
 4834:    $symb - $symb of the current resource
 4835:    $map_error - ref to scalar which will container error if
 4836:                 $navmap object is unavailable in &getSymbMap().
 4837: 
 4838: =cut
 4839: 
 4840: sub defaultFormData {
 4841:     my ($symb)=@_;
 4842:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4843:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4844:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4845: }
 4846: 
 4847: 
 4848: =pod 
 4849: 
 4850: =item getSequenceDropDown
 4851: 
 4852:    Return html dropdown of possible sequences to grade
 4853:  
 4854:  Arguments:
 4855:    $symb - $symb of the current resource 
 4856: 
 4857: =cut
 4858: 
 4859: sub getSequenceDropDown {
 4860:     my ($symb,$map_error)=@_;
 4861:     my $result='<select name="selectpage">'."\n";
 4862:     my ($titles,$symbx) = &getSymbMap($map_error);
 4863:     if (ref($map_error)) {
 4864:         return if ($$map_error);
 4865:     }
 4866:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4867:     my $ctr=0;
 4868:     foreach (@$titles) {
 4869: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4870: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4871: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4872: 	    '>'.$showtitle.'</option>'."\n";
 4873: 	$ctr++;
 4874:     }
 4875:     $result.= '</select>';
 4876:     return $result;
 4877: }
 4878: 
 4879: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4880:                                    # key is zero-based index - 0, 1, 2 ...
 4881: 
 4882: my %first_bubble_line;             # First bubble line no. for each bubble.
 4883: 
 4884: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4885:                                    # matchresponse or rankresponse, where 
 4886:                                    # an individual response can have multiple 
 4887:                                    # lines
 4888: 
 4889: my %responsetype_per_response;     # responsetype for each response
 4890: 
 4891: # Save and restore the bubble lines array to the form env.
 4892: 
 4893: 
 4894: sub save_bubble_lines {
 4895:     foreach my $line (keys(%bubble_lines_per_response)) {
 4896: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4897: 	$env{"form.scantron.first_bubble_line.$line"} =
 4898: 	    $first_bubble_line{$line};
 4899:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4900:             $subdivided_bubble_lines{$line};
 4901:         $env{"form.scantron.responsetype.$line"} =
 4902:             $responsetype_per_response{$line};
 4903:     }
 4904: }
 4905: 
 4906: 
 4907: sub restore_bubble_lines {
 4908:     my $line = 0;
 4909:     %bubble_lines_per_response = ();
 4910:     while ($env{"form.scantron.bubblelines.$line"}) {
 4911: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4912: 	$bubble_lines_per_response{$line} = $value;
 4913: 	$first_bubble_line{$line}  =
 4914: 	    $env{"form.scantron.first_bubble_line.$line"};
 4915:         $subdivided_bubble_lines{$line} =
 4916:             $env{"form.scantron.sub_bubblelines.$line"};
 4917:         $responsetype_per_response{$line} =
 4918:             $env{"form.scantron.responsetype.$line"};
 4919: 	$line++;
 4920:     }
 4921: }
 4922: 
 4923: #  Given the parsed scanline, get the response for 
 4924: #  'answer' number n:
 4925: 
 4926: sub get_response_bubbles {
 4927:     my ($parsed_line, $response)  = @_;
 4928: 
 4929:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4930:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4931:     
 4932:     my $selected = "";
 4933: 
 4934:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4935: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4936: 	$bubble_line++;
 4937:     }
 4938:     return $selected;
 4939: }
 4940: 
 4941: =pod 
 4942: 
 4943: =item scantron_filenames
 4944: 
 4945:    Returns a list of the scantron files in the current course 
 4946: 
 4947: =cut
 4948: 
 4949: sub scantron_filenames {
 4950:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4951:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4952:     my $getpropath = 1;
 4953:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4954:                                        $getpropath);
 4955:     my @possiblenames;
 4956:     foreach my $filename (sort(@files)) {
 4957: 	($filename)=split(/&/,$filename);
 4958: 	if ($filename!~/^scantron_orig_/) { next ; }
 4959: 	$filename=~s/^scantron_orig_//;
 4960: 	push(@possiblenames,$filename);
 4961:     }
 4962:     return @possiblenames;
 4963: }
 4964: 
 4965: =pod 
 4966: 
 4967: =item scantron_uploads
 4968: 
 4969:    Returns  html drop-down list of scantron files in current course.
 4970: 
 4971:  Arguments:
 4972:    $file2grade - filename to set as selected in the dropdown
 4973: 
 4974: =cut
 4975: 
 4976: sub scantron_uploads {
 4977:     my ($file2grade) = @_;
 4978:     my $result=	'<select name="scantron_selectfile">';
 4979:     $result.="<option></option>";
 4980:     foreach my $filename (sort(&scantron_filenames())) {
 4981: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4982:     }
 4983:     $result.="</select>";
 4984:     return $result;
 4985: }
 4986: 
 4987: =pod 
 4988: 
 4989: =item scantron_scantab
 4990: 
 4991:   Returns html drop down of the scantron formats in the scantronformat.tab
 4992:   file.
 4993: 
 4994: =cut
 4995: 
 4996: sub scantron_scantab {
 4997:     my $result='<select name="scantron_format">'."\n";
 4998:     $result.='<option></option>'."\n";
 4999:     my @lines = &get_scantronformat_file();
 5000:     if (@lines > 0) {
 5001:         foreach my $line (@lines) {
 5002:             next if (($line =~ /^\#/) || ($line eq ''));
 5003: 	    my ($name,$descrip)=split(/:/,$line);
 5004: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5005:         }
 5006:     }
 5007:     $result.='</select>'."\n";
 5008:     return $result;
 5009: }
 5010: 
 5011: =pod
 5012: 
 5013: =item get_scantronformat_file
 5014: 
 5015:   Returns an array containing lines from the scantron format file for
 5016:   the domain of the course.
 5017: 
 5018:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5019:   lines are from this file.
 5020: 
 5021:   Otherwise, if a default.tab has been published in RES space by the 
 5022:   domainconfig user, lines are from this file.
 5023: 
 5024:   Otherwise, fall back to getting lines from the legacy file on the
 5025:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5026: 
 5027: =cut
 5028: 
 5029: sub get_scantronformat_file {
 5030:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5031:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5032:     my $gottab = 0;
 5033:     my @lines;
 5034:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5035:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5036:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5037:             if ($formatfile ne '-1') {
 5038:                 @lines = split("\n",$formatfile,-1);
 5039:                 $gottab = 1;
 5040:             }
 5041:         }
 5042:     }
 5043:     if (!$gottab) {
 5044:         my $confname = $cdom.'-domainconfig';
 5045:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5046:         my $formatfile =  &Apache::lonnet::getfile($default);
 5047:         if ($formatfile ne '-1') {
 5048:             @lines = split("\n",$formatfile,-1);
 5049:             $gottab = 1;
 5050:         }
 5051:     }
 5052:     if (!$gottab) {
 5053:         my @domains = &Apache::lonnet::current_machine_domains();
 5054:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5055:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5056:             @lines = <$fh>;
 5057:             close($fh);
 5058:         } else {
 5059:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5060:             @lines = <$fh>;
 5061:             close($fh);
 5062:         }
 5063:     }
 5064:     return @lines;
 5065: }
 5066: 
 5067: =pod 
 5068: 
 5069: =item scantron_CODElist
 5070: 
 5071:   Returns html drop down of the saved CODE lists from current course,
 5072:   generated from earlier printings.
 5073: 
 5074: =cut
 5075: 
 5076: sub scantron_CODElist {
 5077:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5078:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5079:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5080:     my $namechoice='<option></option>';
 5081:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5082: 	if ($name =~ /^error: 2 /) { next; }
 5083: 	if ($name =~ /^type\0/) { next; }
 5084: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5085:     }
 5086:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5087:     return $namechoice;
 5088: }
 5089: 
 5090: =pod 
 5091: 
 5092: =item scantron_CODEunique
 5093: 
 5094:   Returns the html for "Each CODE to be used once" radio.
 5095: 
 5096: =cut
 5097: 
 5098: sub scantron_CODEunique {
 5099:     my $result='<span class="LC_nobreak">
 5100:                  <label><input type="radio" name="scantron_CODEunique"
 5101:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5102:                 </span>
 5103:                 <span class="LC_nobreak">
 5104:                  <label><input type="radio" name="scantron_CODEunique"
 5105:                         value="no" />'.&mt('No').' </label>
 5106:                 </span>';
 5107:     return $result;
 5108: }
 5109: 
 5110: =pod 
 5111: 
 5112: =item scantron_selectphase
 5113: 
 5114:   Generates the initial screen to start the bubble sheet process.
 5115:   Allows for - starting a grading run.
 5116:              - downloading existing scan data (original, corrected
 5117:                                                 or skipped info)
 5118: 
 5119:              - uploading new scan data
 5120: 
 5121:  Arguments:
 5122:   $r          - The Apache request object
 5123:   $file2grade - name of the file that contain the scanned data to score
 5124: 
 5125: =cut
 5126: 
 5127: sub scantron_selectphase {
 5128:     my ($r,$file2grade) = @_;
 5129:     my ($symb)=&get_symb($r);
 5130:     if (!$symb) {return '';}
 5131:     my $map_error;
 5132:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
 5133:     if ($map_error) {
 5134:         $r->print('<br />'.&navmap_errormsg().'<br />');
 5135:         return;
 5136:     }
 5137:     my $default_form_data=&defaultFormData($symb);
 5138:     my $grading_menu_button=&show_grading_menu_form($symb);
 5139:     my $file_selector=&scantron_uploads($file2grade);
 5140:     my $format_selector=&scantron_scantab();
 5141:     my $CODE_selector=&scantron_CODElist();
 5142:     my $CODE_unique=&scantron_CODEunique();
 5143:     my $result;
 5144: 
 5145:     $ssi_error = 0;
 5146: 
 5147:     # Chunk of form to prompt for a file to grade and how:
 5148: 
 5149:     $result.= '
 5150:     <br />
 5151:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5152:     <input type="hidden" name="command" value="scantron_warning" />
 5153:     '.$default_form_data.'
 5154:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5155:        '.&Apache::loncommon::start_data_table_header_row().'
 5156:             <th colspan="2">
 5157:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5158:             </th>
 5159:        '.&Apache::loncommon::end_data_table_header_row().'
 5160:        '.&Apache::loncommon::start_data_table_row().'
 5161:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5162:        '.&Apache::loncommon::end_data_table_row().'
 5163:        '.&Apache::loncommon::start_data_table_row().'
 5164:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
 5165:        '.&Apache::loncommon::end_data_table_row().'
 5166:        '.&Apache::loncommon::start_data_table_row().'
 5167:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
 5168:        '.&Apache::loncommon::end_data_table_row().'
 5169:        '.&Apache::loncommon::start_data_table_row().'
 5170:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5171:        '.&Apache::loncommon::end_data_table_row().'
 5172:        '.&Apache::loncommon::start_data_table_row().'
 5173:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5174:        '.&Apache::loncommon::end_data_table_row().'
 5175:        '.&Apache::loncommon::start_data_table_row().'
 5176: 	    <td> '.&mt('Options:').' </td>
 5177:             <td>
 5178: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5179:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5180:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5181: 	    </td>
 5182:        '.&Apache::loncommon::end_data_table_row().'
 5183:        '.&Apache::loncommon::start_data_table_row().'
 5184:             <td colspan="2">
 5185:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
 5186:             </td>
 5187:        '.&Apache::loncommon::end_data_table_row().'
 5188:     '.&Apache::loncommon::end_data_table().'
 5189:     </form>
 5190: ';
 5191:    
 5192:     $r->print($result);
 5193: 
 5194:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5195:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5196: 
 5197: 	# Chunk of form to prompt for a scantron file upload.
 5198: 
 5199:         $r->print('
 5200:     <br />
 5201:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5202:        '.&Apache::loncommon::start_data_table_header_row().'
 5203:             <th>
 5204:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
 5205:             </th>
 5206:        '.&Apache::loncommon::end_data_table_header_row().'
 5207:        '.&Apache::loncommon::start_data_table_row().'
 5208:             <td>
 5209: ');
 5210:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5211:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5212:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5213:     $r->print('
 5214:               <script type="text/javascript" language="javascript">
 5215:     function checkUpload(formname) {
 5216: 	if (formname.upfile.value == "") {
 5217: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5218: 	    return false;
 5219: 	}
 5220: 	formname.submit();
 5221:     }
 5222:               </script>
 5223: 
 5224:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5225:                 '.$default_form_data.'
 5226:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5227:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5228:                 <input name="command" value="scantronupload_save" type="hidden" />
 5229:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5230:                 <br />
 5231:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 5232:               </form>
 5233: ');
 5234: 
 5235:         $r->print('
 5236:             </td>
 5237:        '.&Apache::loncommon::end_data_table_row().'
 5238:        '.&Apache::loncommon::end_data_table().'
 5239: ');
 5240:     }
 5241: 
 5242:     # Chunk of the form that prompts to view a scoring office file,
 5243:     # corrected file, skipped records in a file.
 5244: 
 5245:     $r->print('
 5246:    <br />
 5247:    <form action="/adm/grades" name="scantron_download">
 5248:      '.$default_form_data.'
 5249:      <input type="hidden" name="command" value="scantron_download" />
 5250:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5251:        '.&Apache::loncommon::start_data_table_header_row().'
 5252:               <th>
 5253:                 &nbsp;'.&mt('Download a scoring office file').'
 5254:               </th>
 5255:        '.&Apache::loncommon::end_data_table_header_row().'
 5256:        '.&Apache::loncommon::start_data_table_row().'
 5257:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5258:                 <br />
 5259:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5260:        '.&Apache::loncommon::end_data_table_row().'
 5261:      '.&Apache::loncommon::end_data_table().'
 5262:    </form>
 5263:    <br />
 5264: ');
 5265: 
 5266:     &Apache::lonpickcode::code_list($r,2);
 5267: 
 5268:     $r->print('<br /><form method="post" name="checkscantron">'.
 5269:              $default_form_data."\n".
 5270:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5271:              &Apache::loncommon::start_data_table_header_row()."\n".
 5272:              '<th colspan="2">
 5273:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
 5274:              '</th>'."\n".
 5275:               &Apache::loncommon::end_data_table_header_row()."\n".
 5276:               &Apache::loncommon::start_data_table_row()."\n".
 5277:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5278:               '<td> '.$sequence_selector.' </td>'.
 5279:               &Apache::loncommon::end_data_table_row()."\n".
 5280:               &Apache::loncommon::start_data_table_row()."\n".
 5281:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5282:               '<td> '.$file_selector.' </td>'."\n".
 5283:               &Apache::loncommon::end_data_table_row()."\n".
 5284:               &Apache::loncommon::start_data_table_row()."\n".
 5285:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5286:               '<td> '.$format_selector.' </td>'."\n".
 5287:               &Apache::loncommon::end_data_table_row()."\n".
 5288:               &Apache::loncommon::start_data_table_row()."\n".
 5289:               '<td> '.&mt('Options').' </td>'."\n".
 5290:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
 5291:               &Apache::loncommon::end_data_table_row()."\n".
 5292:               &Apache::loncommon::start_data_table_row()."\n".
 5293:               '<td colspan="2">'."\n".
 5294:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5295:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
 5296:               '</td>'."\n".
 5297:               &Apache::loncommon::end_data_table_row()."\n".
 5298:               &Apache::loncommon::end_data_table()."\n".
 5299:               '</form><br />');
 5300:     $r->print($grading_menu_button);
 5301:     return;
 5302: }
 5303: 
 5304: =pod
 5305: 
 5306: =item get_scantron_config
 5307: 
 5308:    Parse and return the scantron configuration line selected as a
 5309:    hash of configuration file fields.
 5310: 
 5311:  Arguments:
 5312:     which - the name of the configuration to parse from the file.
 5313: 
 5314: 
 5315:  Returns:
 5316:             If the named configuration is not in the file, an empty
 5317:             hash is returned.
 5318:     a hash with the fields
 5319:       name         - internal name for the this configuration setup
 5320:       description  - text to display to operator that describes this config
 5321:       CODElocation - if 0 or the string 'none'
 5322:                           - no CODE exists for this config
 5323:                      if -1 || the string 'letter'
 5324:                           - a CODE exists for this config and is
 5325:                             a string of letters
 5326:                      Unsupported value (but planned for future support)
 5327:                           if a positive integer
 5328:                                - The CODE exists as the first n items from
 5329:                                  the question section of the form
 5330:                           if the string 'number'
 5331:                                - The CODE exists for this config and is
 5332:                                  a string of numbers
 5333:       CODEstart   - (only matter if a CODE exists) column in the line where
 5334:                      the CODE starts
 5335:       CODElength  - length of the CODE
 5336:       IDstart     - column where the student/employee ID starts
 5337:       IDlength    - length of the student/employee ID info
 5338:       Qstart      - column where the information from the bubbled
 5339:                     'questions' start
 5340:       Qlength     - number of columns comprising a single bubble line from
 5341:                     the sheet. (usually either 1 or 10)
 5342:       Qon         - either a single character representing the character used
 5343:                     to signal a bubble was chosen in the positional setup, or
 5344:                     the string 'letter' if the letter of the chosen bubble is
 5345:                     in the final, or 'number' if a number representing the
 5346:                     chosen bubble is in the file (1->A 0->J)
 5347:       Qoff        - the character used to represent that a bubble was
 5348:                     left blank
 5349:       PaperID     - if the scanning process generates a unique number for each
 5350:                     sheet scanned the column that this ID number starts in
 5351:       PaperIDlength - number of columns that comprise the unique ID number
 5352:                       for the sheet of paper
 5353:       FirstName   - column that the first name starts in
 5354:       FirstNameLength - number of columns that the first name spans
 5355:  
 5356:       LastName    - column that the last name starts in
 5357:       LastNameLength - number of columns that the last name spans
 5358: 
 5359: =cut
 5360: 
 5361: sub get_scantron_config {
 5362:     my ($which) = @_;
 5363:     my @lines = &get_scantronformat_file();
 5364:     my %config;
 5365:     #FIXME probably should move to XML it has already gotten a bit much now
 5366:     foreach my $line (@lines) {
 5367: 	my ($name,$descrip)=split(/:/,$line);
 5368: 	if ($name ne $which ) { next; }
 5369: 	chomp($line);
 5370: 	my @config=split(/:/,$line);
 5371: 	$config{'name'}=$config[0];
 5372: 	$config{'description'}=$config[1];
 5373: 	$config{'CODElocation'}=$config[2];
 5374: 	$config{'CODEstart'}=$config[3];
 5375: 	$config{'CODElength'}=$config[4];
 5376: 	$config{'IDstart'}=$config[5];
 5377: 	$config{'IDlength'}=$config[6];
 5378: 	$config{'Qstart'}=$config[7];
 5379:  	$config{'Qlength'}=$config[8];
 5380: 	$config{'Qoff'}=$config[9];
 5381: 	$config{'Qon'}=$config[10];
 5382: 	$config{'PaperID'}=$config[11];
 5383: 	$config{'PaperIDlength'}=$config[12];
 5384: 	$config{'FirstName'}=$config[13];
 5385: 	$config{'FirstNamelength'}=$config[14];
 5386: 	$config{'LastName'}=$config[15];
 5387: 	$config{'LastNamelength'}=$config[16];
 5388: 	last;
 5389:     }
 5390:     return %config;
 5391: }
 5392: 
 5393: =pod 
 5394: 
 5395: =item username_to_idmap
 5396: 
 5397:     creates a hash keyed by student/employee ID with values of the corresponding
 5398:     student username:domain.
 5399: 
 5400:   Arguments:
 5401: 
 5402:     $classlist - reference to the class list hash. This is a hash
 5403:                  keyed by student name:domain  whose elements are references
 5404:                  to arrays containing various chunks of information
 5405:                  about the student. (See loncoursedata for more info).
 5406: 
 5407:   Returns
 5408:     %idmap - the constructed hash
 5409: 
 5410: =cut
 5411: 
 5412: sub username_to_idmap {
 5413:     my ($classlist)= @_;
 5414:     my %idmap;
 5415:     foreach my $student (keys(%$classlist)) {
 5416: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5417: 	    $student;
 5418:     }
 5419:     return %idmap;
 5420: }
 5421: 
 5422: =pod
 5423: 
 5424: =item scantron_fixup_scanline
 5425: 
 5426:    Process a requested correction to a scanline.
 5427: 
 5428:   Arguments:
 5429:     $scantron_config   - hash from &get_scantron_config()
 5430:     $scan_data         - hash of correction information 
 5431:                           (see &scantron_getfile())
 5432:     $line              - existing scanline
 5433:     $whichline         - line number of the passed in scanline
 5434:     $field             - type of change to process 
 5435:                          (either 
 5436:                           'ID'     -> correct the student/employee ID
 5437:                           'CODE'   -> correct the CODE
 5438:                           'answer' -> fixup the submitted answers)
 5439:     
 5440:    $args               - hash of additional info,
 5441:                           - 'ID' 
 5442:                                'newid' -> studentID to use in replacement
 5443:                                           of existing one
 5444:                           - 'CODE' 
 5445:                                'CODE_ignore_dup' - set to true if duplicates
 5446:                                                    should be ignored.
 5447: 	                       'CODE' - is new code or 'use_unfound'
 5448:                                         if the existing unfound code should
 5449:                                         be used as is
 5450:                           - 'answer'
 5451:                                'response' - new answer or 'none' if blank
 5452:                                'question' - the bubble line to change
 5453:                                'questionnum' - the question identifier,
 5454:                                                may include subquestion. 
 5455: 
 5456:   Returns:
 5457:     $line - the modified scanline
 5458: 
 5459:   Side effects: 
 5460:     $scan_data - may be updated
 5461: 
 5462: =cut
 5463: 
 5464: 
 5465: sub scantron_fixup_scanline {
 5466:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5467:     if ($field eq 'ID') {
 5468: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5469: 	    return ($line,1,'New value too large');
 5470: 	}
 5471: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5472: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5473: 				     $args->{'newid'});
 5474: 	}
 5475: 	substr($line,$$scantron_config{'IDstart'}-1,
 5476: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5477: 	if ($args->{'newid'}=~/^\s*$/) {
 5478: 	    &scan_data($scan_data,"$whichline.user",
 5479: 		       $args->{'username'}.':'.$args->{'domain'});
 5480: 	}
 5481:     } elsif ($field eq 'CODE') {
 5482: 	if ($args->{'CODE_ignore_dup'}) {
 5483: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5484: 	}
 5485: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5486: 	if ($args->{'CODE'} ne 'use_unfound') {
 5487: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5488: 		return ($line,1,'New CODE value too large');
 5489: 	    }
 5490: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5491: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5492: 	    }
 5493: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5494: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5495: 	}
 5496:     } elsif ($field eq 'answer') {
 5497: 	my $length=$scantron_config->{'Qlength'};
 5498: 	my $off=$scantron_config->{'Qoff'};
 5499: 	my $on=$scantron_config->{'Qon'};
 5500: 	my $answer=${off}x$length;
 5501: 	if ($args->{'response'} eq 'none') {
 5502: 	    &scan_data($scan_data,
 5503: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5504: 	} else {
 5505: 	    if ($on eq 'letter') {
 5506: 		my @alphabet=('A'..'Z');
 5507: 		$answer=$alphabet[$args->{'response'}];
 5508: 	    } elsif ($on eq 'number') {
 5509: 		$answer=$args->{'response'}+1;
 5510: 		if ($answer == 10) { $answer = '0'; }
 5511: 	    } else {
 5512: 		substr($answer,$args->{'response'},1)=$on;
 5513: 	    }
 5514: 	    &scan_data($scan_data,
 5515: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5516: 	}
 5517: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5518: 	substr($line,$where-1,$length)=$answer;
 5519:     }
 5520:     return $line;
 5521: }
 5522: 
 5523: =pod
 5524: 
 5525: =item scan_data
 5526: 
 5527:     Edit or look up  an item in the scan_data hash.
 5528: 
 5529:   Arguments:
 5530:     $scan_data  - The hash (see scantron_getfile)
 5531:     $key        - shorthand of the key to edit (actual key is
 5532:                   scantronfilename_key).
 5533:     $data        - New value of the hash entry.
 5534:     $delete      - If true, the entry is removed from the hash.
 5535: 
 5536:   Returns:
 5537:     The new value of the hash table field (undefined if deleted).
 5538: 
 5539: =cut
 5540: 
 5541: 
 5542: sub scan_data {
 5543:     my ($scan_data,$key,$value,$delete)=@_;
 5544:     my $filename=$env{'form.scantron_selectfile'};
 5545:     if (defined($value)) {
 5546: 	$scan_data->{$filename.'_'.$key} = $value;
 5547:     }
 5548:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5549:     return $scan_data->{$filename.'_'.$key};
 5550: }
 5551: 
 5552: # ----- These first few routines are general use routines.----
 5553: 
 5554: # Return the number of occurences of a pattern in a string.
 5555: 
 5556: sub occurence_count {
 5557:     my ($string, $pattern) = @_;
 5558: 
 5559:     my @matches = ($string =~ /$pattern/g);
 5560: 
 5561:     return scalar(@matches);
 5562: }
 5563: 
 5564: 
 5565: # Take a string known to have digits and convert all the
 5566: # digits into letters in the range J,A..I.
 5567: 
 5568: sub digits_to_letters {
 5569:     my ($input) = @_;
 5570: 
 5571:     my @alphabet = ('J', 'A'..'I');
 5572: 
 5573:     my @input    = split(//, $input);
 5574:     my $output ='';
 5575:     for (my $i = 0; $i < scalar(@input); $i++) {
 5576: 	if ($input[$i] =~ /\d/) {
 5577: 	    $output .= $alphabet[$input[$i]];
 5578: 	} else {
 5579: 	    $output .= $input[$i];
 5580: 	}
 5581:     }
 5582:     return $output;
 5583: }
 5584: 
 5585: =pod 
 5586: 
 5587: =item scantron_parse_scanline
 5588: 
 5589:   Decodes a scanline from the selected scantron file
 5590: 
 5591:  Arguments:
 5592:     line             - The text of the scantron file line to process
 5593:     whichline        - Line number
 5594:     scantron_config  - Hash describing the format of the scantron lines.
 5595:     scan_data        - Hash of extra information about the scanline
 5596:                        (see scantron_getfile for more information)
 5597:     just_header      - True if should not process question answers but only
 5598:                        the stuff to the left of the answers.
 5599:  Returns:
 5600:    Hash containing the result of parsing the scanline
 5601: 
 5602:    Keys are all proceeded by the string 'scantron.'
 5603: 
 5604:        CODE    - the CODE in use for this scanline
 5605:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5606:                  by the operator
 5607:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5608:                             CODEs were selected, but the usage has been
 5609:                             forced by the operator
 5610:        ID  - student/employee ID
 5611:        PaperID - if used, the ID number printed on the sheet when the 
 5612:                  paper was scanned
 5613:        FirstName - first name from the sheet
 5614:        LastName  - last name from the sheet
 5615: 
 5616:      if just_header was not true these key may also exist
 5617: 
 5618:        missingerror - a list of bubble ranges that are considered to be answers
 5619:                       to a single question that don't have any bubbles filled in.
 5620:                       Of the form questionnumber:firstbubblenumber:count.
 5621:        doubleerror  - a list of bubble ranges that are considered to be answers
 5622:                       to a single question that have more than one bubble filled in.
 5623:                       Of the form questionnumber::firstbubblenumber:count
 5624:    
 5625:                 In the above, count is the number of bubble responses in the
 5626:                 input line needed to represent the possible answers to the question.
 5627:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5628:                 per line would have count = 2.
 5629: 
 5630:        maxquest     - the number of the last bubble line that was parsed
 5631: 
 5632:        (<number> starts at 1)
 5633:        <number>.answer - zero or more letters representing the selected
 5634:                          letters from the scanline for the bubble line 
 5635:                          <number>.
 5636:                          if blank there was either no bubble or there where
 5637:                          multiple bubbles, (consult the keys missingerror and
 5638:                          doubleerror if this is an error condition)
 5639: 
 5640: =cut
 5641: 
 5642: sub scantron_parse_scanline {
 5643:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5644: 
 5645:     my %record;
 5646:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5647:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5648:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5649:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5650: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5651: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5652: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5653: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5654: 	    $record{'scantron.CODE'}=substr($data,
 5655: 					    $$scantron_config{'CODEstart'}-1,
 5656: 					    $$scantron_config{'CODElength'});
 5657: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5658: 		$record{'scantron.useCODE'}=1;
 5659: 	    }
 5660: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5661: 		$record{'scantron.CODE_ignore_dup'}=1;
 5662: 	    }
 5663: 	} else {
 5664: 	    #FIXME interpret first N questions
 5665: 	}
 5666:     }
 5667:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5668: 				  $$scantron_config{'IDlength'});
 5669:     $record{'scantron.PaperID'}=
 5670: 	substr($data,$$scantron_config{'PaperID'}-1,
 5671: 	       $$scantron_config{'PaperIDlength'});
 5672:     $record{'scantron.FirstName'}=
 5673: 	substr($data,$$scantron_config{'FirstName'}-1,
 5674: 	       $$scantron_config{'FirstNamelength'});
 5675:     $record{'scantron.LastName'}=
 5676: 	substr($data,$$scantron_config{'LastName'}-1,
 5677: 	       $$scantron_config{'LastNamelength'});
 5678:     if ($just_header) { return \%record; }
 5679: 
 5680:     my @alphabet=('A'..'Z');
 5681:     my $questnum=0;
 5682:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5683: 
 5684:     chomp($questions);		# Get rid of any trailing \n.
 5685:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5686:     while (length($questions)) {
 5687: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5688:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5689:                              || 1;
 5690:         $questnum++;
 5691:         my $quest_id = $questnum;
 5692:         my $currentquest = substr($questions,0,$answer_length);
 5693:         $questions       = substr($questions,$answer_length);
 5694:         if (length($currentquest) < $answer_length) { next; }
 5695: 
 5696:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5697:             my $subquestnum = 1;
 5698:             my $subquestions = $currentquest;
 5699:             my @subanswers_needed = 
 5700:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5701:             foreach my $subans (@subanswers_needed) {
 5702:                 my $subans_length =
 5703:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5704:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5705:                 $subquestions   = substr($subquestions,$subans_length);
 5706:                 $quest_id = "$questnum.$subquestnum";
 5707:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5708:                     ($$scantron_config{'Qon'} eq 'number')) {
 5709:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5710:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5711:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5712:                 } else {
 5713:                     $ansnum = &scantron_validator_positional($ansnum,
 5714:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5715:                 }
 5716:                 $subquestnum ++;
 5717:             }
 5718:         } else {
 5719:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5720:                 ($$scantron_config{'Qon'} eq 'number')) {
 5721:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5722:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5723:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5724:             } else {
 5725:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5726:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5727:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5728:             }
 5729:         }
 5730:     }
 5731:     $record{'scantron.maxquest'}=$questnum;
 5732:     return \%record;
 5733: }
 5734: 
 5735: sub scantron_validator_lettnum {
 5736:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5737:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5738: 
 5739:     # Qon 'letter' implies for each slot in currquest we have:
 5740:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5741:     #    about anything else (esp. a value of Qoff) for missing
 5742:     #    bubbles.
 5743:     #
 5744:     # Qon 'number' implies each slot gives a digit that indexes the
 5745:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5746:     #    and * or ? for double bubbles on a single line.
 5747:     #
 5748: 
 5749:     my $matchon;
 5750:     if ($$scantron_config{'Qon'} eq 'letter') {
 5751:         $matchon = '[A-Z]';
 5752:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5753:         $matchon = '\d';
 5754:     }
 5755:     my $occurrences = 0;
 5756:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5757:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5758:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5759:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5760:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5761:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5762:         my @singlelines = split('',$currquest);
 5763:         foreach my $entry (@singlelines) {
 5764:             $occurrences = &occurence_count($entry,$matchon);
 5765:             if ($occurrences > 1) {
 5766:                 last;
 5767:             }
 5768:         } 
 5769:     } else {
 5770:         $occurrences = &occurence_count($currquest,$matchon); 
 5771:     }
 5772:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5773:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5774:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5775:             my $bubble = substr($currquest,$ans,1);
 5776:             if ($bubble =~ /$matchon/ ) {
 5777:                 if ($$scantron_config{'Qon'} eq 'number') {
 5778:                     if ($bubble == 0) {
 5779:                         $bubble = 10; 
 5780:                     }
 5781:                     $record->{"scantron.$ansnum.answer"} = 
 5782:                         $alphabet->[$bubble-1];
 5783:                 } else {
 5784:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5785:                 }
 5786:             } else {
 5787:                 $record->{"scantron.$ansnum.answer"}='';
 5788:             }
 5789:             $ansnum++;
 5790:         }
 5791:     } elsif (!defined($currquest)
 5792:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5793:             || (&occurence_count($currquest,$matchon) == 0)) {
 5794:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5795:             $record->{"scantron.$ansnum.answer"}='';
 5796:             $ansnum++;
 5797:         }
 5798:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5799:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5800:         }
 5801:     } else {
 5802:         if ($$scantron_config{'Qon'} eq 'number') {
 5803:             $currquest = &digits_to_letters($currquest);            
 5804:         }
 5805:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5806:             my $bubble = substr($currquest,$ans,1);
 5807:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5808:             $ansnum++;
 5809:         }
 5810:     }
 5811:     return $ansnum;
 5812: }
 5813: 
 5814: sub scantron_validator_positional {
 5815:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5816:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5817: 
 5818:     # Otherwise there's a positional notation;
 5819:     # each bubble line requires Qlength items, and there are filled in
 5820:     # bubbles for each case where there 'Qon' characters.
 5821:     #
 5822: 
 5823:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5824: 
 5825:     # If the split only gives us one element.. the full length of the
 5826:     # answer string, no bubbles are filled in:
 5827: 
 5828:     if ($answers_needed eq '') {
 5829:         return;
 5830:     }
 5831: 
 5832:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5833:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5834:             $record->{"scantron.$ansnum.answer"}='';
 5835:             $ansnum++;
 5836:         }
 5837:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5838:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5839:         }
 5840:     } elsif (scalar(@array) == 2) {
 5841:         my $location = length($array[0]);
 5842:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5843:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5844:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5845:             if ($ans eq $line_num) {
 5846:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5847:             } else {
 5848:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5849:             }
 5850:             $ansnum++;
 5851:          }
 5852:     } else {
 5853:         #  If there's more than one instance of a bubble character
 5854:         #  That's a double bubble; with positional notation we can
 5855:         #  record all the bubbles filled in as well as the
 5856:         #  fact this response consists of multiple bubbles.
 5857:         #
 5858:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5859:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5860:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5861:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5862:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5863:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5864:             my $doubleerror = 0;
 5865:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5866:                    (!$doubleerror)) {
 5867:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5868:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5869:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5870:                if (length(@currarray) > 2) {
 5871:                    $doubleerror = 1;
 5872:                } 
 5873:             }
 5874:             if ($doubleerror) {
 5875:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5876:             }
 5877:         } else {
 5878:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5879:         }
 5880:         my $item = $ansnum;
 5881:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5882:             $record->{"scantron.$item.answer"} = '';
 5883:             $item ++;
 5884:         }
 5885: 
 5886:         my @ans=@array;
 5887:         my $i=0;
 5888:         my $increment = 0;
 5889:         while ($#ans) {
 5890:             $i+=length($ans[0]) + $increment;
 5891:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5892:             my $bubble = $i%$$scantron_config{'Qlength'};
 5893:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5894:             shift(@ans);
 5895:             $increment = 1;
 5896:         }
 5897:         $ansnum += $answers_needed;
 5898:     }
 5899:     return $ansnum;
 5900: }
 5901: 
 5902: =pod
 5903: 
 5904: =item scantron_add_delay
 5905: 
 5906:    Adds an error message that occurred during the grading phase to a
 5907:    queue of messages to be shown after grading pass is complete
 5908: 
 5909:  Arguments:
 5910:    $delayqueue  - arrary ref of hash ref of error messages
 5911:    $scanline    - the scanline that caused the error
 5912:    $errormesage - the error message
 5913:    $errorcode   - a numeric code for the error
 5914: 
 5915:  Side Effects:
 5916:    updates the $delayqueue to have a new hash ref of the error
 5917: 
 5918: =cut
 5919: 
 5920: sub scantron_add_delay {
 5921:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5922:     push(@$delayqueue,
 5923: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5924: 	  'ecode' => $errorcode }
 5925: 	 );
 5926: }
 5927: 
 5928: =pod
 5929: 
 5930: =item scantron_find_student
 5931: 
 5932:    Finds the username for the current scanline
 5933: 
 5934:   Arguments:
 5935:    $scantron_record - hash result from scantron_parse_scanline
 5936:    $scan_data       - hash of correction information 
 5937:                       (see &scantron_getfile() form more information)
 5938:    $idmap           - hash from &username_to_idmap()
 5939:    $line            - number of current scanline
 5940:  
 5941:   Returns:
 5942:    Either 'username:domain' or undef if unknown
 5943: 
 5944: =cut
 5945: 
 5946: sub scantron_find_student {
 5947:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5948:     my $scanID=$$scantron_record{'scantron.ID'};
 5949:     if ($scanID =~ /^\s*$/) {
 5950:  	return &scan_data($scan_data,"$line.user");
 5951:     }
 5952:     foreach my $id (keys(%$idmap)) {
 5953:  	if (lc($id) eq lc($scanID)) {
 5954:  	    return $$idmap{$id};
 5955:  	}
 5956:     }
 5957:     return undef;
 5958: }
 5959: 
 5960: =pod
 5961: 
 5962: =item scantron_filter
 5963: 
 5964:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5965:    hidden resources was selected
 5966: 
 5967: =cut
 5968: 
 5969: sub scantron_filter {
 5970:     my ($curres)=@_;
 5971: 
 5972:     if (ref($curres) && $curres->is_problem()) {
 5973: 	# if the user has asked to not have either hidden
 5974: 	# or 'randomout' controlled resources to be graded
 5975: 	# don't include them
 5976: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5977: 	    && $curres->randomout) {
 5978: 	    return 0;
 5979: 	}
 5980: 	return 1;
 5981:     }
 5982:     return 0;
 5983: }
 5984: 
 5985: =pod
 5986: 
 5987: =item scantron_process_corrections
 5988: 
 5989:    Gets correction information out of submitted form data and corrects
 5990:    the scanline
 5991: 
 5992: =cut
 5993: 
 5994: sub scantron_process_corrections {
 5995:     my ($r) = @_;
 5996:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5997:     my ($scanlines,$scan_data)=&scantron_getfile();
 5998:     my $classlist=&Apache::loncoursedata::get_classlist();
 5999:     my $which=$env{'form.scantron_line'};
 6000:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6001:     my ($skip,$err,$errmsg);
 6002:     if ($env{'form.scantron_skip_record'}) {
 6003: 	$skip=1;
 6004:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6005: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6006: 	    $env{'form.scantron_domain'};
 6007: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6008: 	($line,$err,$errmsg)=
 6009: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6010: 				     'ID',{'newid'=>$newid,
 6011: 				    'username'=>$env{'form.scantron_username'},
 6012: 				    'domain'=>$env{'form.scantron_domain'}});
 6013:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6014: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6015: 	my $newCODE;
 6016: 	my %args;
 6017: 	if      ($resolution eq 'use_unfound') {
 6018: 	    $newCODE='use_unfound';
 6019: 	} elsif ($resolution eq 'use_found') {
 6020: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6021: 	} elsif ($resolution eq 'use_typed') {
 6022: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6023: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6024: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6025: 	}
 6026: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6027: 	    $args{'CODE_ignore_dup'}=1;
 6028: 	}
 6029: 	$args{'CODE'}=$newCODE;
 6030: 	($line,$err,$errmsg)=
 6031: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6032: 				     'CODE',\%args);
 6033:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6034: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6035: 	    ($line,$err,$errmsg)=
 6036: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6037: 					 $which,'answer',
 6038: 					 { 'question'=>$question,
 6039: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6040:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6041: 	    if ($err) { last; }
 6042: 	}
 6043:     }
 6044:     if ($err) {
 6045: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6046:     } else {
 6047: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6048: 	&scantron_putfile($scanlines,$scan_data);
 6049:     }
 6050: }
 6051: 
 6052: =pod
 6053: 
 6054: =item reset_skipping_status
 6055: 
 6056:    Forgets the current set of remember skipped scanlines (and thus
 6057:    reverts back to considering all lines in the
 6058:    scantron_skipped_<filename> file)
 6059: 
 6060: =cut
 6061: 
 6062: sub reset_skipping_status {
 6063:     my ($scanlines,$scan_data)=&scantron_getfile();
 6064:     &scan_data($scan_data,'remember_skipping',undef,1);
 6065:     &scantron_putfile(undef,$scan_data);
 6066: }
 6067: 
 6068: =pod
 6069: 
 6070: =item start_skipping
 6071: 
 6072:    Marks a scanline to be skipped. 
 6073: 
 6074: =cut
 6075: 
 6076: sub start_skipping {
 6077:     my ($scan_data,$i)=@_;
 6078:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6079:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6080: 	$remembered{$i}=2;
 6081:     } else {
 6082: 	$remembered{$i}=1;
 6083:     }
 6084:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6085: }
 6086: 
 6087: =pod
 6088: 
 6089: =item should_be_skipped
 6090: 
 6091:    Checks whether a scanline should be skipped.
 6092: 
 6093: =cut
 6094: 
 6095: sub should_be_skipped {
 6096:     my ($scanlines,$scan_data,$i)=@_;
 6097:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6098: 	# not redoing old skips
 6099: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6100: 	return 0;
 6101:     }
 6102:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6103: 
 6104:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6105: 	return 0;
 6106:     }
 6107:     return 1;
 6108: }
 6109: 
 6110: =pod
 6111: 
 6112: =item remember_current_skipped
 6113: 
 6114:    Discovers what scanlines are in the scantron_skipped_<filename>
 6115:    file and remembers them into scan_data for later use.
 6116: 
 6117: =cut
 6118: 
 6119: sub remember_current_skipped {
 6120:     my ($scanlines,$scan_data)=&scantron_getfile();
 6121:     my %to_remember;
 6122:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6123: 	if ($scanlines->{'skipped'}[$i]) {
 6124: 	    $to_remember{$i}=1;
 6125: 	}
 6126:     }
 6127: 
 6128:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6129:     &scantron_putfile(undef,$scan_data);
 6130: }
 6131: 
 6132: =pod
 6133: 
 6134: =item check_for_error
 6135: 
 6136:     Checks if there was an error when attempting to remove a specific
 6137:     scantron_.. bubble sheet data file. Prints out an error if
 6138:     something went wrong.
 6139: 
 6140: =cut
 6141: 
 6142: sub check_for_error {
 6143:     my ($r,$result)=@_;
 6144:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6145: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6146:     }
 6147: }
 6148: 
 6149: =pod
 6150: 
 6151: =item scantron_warning_screen
 6152: 
 6153:    Interstitial screen to make sure the operator has selected the
 6154:    correct options before we start the validation phase.
 6155: 
 6156: =cut
 6157: 
 6158: sub scantron_warning_screen {
 6159:     my ($button_text)=@_;
 6160:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6161:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6162:     my $CODElist;
 6163:     if ($scantron_config{'CODElocation'} &&
 6164: 	$scantron_config{'CODEstart'} &&
 6165: 	$scantron_config{'CODElength'}) {
 6166: 	$CODElist=$env{'form.scantron_CODElist'};
 6167: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6168: 	$CODElist=
 6169: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6170: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6171:     }
 6172:     return ('
 6173: <p>
 6174: <span class="LC_warning">
 6175: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6176: </p>
 6177: <table>
 6178: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6179: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6180: '.$CODElist.'
 6181: </table>
 6182: <br />
 6183: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6184: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6185: 
 6186: <br />
 6187: ');
 6188: }
 6189: 
 6190: =pod
 6191: 
 6192: =item scantron_do_warning
 6193: 
 6194:    Check if the operator has picked something for all required
 6195:    fields. Error out if something is missing.
 6196: 
 6197: =cut
 6198: 
 6199: sub scantron_do_warning {
 6200:     my ($r)=@_;
 6201:     my ($symb)=&get_symb($r);
 6202:     if (!$symb) {return '';}
 6203:     my $default_form_data=&defaultFormData($symb);
 6204:     $r->print(&scantron_form_start().$default_form_data);
 6205:     if ( $env{'form.selectpage'} eq '' ||
 6206: 	 $env{'form.scantron_selectfile'} eq '' ||
 6207: 	 $env{'form.scantron_format'} eq '' ) {
 6208: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6209: 	if ( $env{'form.selectpage'} eq '') {
 6210: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6211: 	} 
 6212: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6213: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6214: 	} 
 6215: 	if ( $env{'form.scantron_format'} eq '') {
 6216: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6217: 	} 
 6218:     } else {
 6219: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6220: 	$r->print('
 6221: '.$warning.'
 6222: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6223: <input type="hidden" name="command" value="scantron_validate" />
 6224: ');
 6225:     }
 6226:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6227:     return '';
 6228: }
 6229: 
 6230: =pod
 6231: 
 6232: =item scantron_form_start
 6233: 
 6234:     html hidden input for remembering all selected grading options
 6235: 
 6236: =cut
 6237: 
 6238: sub scantron_form_start {
 6239:     my ($max_bubble)=@_;
 6240:     my $result= <<SCANTRONFORM;
 6241: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6242:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6243:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6244:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6245:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6246:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6247:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6248:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6249:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6250:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6251: SCANTRONFORM
 6252: 
 6253:   my $line = 0;
 6254:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6255:        my $chunk =
 6256: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6257:        $chunk .=
 6258: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6259:        $chunk .= 
 6260:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6261:        $chunk .=
 6262:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6263:        $result .= $chunk;
 6264:        $line++;
 6265:    }
 6266:     return $result;
 6267: }
 6268: 
 6269: =pod
 6270: 
 6271: =item scantron_validate_file
 6272: 
 6273:     Dispatch routine for doing validation of a bubble sheet data file.
 6274: 
 6275:     Also processes any necessary information resets that need to
 6276:     occur before validation begins (ignore previous corrections,
 6277:     restarting the skipped records processing)
 6278: 
 6279: =cut
 6280: 
 6281: sub scantron_validate_file {
 6282:     my ($r) = @_;
 6283:     my ($symb)=&get_symb($r);
 6284:     if (!$symb) {return '';}
 6285:     my $default_form_data=&defaultFormData($symb);
 6286:     
 6287:     # do the detection of only doing skipped records first befroe we delete
 6288:     # them when doing the corrections reset
 6289:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6290: 	&reset_skipping_status();
 6291:     }
 6292:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6293: 	&remember_current_skipped();
 6294: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6295:     }
 6296: 
 6297:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6298: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6299: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6300: 	&check_for_error($r,&scantron_remove_scan_data());
 6301: 	$env{'form.scantron_options_ignore'}='done';
 6302:     }
 6303: 
 6304:     if ($env{'form.scantron_corrections'}) {
 6305: 	&scantron_process_corrections($r);
 6306:     }
 6307:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6308:     #get the student pick code ready
 6309:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6310:     my $nav_error;
 6311:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 6312:     if ($nav_error) {
 6313:         $r->print(&navmap_errormsg());
 6314:         return '';
 6315:     }
 6316:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6317:     $r->print($result);
 6318:     
 6319:     my @validate_phases=( 'sequence',
 6320: 			  'ID',
 6321: 			  'CODE',
 6322: 			  'doublebubble',
 6323: 			  'missingbubbles');
 6324:     if (!$env{'form.validatepass'}) {
 6325: 	$env{'form.validatepass'} = 0;
 6326:     }
 6327:     my $currentphase=$env{'form.validatepass'};
 6328: 
 6329: 
 6330:     my $stop=0;
 6331:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6332: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6333: 	$r->rflush();
 6334: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6335: 	{
 6336: 	    no strict 'refs';
 6337: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6338: 	}
 6339:     }
 6340:     if (!$stop) {
 6341: 	my $warning=&scantron_warning_screen('Start Grading');
 6342: 	$r->print(&mt('Validation process complete.').'<br />'.
 6343:                   $warning.
 6344:                   &mt('Perform verification for each student after storage of submissions?').
 6345:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6346:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6347:                   ('&nbsp;'x3).'<label>'.
 6348:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6349:                   '</label></span><br />'.
 6350:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6351:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6352:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6353:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6354:     } else {
 6355: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6356: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6357:     }
 6358:     if ($stop) {
 6359: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6360: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6361: 	    $r->print(' '.&mt('this error').' <br />');
 6362: 
 6363: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6364: 	} else {
 6365:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6366: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6367:             } else {
 6368:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6369:             }
 6370: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6371: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6372: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6373: 	}
 6374:     }
 6375:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6376:     return '';
 6377: }
 6378: 
 6379: 
 6380: =pod
 6381: 
 6382: =item scantron_remove_file
 6383: 
 6384:    Removes the requested bubble sheet data file, makes sure that
 6385:    scantron_original_<filename> is never removed
 6386: 
 6387: 
 6388: =cut
 6389: 
 6390: sub scantron_remove_file {
 6391:     my ($which)=@_;
 6392:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6393:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6394:     my $file='scantron_';
 6395:     if ($which eq 'corrected' || $which eq 'skipped') {
 6396: 	$file.=$which.'_';
 6397:     } else {
 6398: 	return 'refused';
 6399:     }
 6400:     $file.=$env{'form.scantron_selectfile'};
 6401:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6402: }
 6403: 
 6404: 
 6405: =pod
 6406: 
 6407: =item scantron_remove_scan_data
 6408: 
 6409:    Removes all scan_data correction for the requested bubble sheet
 6410:    data file.  (In the case that both the are doing skipped records we need
 6411:    to remember the old skipped lines for the time being so that element
 6412:    persists for a while.)
 6413: 
 6414: =cut
 6415: 
 6416: sub scantron_remove_scan_data {
 6417:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6418:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6419:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6420:     my @todelete;
 6421:     my $filename=$env{'form.scantron_selectfile'};
 6422:     foreach my $key (@keys) {
 6423: 	if ($key=~/^\Q$filename\E_/) {
 6424: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6425: 		$key=~/remember_skipping/) {
 6426: 		next;
 6427: 	    }
 6428: 	    push(@todelete,$key);
 6429: 	}
 6430:     }
 6431:     my $result;
 6432:     if (@todelete) {
 6433: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6434: 				       \@todelete,$cdom,$cname);
 6435:     } else {
 6436: 	$result = 'ok';
 6437:     }
 6438:     return $result;
 6439: }
 6440: 
 6441: 
 6442: =pod
 6443: 
 6444: =item scantron_getfile
 6445: 
 6446:     Fetches the requested bubble sheet data file (all 3 versions), and
 6447:     the scan_data hash
 6448:   
 6449:   Arguments:
 6450:     None
 6451: 
 6452:   Returns:
 6453:     2 hash references
 6454: 
 6455:      - first one has 
 6456:          orig      -
 6457:          corrected -
 6458:          skipped   -  each of which points to an array ref of the specified
 6459:                       file broken up into individual lines
 6460:          count     - number of scanlines
 6461:  
 6462:      - second is the scan_data hash possible keys are
 6463:        ($number refers to scanline numbered $number and thus the key affects
 6464:         only that scanline
 6465:         $bubline refers to the specific bubble line element and the aspects
 6466:         refers to that specific bubble line element)
 6467: 
 6468:        $number.user - username:domain to use
 6469:        $number.CODE_ignore_dup 
 6470:                     - ignore the duplicate CODE error 
 6471:        $number.useCODE
 6472:                     - use the CODE in the scanline as is
 6473:        $number.no_bubble.$bubline
 6474:                     - it is valid that there is no bubbled in bubble
 6475:                       at $number $bubline
 6476:        remember_skipping
 6477:                     - a frozen hash containing keys of $number and values
 6478:                       of either 
 6479:                         1 - we are on a 'do skipped records pass' and plan
 6480:                             on processing this line
 6481:                         2 - we are on a 'do skipped records pass' and this
 6482:                             scanline has been marked to skip yet again
 6483: 
 6484: =cut
 6485: 
 6486: sub scantron_getfile {
 6487:     #FIXME really would prefer a scantron directory
 6488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6489:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6490:     my $lines;
 6491:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6492: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6493:     my %scanlines;
 6494:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6495:     my $temp=$scanlines{'orig'};
 6496:     $scanlines{'count'}=$#$temp;
 6497: 
 6498:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6499: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6500:     if ($lines eq '-1') {
 6501: 	$scanlines{'corrected'}=[];
 6502:     } else {
 6503: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6504:     }
 6505:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6506: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6507:     if ($lines eq '-1') {
 6508: 	$scanlines{'skipped'}=[];
 6509:     } else {
 6510: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6511:     }
 6512:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6513:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6514:     my %scan_data = @tmp;
 6515:     return (\%scanlines,\%scan_data);
 6516: }
 6517: 
 6518: =pod
 6519: 
 6520: =item lonnet_putfile
 6521: 
 6522:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6523: 
 6524:  Arguments:
 6525:    $contents - data to store
 6526:    $filename - filename to store $contents into
 6527: 
 6528:  Returns:
 6529:    result value from &Apache::lonnet::finishuserfileupload
 6530: 
 6531: =cut
 6532: 
 6533: sub lonnet_putfile {
 6534:     my ($contents,$filename)=@_;
 6535:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6536:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6537:     $env{'form.sillywaytopassafilearound'}=$contents;
 6538:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6539: 
 6540: }
 6541: 
 6542: =pod
 6543: 
 6544: =item scantron_putfile
 6545: 
 6546:     Stores the current version of the bubble sheet data files, and the
 6547:     scan_data hash. (Does not modify the original version only the
 6548:     corrected and skipped versions.
 6549: 
 6550:  Arguments:
 6551:     $scanlines - hash ref that looks like the first return value from
 6552:                  &scantron_getfile()
 6553:     $scan_data - hash ref that looks like the second return value from
 6554:                  &scantron_getfile()
 6555: 
 6556: =cut
 6557: 
 6558: sub scantron_putfile {
 6559:     my ($scanlines,$scan_data) = @_;
 6560:     #FIXME really would prefer a scantron directory
 6561:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6562:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6563:     if ($scanlines) {
 6564: 	my $prefix='scantron_';
 6565: # no need to update orig, shouldn't change
 6566: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6567: #		    $env{'form.scantron_selectfile'});
 6568: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6569: 			$prefix.'corrected_'.
 6570: 			$env{'form.scantron_selectfile'});
 6571: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6572: 			$prefix.'skipped_'.
 6573: 			$env{'form.scantron_selectfile'});
 6574:     }
 6575:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6576: }
 6577: 
 6578: =pod
 6579: 
 6580: =item scantron_get_line
 6581: 
 6582:    Returns the correct version of the scanline
 6583: 
 6584:  Arguments:
 6585:     $scanlines - hash ref that looks like the first return value from
 6586:                  &scantron_getfile()
 6587:     $scan_data - hash ref that looks like the second return value from
 6588:                  &scantron_getfile()
 6589:     $i         - number of the requested line (starts at 0)
 6590: 
 6591:  Returns:
 6592:    A scanline, (either the original or the corrected one if it
 6593:    exists), or undef if the requested scanline should be
 6594:    skipped. (Either because it's an skipped scanline, or it's an
 6595:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6596:    pass.
 6597: 
 6598: =cut
 6599: 
 6600: sub scantron_get_line {
 6601:     my ($scanlines,$scan_data,$i)=@_;
 6602:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6603:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6604:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6605:     return $scanlines->{'orig'}[$i]; 
 6606: }
 6607: 
 6608: =pod
 6609: 
 6610: =item scantron_todo_count
 6611: 
 6612:     Counts the number of scanlines that need processing.
 6613: 
 6614:  Arguments:
 6615:     $scanlines - hash ref that looks like the first return value from
 6616:                  &scantron_getfile()
 6617:     $scan_data - hash ref that looks like the second return value from
 6618:                  &scantron_getfile()
 6619: 
 6620:  Returns:
 6621:     $count - number of scanlines to process
 6622: 
 6623: =cut
 6624: 
 6625: sub get_todo_count {
 6626:     my ($scanlines,$scan_data)=@_;
 6627:     my $count=0;
 6628:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6629: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6630: 	if ($line=~/^[\s\cz]*$/) { next; }
 6631: 	$count++;
 6632:     }
 6633:     return $count;
 6634: }
 6635: 
 6636: =pod
 6637: 
 6638: =item scantron_put_line
 6639: 
 6640:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6641:     data file.
 6642: 
 6643:  Arguments:
 6644:     $scanlines - hash ref that looks like the first return value from
 6645:                  &scantron_getfile()
 6646:     $scan_data - hash ref that looks like the second return value from
 6647:                  &scantron_getfile()
 6648:     $i         - line number to update
 6649:     $newline   - contents of the updated scanline
 6650:     $skip      - if true make the line for skipping and update the
 6651:                  'skipped' file
 6652: 
 6653: =cut
 6654: 
 6655: sub scantron_put_line {
 6656:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6657:     if ($skip) {
 6658: 	$scanlines->{'skipped'}[$i]=$newline;
 6659: 	&start_skipping($scan_data,$i);
 6660: 	return;
 6661:     }
 6662:     $scanlines->{'corrected'}[$i]=$newline;
 6663: }
 6664: 
 6665: =pod
 6666: 
 6667: =item scantron_clear_skip
 6668: 
 6669:    Remove a line from the 'skipped' file
 6670: 
 6671:  Arguments:
 6672:     $scanlines - hash ref that looks like the first return value from
 6673:                  &scantron_getfile()
 6674:     $scan_data - hash ref that looks like the second return value from
 6675:                  &scantron_getfile()
 6676:     $i         - line number to update
 6677: 
 6678: =cut
 6679: 
 6680: sub scantron_clear_skip {
 6681:     my ($scanlines,$scan_data,$i)=@_;
 6682:     if (exists($scanlines->{'skipped'}[$i])) {
 6683: 	undef($scanlines->{'skipped'}[$i]);
 6684: 	return 1;
 6685:     }
 6686:     return 0;
 6687: }
 6688: 
 6689: =pod
 6690: 
 6691: =item scantron_filter_not_exam
 6692: 
 6693:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6694:    filter out resources that are not marked as 'exam' mode
 6695: 
 6696: =cut
 6697: 
 6698: sub scantron_filter_not_exam {
 6699:     my ($curres)=@_;
 6700:     
 6701:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6702: 	# if the user has asked to not have either hidden
 6703: 	# or 'randomout' controlled resources to be graded
 6704: 	# don't include them
 6705: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6706: 	    && $curres->randomout) {
 6707: 	    return 0;
 6708: 	}
 6709: 	return 1;
 6710:     }
 6711:     return 0;
 6712: }
 6713: 
 6714: =pod
 6715: 
 6716: =item scantron_validate_sequence
 6717: 
 6718:     Validates the selected sequence, checking for resource that are
 6719:     not set to exam mode.
 6720: 
 6721: =cut
 6722: 
 6723: sub scantron_validate_sequence {
 6724:     my ($r,$currentphase) = @_;
 6725: 
 6726:     my $navmap=Apache::lonnavmaps::navmap->new();
 6727:     unless (ref($navmap)) {
 6728:         $r->print(&navmap_errormsg());
 6729:         return (1,$currentphase);
 6730:     }
 6731:     my (undef,undef,$sequence)=
 6732: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6733: 
 6734:     my $map=$navmap->getResourceByUrl($sequence);
 6735: 
 6736:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6737:                                     value="ignore" />');
 6738:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6739: 	my @resources=
 6740: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6741: 	if (@resources) {
 6742: 	    $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>");
 6743: 	    return (1,$currentphase);
 6744: 	}
 6745:     }
 6746: 
 6747:     return (0,$currentphase+1);
 6748: }
 6749: 
 6750: 
 6751: 
 6752: sub scantron_validate_ID {
 6753:     my ($r,$currentphase) = @_;
 6754:     
 6755:     #get student info
 6756:     my $classlist=&Apache::loncoursedata::get_classlist();
 6757:     my %idmap=&username_to_idmap($classlist);
 6758: 
 6759:     #get scantron line setup
 6760:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6761:     my ($scanlines,$scan_data)=&scantron_getfile();
 6762:     
 6763:     my $nav_error;
 6764:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
 6765:     if ($nav_error) {
 6766:         $r->print(&navmap_errormsg());
 6767:         return(1,$currentphase);
 6768:     }
 6769: 
 6770:     my %found=('ids'=>{},'usernames'=>{});
 6771:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6772: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6773: 	if ($line=~/^[\s\cz]*$/) { next; }
 6774: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6775: 						 $scan_data);
 6776: 	my $id=$$scan_record{'scantron.ID'};
 6777: 	my $found;
 6778: 	foreach my $checkid (keys(%idmap)) {
 6779: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6780: 	}
 6781: 	if ($found) {
 6782: 	    my $username=$idmap{$found};
 6783: 	    if ($found{'ids'}{$found}) {
 6784: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6785: 					 $line,'duplicateID',$found);
 6786: 		return(1,$currentphase);
 6787: 	    } elsif ($found{'usernames'}{$username}) {
 6788: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6789: 					 $line,'duplicateID',$username);
 6790: 		return(1,$currentphase);
 6791: 	    }
 6792: 	    #FIXME store away line we previously saw the ID on to use above
 6793: 	    $found{'ids'}{$found}++;
 6794: 	    $found{'usernames'}{$username}++;
 6795: 	} else {
 6796: 	    if ($id =~ /^\s*$/) {
 6797: 		my $username=&scan_data($scan_data,"$i.user");
 6798: 		if (defined($username) && $found{'usernames'}{$username}) {
 6799: 		    &scantron_get_correction($r,$i,$scan_record,
 6800: 					     \%scantron_config,
 6801: 					     $line,'duplicateID',$username);
 6802: 		    return(1,$currentphase);
 6803: 		} elsif (!defined($username)) {
 6804: 		    &scantron_get_correction($r,$i,$scan_record,
 6805: 					     \%scantron_config,
 6806: 					     $line,'incorrectID');
 6807: 		    return(1,$currentphase);
 6808: 		}
 6809: 		$found{'usernames'}{$username}++;
 6810: 	    } else {
 6811: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6812: 					 $line,'incorrectID');
 6813: 		return(1,$currentphase);
 6814: 	    }
 6815: 	}
 6816:     }
 6817: 
 6818:     return (0,$currentphase+1);
 6819: }
 6820: 
 6821: 
 6822: sub scantron_get_correction {
 6823:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6824: #FIXME in the case of a duplicated ID the previous line, probably need
 6825: #to show both the current line and the previous one and allow skipping
 6826: #the previous one or the current one
 6827: 
 6828:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6829: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6830: 			    " for PaperID <tt>[_1]</tt>",
 6831: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6832:     } else {
 6833: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6834: 			    " in scanline [_1] <pre>[_2]</pre>",
 6835: 			    $i,$line)."</p> \n");
 6836:     }
 6837:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6838: 			  "The name on the paper is [_2],[_3]",
 6839: 			  $$scan_record{'scantron.ID'},
 6840: 			  $$scan_record{'scantron.LastName'},
 6841: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6842: 
 6843:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6844:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6845:                            # Array populated for doublebubble or
 6846:     my @lines_to_correct;  # missingbubble errors to build javascript
 6847:                            # to validate radio button checking   
 6848: 
 6849:     if ($error =~ /ID$/) {
 6850: 	if ($error eq 'incorrectID') {
 6851: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6852: 		      "</p>\n");
 6853: 	} elsif ($error eq 'duplicateID') {
 6854: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6855: 	}
 6856: 	$r->print($message);
 6857: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6858: 	$r->print("\n<ul><li> ");
 6859: 	#FIXME it would be nice if this sent back the user ID and
 6860: 	#could do partial userID matches
 6861: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6862: 				       'scantron_username','scantron_domain'));
 6863: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6864: 	$r->print("\n@".
 6865: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6866: 
 6867: 	$r->print('</li>');
 6868:     } elsif ($error =~ /CODE$/) {
 6869: 	if ($error eq 'incorrectCODE') {
 6870: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6871: 	} elsif ($error eq 'duplicateCODE') {
 6872: 	    $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");
 6873: 	}
 6874: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6875: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6876: 	$r->print($message);
 6877: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6878: 	$r->print("\n<br /> ");
 6879: 	my $i=0;
 6880: 	if ($error eq 'incorrectCODE' 
 6881: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6882: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6883: 	    if ($closest > 0) {
 6884: 		foreach my $testcode (@{$closest}) {
 6885: 		    my $checked='';
 6886: 		    if (!$i) { $checked=' checked="checked"'; }
 6887: 		    $r->print("
 6888:    <label>
 6889:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
 6890:        ".&mt("Use the similar CODE [_1] instead.",
 6891: 	    "<b><tt>".$testcode."</tt></b>")."
 6892:     </label>
 6893:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6894: 		    $r->print("\n<br />");
 6895: 		    $i++;
 6896: 		}
 6897: 	    }
 6898: 	}
 6899: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6900: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
 6901: 	    $r->print("
 6902:     <label>
 6903:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
 6904:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6905: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6906:     </label>");
 6907: 	    $r->print("\n<br />");
 6908: 	}
 6909: 
 6910: 	$r->print(<<ENDSCRIPT);
 6911: <script type="text/javascript">
 6912: function change_radio(field) {
 6913:     var slct=document.scantronupload.scantron_CODE_resolution;
 6914:     var i;
 6915:     for (i=0;i<slct.length;i++) {
 6916:         if (slct[i].value==field) { slct[i].checked=true; }
 6917:     }
 6918: }
 6919: </script>
 6920: ENDSCRIPT
 6921: 	my $href="/adm/pickcode?".
 6922: 	   "form=".&escape("scantronupload").
 6923: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6924: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6925: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6926: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6927: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6928: 	    $r->print("
 6929:     <label>
 6930:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6931:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6932: 	     "<a target='_blank' href='$href'>","</a>")."
 6933:     </label> 
 6934:     ".&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\')" />'));
 6935: 	    $r->print("\n<br />");
 6936: 	}
 6937: 	$r->print("
 6938:     <label>
 6939:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6940:        ".&mt("Use [_1] as the CODE.",
 6941: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6942: 	$r->print("\n<br /><br />");
 6943:     } elsif ($error eq 'doublebubble') {
 6944: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6945: 
 6946: 	# The form field scantron_questions is acutally a list of line numbers.
 6947: 	# represented by this form so:
 6948: 
 6949: 	my $line_list = &questions_to_line_list($arg);
 6950: 
 6951: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6952: 		  $line_list.'" />');
 6953: 	$r->print($message);
 6954: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6955: 	foreach my $question (@{$arg}) {
 6956: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6957:                                                    $scan_record, $error);
 6958:             push(@lines_to_correct,@linenums);
 6959: 	}
 6960:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6961:     } elsif ($error eq 'missingbubble') {
 6962: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6963: 	$r->print($message);
 6964: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6965: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6966: 
 6967: 	# The form field scantron_questions is actually a list of line numbers not
 6968: 	# a list of question numbers. Therefore:
 6969: 	#
 6970: 	
 6971: 	my $line_list = &questions_to_line_list($arg);
 6972: 
 6973: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6974: 		  $line_list.'" />');
 6975: 	foreach my $question (@{$arg}) {
 6976: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6977:                                                    $scan_record, $error);
 6978:             push(@lines_to_correct,@linenums);
 6979: 	}
 6980:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6981:     } else {
 6982: 	$r->print("\n<ul>");
 6983:     }
 6984:     $r->print("\n</li></ul>");
 6985: }
 6986: 
 6987: sub verify_bubbles_checked {
 6988:     my (@ansnums) = @_;
 6989:     my $ansnumstr = join('","',@ansnums);
 6990:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6991:     my $output = (<<ENDSCRIPT);
 6992: <script type="text/javascript">
 6993: function verify_bubble_radio(form) {
 6994:     var ansnumArray = new Array ("$ansnumstr");
 6995:     var need_bubble_count = 0;
 6996:     for (var i=0; i<ansnumArray.length; i++) {
 6997:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6998:             var bubble_picked = 0; 
 6999:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 7000:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 7001:                     bubble_picked = 1;
 7002:                 }
 7003:             }
 7004:             if (bubble_picked == 0) {
 7005:                 need_bubble_count ++;
 7006:             }
 7007:         }
 7008:     }
 7009:     if (need_bubble_count) {
 7010:         alert("$warning");
 7011:         return;
 7012:     }
 7013:     form.submit(); 
 7014: }
 7015: </script>
 7016: ENDSCRIPT
 7017:     return $output;
 7018: }
 7019: 
 7020: =pod
 7021: 
 7022: =item  questions_to_line_list
 7023: 
 7024: Converts a list of questions into a string of comma separated
 7025: line numbers in the answer sheet used by the questions.  This is
 7026: used to fill in the scantron_questions form field.
 7027: 
 7028:   Arguments:
 7029:      questions    - Reference to an array of questions.
 7030: 
 7031: =cut
 7032: 
 7033: 
 7034: sub questions_to_line_list {
 7035:     my ($questions) = @_;
 7036:     my @lines;
 7037: 
 7038:     foreach my $item (@{$questions}) {
 7039:         my $question = $item;
 7040:         my ($first,$count,$last);
 7041:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7042:             $question = $1;
 7043:             my $subquestion = $2;
 7044:             $first = $first_bubble_line{$question-1} + 1;
 7045:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7046:             my $subcount = 1;
 7047:             while ($subcount<$subquestion) {
 7048:                 $first += $subans[$subcount-1];
 7049:                 $subcount ++;
 7050:             }
 7051:             $count = $subans[$subquestion-1];
 7052:         } else {
 7053: 	    $first   = $first_bubble_line{$question-1} + 1;
 7054: 	    $count   = $bubble_lines_per_response{$question-1};
 7055:         }
 7056:         $last = $first+$count-1;
 7057:         push(@lines, ($first..$last));
 7058:     }
 7059:     return join(',', @lines);
 7060: }
 7061: 
 7062: =pod 
 7063: 
 7064: =item prompt_for_corrections
 7065: 
 7066: Prompts for a potentially multiline correction to the
 7067: user's bubbling (factors out common code from scantron_get_correction
 7068: for multi and missing bubble cases).
 7069: 
 7070:  Arguments:
 7071:    $r           - Apache request object.
 7072:    $question    - The question number to prompt for.
 7073:    $scan_config - The scantron file configuration hash.
 7074:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7075:    $error       - Type of error
 7076: 
 7077:  Implicit inputs:
 7078:    %bubble_lines_per_response   - Starting line numbers for each question.
 7079:                                   Numbered from 0 (but question numbers are from
 7080:                                   1.
 7081:    %first_bubble_line           - Starting bubble line for each question.
 7082:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7083:                                   type problems render as separate sub-questions, 
 7084:                                   in exam mode. This hash contains a 
 7085:                                   comma-separated list of the lines per 
 7086:                                   sub-question.
 7087:    %responsetype_per_response   - essayresponse, formularesponse,
 7088:                                   stringresponse, imageresponse, reactionresponse,
 7089:                                   and organicresponse type problem parts can have
 7090:                                   multiple lines per response if the weight
 7091:                                   assigned exceeds 10.  In this case, only
 7092:                                   one bubble per line is permitted, but more 
 7093:                                   than one line might contain bubbles, e.g.
 7094:                                   bubbling of: line 1 - J, line 2 - J, 
 7095:                                   line 3 - B would assign 22 points.  
 7096: 
 7097: =cut
 7098: 
 7099: sub prompt_for_corrections {
 7100:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7101:     my ($current_line,$lines);
 7102:     my @linenums;
 7103:     my $questionnum = $question;
 7104:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7105:         $question = $1;
 7106:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7107:         my $subquestion = $2;
 7108:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7109:         my $subcount = 1;
 7110:         while ($subcount<$subquestion) {
 7111:             $current_line += $subans[$subcount-1];
 7112:             $subcount ++;
 7113:         }
 7114:         $lines = $subans[$subquestion-1];
 7115:     } else {
 7116:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7117:         $lines        = $bubble_lines_per_response{$question-1};
 7118:     }
 7119:     if ($lines > 1) {
 7120:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7121:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7122:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7123:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7124:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7125:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7126:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7127:             $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 />');
 7128:         } else {
 7129:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7130:         }
 7131:     }
 7132:     for (my $i =0; $i < $lines; $i++) {
 7133:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7134: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7135: 	        		  $questionnum,$error,split('', $selected));
 7136:         push(@linenums,$current_line);
 7137: 	$current_line++;
 7138:     }
 7139:     if ($lines > 1) {
 7140: 	$r->print("<hr /><br />");
 7141:     }
 7142:     return @linenums;
 7143: }
 7144: 
 7145: =pod
 7146: 
 7147: =item scantron_bubble_selector
 7148:   
 7149:    Generates the html radiobuttons to correct a single bubble line
 7150:    possibly showing the existing the selected bubbles if known
 7151: 
 7152:  Arguments:
 7153:     $r           - Apache request object
 7154:     $scan_config - hash from &get_scantron_config()
 7155:     $line        - Number of the line being displayed.
 7156:     $questionnum - Question number (may include subquestion)
 7157:     $error       - Type of error.
 7158:     @selected    - Array of bubbles picked on this line.
 7159: 
 7160: =cut
 7161: 
 7162: sub scantron_bubble_selector {
 7163:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7164:     my $max=$$scan_config{'Qlength'};
 7165: 
 7166:     my $scmode=$$scan_config{'Qon'};
 7167:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7168: 
 7169:     my @alphabet=('A'..'Z');
 7170:     $r->print(&Apache::loncommon::start_data_table().
 7171:               &Apache::loncommon::start_data_table_row());
 7172:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7173:     for (my $i=0;$i<$max+1;$i++) {
 7174: 	$r->print("\n".'<td align="center">');
 7175: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7176: 	else { $r->print('&nbsp;'); }
 7177: 	$r->print('</td>');
 7178:     }
 7179:     $r->print(&Apache::loncommon::end_data_table_row().
 7180:               &Apache::loncommon::start_data_table_row());
 7181:     for (my $i=0;$i<$max;$i++) {
 7182: 	$r->print("\n".
 7183: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7184: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7185:     }
 7186:     my $nobub_checked = ' ';
 7187:     if ($error eq 'missingbubble') {
 7188:         $nobub_checked = ' checked = "checked" ';
 7189:     }
 7190:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7191: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7192:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7193:               $line.'" value="'.$questionnum.'" /></td>');
 7194:     $r->print(&Apache::loncommon::end_data_table_row().
 7195:               &Apache::loncommon::end_data_table());
 7196: }
 7197: 
 7198: =pod
 7199: 
 7200: =item num_matches
 7201: 
 7202:    Counts the number of characters that are the same between the two arguments.
 7203: 
 7204:  Arguments:
 7205:    $orig - CODE from the scanline
 7206:    $code - CODE to match against
 7207: 
 7208:  Returns:
 7209:    $count - integer count of the number of same characters between the
 7210:             two arguments
 7211: 
 7212: =cut
 7213: 
 7214: sub num_matches {
 7215:     my ($orig,$code) = @_;
 7216:     my @code=split(//,$code);
 7217:     my @orig=split(//,$orig);
 7218:     my $same=0;
 7219:     for (my $i=0;$i<scalar(@code);$i++) {
 7220: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7221:     }
 7222:     return $same;
 7223: }
 7224: 
 7225: =pod
 7226: 
 7227: =item scantron_get_closely_matching_CODEs
 7228: 
 7229:    Cycles through all CODEs and finds the set that has the greatest
 7230:    number of same characters as the provided CODE
 7231: 
 7232:  Arguments:
 7233:    $allcodes - hash ref returned by &get_codes()
 7234:    $CODE     - CODE from the current scanline
 7235: 
 7236:  Returns:
 7237:    2 element list
 7238:     - first elements is number of how closely matching the best fit is 
 7239:       (5 means best set has 5 matching characters)
 7240:     - second element is an arrary ref containing the set of valid CODEs
 7241:       that best fit the passed in CODE
 7242: 
 7243: =cut
 7244: 
 7245: sub scantron_get_closely_matching_CODEs {
 7246:     my ($allcodes,$CODE)=@_;
 7247:     my @CODEs;
 7248:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7249: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7250:     }
 7251: 
 7252:     return ($#CODEs,$CODEs[-1]);
 7253: }
 7254: 
 7255: =pod
 7256: 
 7257: =item get_codes
 7258: 
 7259:    Builds a hash which has keys of all of the valid CODEs from the selected
 7260:    set of remembered CODEs.
 7261: 
 7262:  Arguments:
 7263:   $old_name - name of the set of remembered CODEs
 7264:   $cdom     - domain of the course
 7265:   $cnum     - internal course name
 7266: 
 7267:  Returns:
 7268:   %allcodes - keys are the valid CODEs, values are all 1
 7269: 
 7270: =cut
 7271: 
 7272: sub get_codes {
 7273:     my ($old_name, $cdom, $cnum) = @_;
 7274:     if (!$old_name) {
 7275: 	$old_name=$env{'form.scantron_CODElist'};
 7276:     }
 7277:     if (!$cdom) {
 7278: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7279:     }
 7280:     if (!$cnum) {
 7281: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7282:     }
 7283:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7284: 				    $cdom,$cnum);
 7285:     my %allcodes;
 7286:     if ($result{"type\0$old_name"} eq 'number') {
 7287: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7288:     } else {
 7289: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7290:     }
 7291:     return %allcodes;
 7292: }
 7293: 
 7294: =pod
 7295: 
 7296: =item scantron_validate_CODE
 7297: 
 7298:    Validates all scanlines in the selected file to not have any
 7299:    invalid or underspecified CODEs and that none of the codes are
 7300:    duplicated if this was requested.
 7301: 
 7302: =cut
 7303: 
 7304: sub scantron_validate_CODE {
 7305:     my ($r,$currentphase) = @_;
 7306:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7307:     if ($scantron_config{'CODElocation'} &&
 7308: 	$scantron_config{'CODEstart'} &&
 7309: 	$scantron_config{'CODElength'}) {
 7310: 	if (!defined($env{'form.scantron_CODElist'})) {
 7311: 	    &FIXME_blow_up()
 7312: 	}
 7313:     } else {
 7314: 	return (0,$currentphase+1);
 7315:     }
 7316:     
 7317:     my %usedCODEs;
 7318: 
 7319:     my %allcodes=&get_codes();
 7320: 
 7321:     my $nav_error;
 7322:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
 7323:     if ($nav_error) {
 7324:         $r->print(&navmap_errormsg());
 7325:         return(1,$currentphase);
 7326:     }
 7327: 
 7328:     my ($scanlines,$scan_data)=&scantron_getfile();
 7329:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7330: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7331: 	if ($line=~/^[\s\cz]*$/) { next; }
 7332: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7333: 						 $scan_data);
 7334: 	my $CODE=$$scan_record{'scantron.CODE'};
 7335: 	my $error=0;
 7336: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7337: 	    &scantron_get_correction($r,$i,$scan_record,
 7338: 				     \%scantron_config,
 7339: 				     $line,'incorrectCODE',\%allcodes);
 7340: 	    return(1,$currentphase);
 7341: 	}
 7342: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7343: 	    && !$$scan_record{'scantron.useCODE'}) {
 7344: 	    &scantron_get_correction($r,$i,$scan_record,
 7345: 				     \%scantron_config,
 7346: 				     $line,'incorrectCODE',\%allcodes);
 7347: 	    return(1,$currentphase);
 7348: 	}
 7349: 	if (exists($usedCODEs{$CODE}) 
 7350: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7351: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7352: 	    &scantron_get_correction($r,$i,$scan_record,
 7353: 				     \%scantron_config,
 7354: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7355: 	    return(1,$currentphase);
 7356: 	}
 7357: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7358:     }
 7359:     return (0,$currentphase+1);
 7360: }
 7361: 
 7362: =pod
 7363: 
 7364: =item scantron_validate_doublebubble
 7365: 
 7366:    Validates all scanlines in the selected file to not have any
 7367:    bubble lines with multiple bubbles marked.
 7368: 
 7369: =cut
 7370: 
 7371: sub scantron_validate_doublebubble {
 7372:     my ($r,$currentphase) = @_;
 7373:     #get student info
 7374:     my $classlist=&Apache::loncoursedata::get_classlist();
 7375:     my %idmap=&username_to_idmap($classlist);
 7376: 
 7377:     #get scantron line setup
 7378:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7379:     my ($scanlines,$scan_data)=&scantron_getfile();
 7380:     my $nav_error;
 7381:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
 7382:     if ($nav_error) {
 7383:         $r->print(&navmap_errormsg());
 7384:         return(1,$currentphase);
 7385:     }
 7386: 
 7387:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7388: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7389: 	if ($line=~/^[\s\cz]*$/) { next; }
 7390: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7391: 						 $scan_data);
 7392: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7393: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7394: 				 'doublebubble',
 7395: 				 $$scan_record{'scantron.doubleerror'});
 7396:     	return (1,$currentphase);
 7397:     }
 7398:     return (0,$currentphase+1);
 7399: }
 7400: 
 7401: 
 7402: sub scantron_get_maxbubble {
 7403:     my ($nav_error) = @_;
 7404: 
 7405:     if (defined($env{'form.scantron_maxbubble'}) &&
 7406: 	$env{'form.scantron_maxbubble'}) {
 7407: 	&restore_bubble_lines();
 7408: 	return $env{'form.scantron_maxbubble'};
 7409:     }
 7410: 
 7411:     my (undef, undef, $sequence) =
 7412: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7413: 
 7414:     my $navmap=Apache::lonnavmaps::navmap->new();
 7415:     unless (ref($navmap)) {
 7416:         if (ref($nav_error)) {
 7417:             $$nav_error = 1;
 7418:         }
 7419:         return;
 7420:     }
 7421:     my $map=$navmap->getResourceByUrl($sequence);
 7422:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7423: 
 7424:     &Apache::lonxml::clear_problem_counter();
 7425: 
 7426:     my $uname       = $env{'user.name'};
 7427:     my $udom        = $env{'user.domain'};
 7428:     my $cid         = $env{'request.course.id'};
 7429:     my $total_lines = 0;
 7430:     %bubble_lines_per_response = ();
 7431:     %first_bubble_line         = ();
 7432:     %subdivided_bubble_lines   = ();
 7433:     %responsetype_per_response = ();
 7434: 
 7435:     my $response_number = 0;
 7436:     my $bubble_line     = 0;
 7437:     foreach my $resource (@resources) {
 7438:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7439:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7440: 	    foreach my $part_id (@{$parts}) {
 7441:                 my $lines;
 7442: 
 7443: 	        # TODO - make this a persistent hash not an array.
 7444: 
 7445:                 # optionresponse, matchresponse and rankresponse type items 
 7446:                 # render as separate sub-questions in exam mode.
 7447:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7448:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7449:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7450:                     my ($numbub,$numshown);
 7451:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7452:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7453:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7454:                         }
 7455:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7456:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7457:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7458:                         }
 7459:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7460:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7461:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7462:                         }
 7463:                     }
 7464:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7465:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7466:                     }
 7467:                     my $bubbles_per_line = 10;
 7468:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7469:                     if (($numbub % $bubbles_per_line) != 0) {
 7470:                         $inner_bubble_lines++;
 7471:                     }
 7472:                     for (my $i=0; $i<$numshown; $i++) {
 7473:                         $subdivided_bubble_lines{$response_number} .= 
 7474:                             $inner_bubble_lines.',';
 7475:                     }
 7476:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7477:                     $lines = $numshown * $inner_bubble_lines;
 7478:                 } else {
 7479:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7480:                 } 
 7481: 
 7482:                 $first_bubble_line{$response_number} = $bubble_line;
 7483: 	        $bubble_lines_per_response{$response_number} = $lines;
 7484:                 $responsetype_per_response{$response_number} = 
 7485:                     $analysis->{$part_id.'.type'};
 7486: 	        $response_number++;
 7487: 
 7488: 	        $bubble_line +=  $lines;
 7489: 	        $total_lines +=  $lines;
 7490: 	    }
 7491:         }
 7492:     }
 7493:     &Apache::lonnet::delenv('scantron.');
 7494: 
 7495:     &save_bubble_lines();
 7496:     $env{'form.scantron_maxbubble'} =
 7497: 	$total_lines;
 7498:     return $env{'form.scantron_maxbubble'};
 7499: }
 7500: 
 7501: sub scantron_validate_missingbubbles {
 7502:     my ($r,$currentphase) = @_;
 7503:     #get student info
 7504:     my $classlist=&Apache::loncoursedata::get_classlist();
 7505:     my %idmap=&username_to_idmap($classlist);
 7506: 
 7507:     #get scantron line setup
 7508:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7509:     my ($scanlines,$scan_data)=&scantron_getfile();
 7510:     my $nav_error;
 7511:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
 7512:     if ($nav_error) {
 7513:         return(1,$currentphase);
 7514:     }
 7515:     if (!$max_bubble) { $max_bubble=2**31; }
 7516:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7517: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7518: 	if ($line=~/^[\s\cz]*$/) { next; }
 7519: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7520: 						 $scan_data);
 7521: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7522: 	my @to_correct;
 7523: 	
 7524: 	# Probably here's where the error is...
 7525: 
 7526: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7527:             my $lastbubble;
 7528:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7529:                my $question = $1;
 7530:                my $subquestion = $2;
 7531:                if (!defined($first_bubble_line{$question -1})) { next; }
 7532:                my $first = $first_bubble_line{$question-1};
 7533:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7534:                my $subcount = 1;
 7535:                while ($subcount<$subquestion) {
 7536:                    $first += $subans[$subcount-1];
 7537:                    $subcount ++;
 7538:                }
 7539:                my $count = $subans[$subquestion-1];
 7540:                $lastbubble = $first + $count;
 7541:             } else {
 7542:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7543:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7544:             }
 7545:             if ($lastbubble > $max_bubble) { next; }
 7546: 	    push(@to_correct,$missing);
 7547: 	}
 7548: 	if (@to_correct) {
 7549: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7550: 				     $line,'missingbubble',\@to_correct);
 7551: 	    return (1,$currentphase);
 7552: 	}
 7553: 
 7554:     }
 7555:     return (0,$currentphase+1);
 7556: }
 7557: 
 7558: 
 7559: sub scantron_process_students {
 7560:     my ($r) = @_;
 7561: 
 7562:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7563:     my ($symb)=&get_symb($r);
 7564:     if (!$symb) {
 7565: 	return '';
 7566:     }
 7567:     my $default_form_data=&defaultFormData($symb);
 7568: 
 7569:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7570:     my ($scanlines,$scan_data)=&scantron_getfile();
 7571:     my $classlist=&Apache::loncoursedata::get_classlist();
 7572:     my %idmap=&username_to_idmap($classlist);
 7573:     my $navmap=Apache::lonnavmaps::navmap->new();
 7574:     unless (ref($navmap)) {
 7575:         $r->print(&navmap_errormsg());
 7576:         return '';
 7577:     }  
 7578:     my $map=$navmap->getResourceByUrl($sequence);
 7579:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7580:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 7581:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
 7582:                             \%grader_randomlists_by_symb);
 7583:     my $resource_error;
 7584:     foreach my $resource (@resources) {
 7585:         my $ressymb;
 7586:         if (ref($resource)) {
 7587:             $ressymb = $resource->symb();
 7588:         } else {
 7589:             $resource_error = 1;
 7590:             last;
 7591:         }
 7592:         my ($analysis,$parts) =
 7593:             &scantron_partids_tograde($resource,$env{'request.course.id'},
 7594:                                       $env{'user.name'},$env{'user.domain'},1);
 7595:         $grader_partids_by_symb{$ressymb} = $parts;
 7596:         if (ref($analysis) eq 'HASH') {
 7597:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7598:                 $grader_randomlists_by_symb{$ressymb} = 
 7599:                     $analysis->{'parts_withrandomlist'};
 7600:             }
 7601:         }
 7602:     }
 7603:     if ($resource_error) {
 7604:         $r->print(&navmap_errormsg());
 7605:         return '';
 7606:     }
 7607: 
 7608:     my ($uname,$udom);
 7609:     my $result= <<SCANTRONFORM;
 7610: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7611:   <input type="hidden" name="command" value="scantron_configphase" />
 7612:   $default_form_data
 7613: SCANTRONFORM
 7614:     $r->print($result);
 7615: 
 7616:     my @delayqueue;
 7617:     my (%completedstudents,%scandata);
 7618:     
 7619:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7620:     my $count=&get_todo_count($scanlines,$scan_data);
 7621:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
 7622:  				    'Bubblesheet Progress',$count,
 7623: 				    'inline',undef,'scantronupload');
 7624:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7625: 					  'Processing first student');
 7626:     $r->print('<br />');
 7627:     my $start=&Time::HiRes::time();
 7628:     my $i=-1;
 7629:     my $started;
 7630: 
 7631:     my $nav_error;
 7632:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 7633:     if ($nav_error) {
 7634:         $r->print(&navmap_errormsg());
 7635:         return '';
 7636:     }
 7637: 
 7638:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7639:     # the user and return.
 7640: 
 7641:     if ($ssi_error) {
 7642: 	$r->print("</form>");
 7643: 	&ssi_print_error($r);
 7644: 	$r->print(&show_grading_menu_form($symb));
 7645:         &Apache::lonnet::remove_lock($lock);
 7646: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7647:     }
 7648: 
 7649:     my %lettdig = &letter_to_digits();
 7650:     my $numletts = scalar(keys(%lettdig));
 7651: 
 7652:     while ($i<$scanlines->{'count'}) {
 7653:  	($uname,$udom)=('','');
 7654:  	$i++;
 7655:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7656:  	if ($line=~/^[\s\cz]*$/) { next; }
 7657: 	if ($started) {
 7658: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7659: 						     'last student');
 7660: 	}
 7661: 	$started=1;
 7662:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7663:  						 $scan_data);
 7664:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7665:  					      \%idmap,$i)) {
 7666:   	    &scantron_add_delay(\@delayqueue,$line,
 7667:  				'Unable to find a student that matches',1);
 7668:  	    next;
 7669:   	}
 7670:  	if (exists $completedstudents{$uname}) {
 7671:  	    &scantron_add_delay(\@delayqueue,$line,
 7672:  				'Student '.$uname.' has multiple sheets',2);
 7673:  	    next;
 7674:  	}
 7675:   	($uname,$udom)=split(/:/,$uname);
 7676: 
 7677:         my (%partids_by_symb,$res_error);
 7678:         foreach my $resource (@resources) {
 7679:             my $ressymb;
 7680:             if (ref($resource)) {
 7681:                 $ressymb = $resource->symb();
 7682:             } else {
 7683:                 $res_error = 1;
 7684:                 last;
 7685:             }
 7686:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 7687:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 7688:                 my ($analysis,$parts) =
 7689:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7690:                 $partids_by_symb{$ressymb} = $parts;
 7691:             } else {
 7692:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
 7693:             }
 7694:         }
 7695: 
 7696:         if ($res_error) {
 7697:             &scantron_add_delay(\@delayqueue,$line,
 7698:                                 'An error occurred while grading student '.$uname,2);
 7699:             next;
 7700:         }
 7701: 
 7702: 	&Apache::lonxml::clear_problem_counter();
 7703:   	&Apache::lonnet::appenv($scan_record);
 7704: 
 7705: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7706: 	    &scantron_putfile($scanlines,$scan_data);
 7707: 	}
 7708: 	
 7709:         my $scancode;
 7710:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7711:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7712:             $scancode = $scan_record->{'scantron.CODE'};
 7713:         } else {
 7714:             $scancode = '';
 7715:         }
 7716: 
 7717:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7718:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7719:             $ssi_error = 0; # So end of handler error message does not trigger.
 7720:             $r->print("</form>");
 7721:             &ssi_print_error($r);
 7722:             $r->print(&show_grading_menu_form($symb));
 7723:             &Apache::lonnet::remove_lock($lock);
 7724:             return '';      # Why return ''?  Beats me.
 7725:         }
 7726: 
 7727: 	$completedstudents{$uname}={'line'=>$line};
 7728:         if ($env{'form.verifyrecord'}) {
 7729:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7730:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7731:             chomp($studentdata);
 7732:             $studentdata =~ s/\r$//;
 7733:             my $studentrecord = '';
 7734:             my $counter = -1;
 7735:             foreach my $resource (@resources) {
 7736:                 my $ressymb = $resource->symb();
 7737:                 ($counter,my $recording) =
 7738:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7739:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7740:                                              \%scantron_config,\%lettdig,$numletts);
 7741:                 $studentrecord .= $recording;
 7742:             }
 7743:             if ($studentrecord ne $studentdata) {
 7744:                 &Apache::lonxml::clear_problem_counter();
 7745:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7746:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7747:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7748:                     $r->print("</form>");
 7749:                     &ssi_print_error($r);
 7750:                     $r->print(&show_grading_menu_form($symb));
 7751:                     &Apache::lonnet::remove_lock($lock);
 7752:                     delete($completedstudents{$uname});
 7753:                     return '';
 7754:                 }
 7755:                 $counter = -1;
 7756:                 $studentrecord = '';
 7757:                 foreach my $resource (@resources) {
 7758:                     my $ressymb = $resource->symb();
 7759:                     ($counter,my $recording) =
 7760:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7761:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7762:                                                  \%scantron_config,\%lettdig,$numletts);
 7763:                     $studentrecord .= $recording;
 7764:                 }
 7765:                 if ($studentrecord ne $studentdata) {
 7766:                     $r->print('<p><span class="LC_error">');
 7767:                     if ($scancode eq '') {
 7768:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7769:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7770:                     } else {
 7771:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7772:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7773:                     }
 7774:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7775:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7776:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7777:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7778:                               &Apache::loncommon::start_data_table_row().
 7779:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7780:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7781:                               &Apache::loncommon::end_data_table_row().
 7782:                               &Apache::loncommon::start_data_table_row().
 7783:                               '<td>Stored submissions</td>'.
 7784:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7785:                               &Apache::loncommon::end_data_table_row().
 7786:                               &Apache::loncommon::end_data_table().'</p>');
 7787:                 } else {
 7788:                     $r->print('<br /><span class="LC_warning">'.
 7789:                              &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 />'.
 7790:                              &mt("As a consequence, this user's submission history records two tries.").
 7791:                                  '</span><br />');
 7792:                 }
 7793:             }
 7794:         }
 7795:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7796:     } continue {
 7797: 	&Apache::lonxml::clear_problem_counter();
 7798: 	&Apache::lonnet::delenv('scantron.');
 7799:     }
 7800:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7801:     &Apache::lonnet::remove_lock($lock);
 7802: #    my $lasttime = &Time::HiRes::time()-$start;
 7803: #    $r->print("<p>took $lasttime</p>");
 7804: 
 7805:     $r->print("</form>");
 7806:     $r->print(&show_grading_menu_form($symb));
 7807:     return '';
 7808: }
 7809: 
 7810: sub graders_resources_pass {
 7811:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
 7812:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
 7813:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
 7814:         foreach my $resource (@{$resources}) {
 7815:             my $ressymb = $resource->symb();
 7816:             my ($analysis,$parts) =
 7817:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
 7818:                                           $env{'user.name'},$env{'user.domain'},1);
 7819:             $grader_partids_by_symb->{$ressymb} = $parts;
 7820:             if (ref($analysis) eq 'HASH') {
 7821:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
 7822:                     $grader_randomlists_by_symb->{$ressymb} =
 7823:                         $analysis->{'parts_withrandomlist'};
 7824:                 }
 7825:             }
 7826:         }
 7827:     }
 7828:     return;
 7829: }
 7830: 
 7831: sub grade_student_bubbles {
 7832:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7833:     if (ref($resources) eq 'ARRAY') {
 7834:         my $count = 0;
 7835:         foreach my $resource (@{$resources}) {
 7836:             my $ressymb = $resource->symb();
 7837:             my %form = ('submitted'      => 'scantron',
 7838:                         'grade_target'   => 'grade',
 7839:                         'grade_username' => $uname,
 7840:                         'grade_domain'   => $udom,
 7841:                         'grade_courseid' => $env{'request.course.id'},
 7842:                         'grade_symb'     => $ressymb,
 7843:                         'CODE'           => $scancode
 7844:                        );
 7845:             if (ref($parts) eq 'HASH') {
 7846:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7847:                     foreach my $part (@{$parts->{$ressymb}}) {
 7848:                         $form{'scantron_questnum_start.'.$part} =
 7849:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7850:                         $count++;
 7851:                     }
 7852:                 }
 7853:             }
 7854:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7855:             return 'ssi_error' if ($ssi_error);
 7856:             last if (&Apache::loncommon::connection_aborted($r));
 7857:         }
 7858:     }
 7859:     return;
 7860: }
 7861: 
 7862: sub scantron_upload_scantron_data {
 7863:     my ($r)=@_;
 7864:     my $dom = $env{'request.role.domain'};
 7865:     my $domdesc = &Apache::lonnet::domain($dom,'description');
 7866:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
 7867:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7868: 							  'domainid',
 7869: 							  'coursename',$dom);
 7870:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
 7871:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
 7872:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7873:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
 7874:     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.");
 7875:     $r->print('
 7876: <script type="text/javascript" language="javascript">
 7877:     function checkUpload(formname) {
 7878: 	if (formname.upfile.value == "") {
 7879: 	    alert("'.$nofile_alert.'");
 7880: 	    return false;
 7881: 	}
 7882:         if (formname.courseid.value == "") {
 7883:             alert("'.$nocourseid_alert.'");
 7884:             return false;
 7885:         }
 7886: 	formname.submit();
 7887:     }
 7888: 
 7889:     function ToSyllabus() {
 7890:         var cdom = '."'$dom'".';
 7891:         var cnum = document.rules.courseid.value;
 7892:         if (cdom == "" || cdom == null) {
 7893:             return;
 7894:         }
 7895:         if (cnum == "" || cnum == null) {
 7896:            return;
 7897:         }
 7898:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
 7899:                             "height=350,width=350,scrollbars=yes,menubar=no");
 7900:         return;
 7901:     }
 7902: 
 7903: </script>
 7904: 
 7905: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
 7906: 
 7907: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7908: '.$default_form_data.
 7909:   &Apache::lonhtmlcommon::start_pick_box().
 7910:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
 7911:   '<input name="courseid" type="text" size="30" />'.$select_link.
 7912:   &Apache::lonhtmlcommon::row_closure().
 7913:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
 7914:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
 7915:   &Apache::lonhtmlcommon::row_closure().
 7916:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
 7917:   '<input name="domainid" type="hidden" />'.$domdesc.
 7918:   &Apache::lonhtmlcommon::row_closure().
 7919:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
 7920:   '<input type="file" name="upfile" size="50" />'.
 7921:   &Apache::lonhtmlcommon::row_closure(1).
 7922:   &Apache::lonhtmlcommon::end_pick_box().'<br />
 7923: 
 7924: <input name="command" value="scantronupload_save" type="hidden" />
 7925: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
 7926: </form>
 7927: ');
 7928:     return '';
 7929: }
 7930: 
 7931: 
 7932: sub scantron_upload_scantron_data_save {
 7933:     my($r)=@_;
 7934:     my ($symb)=&get_symb($r,1);
 7935:     my $doanotherupload=
 7936: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7937: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7938: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7939: 	'</form>'."\n";
 7940:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7941: 	!&Apache::lonnet::allowed('usc',
 7942: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7943: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
 7944: 	if ($symb) {
 7945: 	    $r->print(&show_grading_menu_form($symb));
 7946: 	} else {
 7947: 	    $r->print($doanotherupload);
 7948: 	}
 7949: 	return '';
 7950:     }
 7951:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7952:     my $uploadedfile;
 7953:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
 7954:     if (length($env{'form.upfile'}) < 2) {
 7955:         $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>'));
 7956:     } else {
 7957:         my $result = 
 7958:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
 7959:                                             $env{'form.courseid'},$env{'form.domainid'});
 7960: 	if ($result =~ m{^/uploaded/}) {
 7961: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
 7962:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
 7963: 			  '<span class="LC_filename">'.$result.'</span>'));
 7964:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
 7965:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
 7966:                                                        $env{'form.courseid'},$uploadedfile));
 7967: 	} else {
 7968: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
 7969:                           '<span class="LC_error">','</span>',$result,
 7970: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
 7971: 	}
 7972:     }
 7973:     if ($symb) {
 7974: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7975:     } else {
 7976: 	$r->print($doanotherupload);
 7977:     }
 7978:     return '';
 7979: }
 7980: 
 7981: sub validate_uploaded_scantron_file {
 7982:     my ($cdom,$cname,$fname) = @_;
 7983:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
 7984:     my @lines;
 7985:     if ($scanlines ne '-1') {
 7986:         @lines=split("\n",$scanlines,-1);
 7987:     }
 7988:     my $output;
 7989:     if (@lines) {
 7990:         my (%counts,$max_match_format);
 7991:         my ($max_match_count,$max_match_pct) = (0,0);
 7992:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
 7993:         my %idmap = &username_to_idmap($classlist);
 7994:         foreach my $key (keys(%idmap)) {
 7995:             my $lckey = lc($key);
 7996:             $idmap{$lckey} = $idmap{$key};
 7997:         }
 7998:         my %unique_formats;
 7999:         my @formatlines = &get_scantronformat_file();
 8000:         foreach my $line (@formatlines) {
 8001:             chomp($line);
 8002:             my @config = split(/:/,$line);
 8003:             my $idstart = $config[5];
 8004:             my $idlength = $config[6];
 8005:             if (($idstart ne '') && ($idlength > 0)) {
 8006:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
 8007:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
 8008:                 } else {
 8009:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
 8010:                 }
 8011:             }
 8012:         }
 8013:         foreach my $key (keys(%unique_formats)) {
 8014:             my ($idstart,$idlength) = split(':',$key);
 8015:             %{$counts{$key}} = (
 8016:                                'found'   => 0,
 8017:                                'total'   => 0,
 8018:                               );
 8019:             foreach my $line (@lines) {
 8020:                 next if ($line =~ /^#/);
 8021:                 next if ($line =~ /^[\s\cz]*$/);
 8022:                 my $id = substr($line,$idstart-1,$idlength);
 8023:                 $id = lc($id);
 8024:                 if (exists($idmap{$id})) {
 8025:                     $counts{$key}{'found'} ++;
 8026:                 }
 8027:                 $counts{$key}{'total'} ++;
 8028:             }
 8029:             if ($counts{$key}{'total'}) {
 8030:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
 8031:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
 8032:                     $max_match_pct = $percent_match;
 8033:                     $max_match_format = $key;
 8034:                     $max_match_count = $counts{$key}{'total'};
 8035:                 }
 8036:             }
 8037:         }
 8038:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
 8039:             my $format_descs;
 8040:             my $numwithformat = @{$unique_formats{$max_match_format}};
 8041:             for (my $i=0; $i<$numwithformat; $i++) {
 8042:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
 8043:                 if ($i<$numwithformat-2) {
 8044:                     $format_descs .= '"<i>'.$desc.'</i>", ';
 8045:                 } elsif ($i==$numwithformat-2) {
 8046:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
 8047:                 } elsif ($i==$numwithformat-1) {
 8048:                     $format_descs .= '"<i>'.$desc.'</i>"';
 8049:                 }
 8050:             }
 8051:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
 8052:             $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).
 8053:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
 8054:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
 8055:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
 8056:                                   '<i>'.$cdom.'</i>').'</li>'.
 8057:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
 8058:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
 8059:                        '</ul>';
 8060:         }
 8061:     } else {
 8062:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
 8063:     }
 8064:     return $output;
 8065: }
 8066: 
 8067: sub valid_file {
 8068:     my ($requested_file)=@_;
 8069:     foreach my $filename (sort(&scantron_filenames())) {
 8070: 	if ($requested_file eq $filename) { return 1; }
 8071:     }
 8072:     return 0;
 8073: }
 8074: 
 8075: sub scantron_download_scantron_data {
 8076:     my ($r)=@_;
 8077:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 8078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8080:     my $file=$env{'form.scantron_selectfile'};
 8081:     if (! &valid_file($file)) {
 8082: 	$r->print('
 8083: 	<p>
 8084: 	    '.&mt('The requested file name was invalid.').'
 8085:         </p>
 8086: ');
 8087: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 8088: 	return;
 8089:     }
 8090:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 8091:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 8092:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 8093:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 8094:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 8095:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 8096:     $r->print('
 8097:     <p>
 8098: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 8099: 	      '<a href="'.$orig.'">','</a>').'
 8100:     </p>
 8101:     <p>
 8102: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 8103: 	      '<a href="'.$corrected.'">','</a>').'
 8104:     </p>
 8105:     <p>
 8106: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 8107: 	      '<a href="'.$skipped.'">','</a>').'
 8108:     </p>
 8109: ');
 8110:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 8111:     return '';
 8112: }
 8113: 
 8114: sub checkscantron_results {
 8115:     my ($r) = @_;
 8116:     my ($symb)=&get_symb($r);
 8117:     if (!$symb) {return '';}
 8118:     my $grading_menu_button=&show_grading_menu_form($symb);
 8119:     my $cid = $env{'request.course.id'};
 8120:     my %lettdig = &letter_to_digits();
 8121:     my $numletts = scalar(keys(%lettdig));
 8122:     my $cnum = $env{'course.'.$cid.'.num'};
 8123:     my $cdom = $env{'course.'.$cid.'.domain'};
 8124:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 8125:     my %record;
 8126:     my %scantron_config =
 8127:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 8128:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 8129:     my $classlist=&Apache::loncoursedata::get_classlist();
 8130:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 8131:     my $navmap=Apache::lonnavmaps::navmap->new();
 8132:     unless (ref($navmap)) {
 8133:         $r->print(&navmap_errormsg());
 8134:         return '';
 8135:     }
 8136:     my $map=$navmap->getResourceByUrl($sequence);
 8137:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 8138:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
 8139:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
 8140: 
 8141:     my ($uname,$udom);
 8142:     my (%scandata,%lastname,%bylast);
 8143:     $r->print('
 8144: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 8145: 
 8146:     my @delayqueue;
 8147:     my %completedstudents;
 8148: 
 8149:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 8150:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
 8151:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
 8152:                                     'inline',undef,'checkscantron');
 8153:     my ($username,$domain,$started);
 8154:     my $nav_error;
 8155:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
 8156:     if ($nav_error) {
 8157:         $r->print(&navmap_errormsg());
 8158:         return '';
 8159:     }
 8160: 
 8161:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 8162:                                           'Processing first student');
 8163:     my $start=&Time::HiRes::time();
 8164:     my $i=-1;
 8165: 
 8166:     while ($i<$scanlines->{'count'}) {
 8167:         ($username,$domain,$uname)=('','','');
 8168:         $i++;
 8169:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 8170:         if ($line=~/^[\s\cz]*$/) { next; }
 8171:         if ($started) {
 8172:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 8173:                                                      'last student');
 8174:         }
 8175:         $started=1;
 8176:         my $scan_record=
 8177:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 8178:                                                      $scan_data);
 8179:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 8180:                                                               \%idmap,$i)) {
 8181:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8182:                                 'Unable to find a student that matches',1);
 8183:             next;
 8184:         }
 8185:         if (exists $completedstudents{$uname}) {
 8186:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 8187:                                 'Student '.$uname.' has multiple sheets',2);
 8188:             next;
 8189:         }
 8190:         my $pid = $scan_record->{'scantron.ID'};
 8191:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 8192:         push(@{$bylast{$lastname{$pid}}},$pid);
 8193:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 8194:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 8195:         chomp($scandata{$pid});
 8196:         $scandata{$pid} =~ s/\r$//;
 8197:         ($username,$domain)=split(/:/,$uname);
 8198:         my $counter = -1;
 8199:         foreach my $resource (@resources) {
 8200:             my $parts;
 8201:             my $ressymb = $resource->symb();
 8202:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
 8203:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
 8204:                 (my $analysis,$parts) =
 8205:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 8206:             } else {
 8207:                 $parts = $grader_partids_by_symb{$ressymb};
 8208:             }
 8209:             ($counter,my $recording) =
 8210:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 8211:                                          $scandata{$pid},$parts,
 8212:                                          \%scantron_config,\%lettdig,$numletts);
 8213:             $record{$pid} .= $recording;
 8214:         }
 8215:     }
 8216:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8217:     $r->print('<br />');
 8218:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8219:     $passed = 0;
 8220:     $failed = 0;
 8221:     $numstudents = 0;
 8222:     foreach my $last (sort(keys(%bylast))) {
 8223:         if (ref($bylast{$last}) eq 'ARRAY') {
 8224:             foreach my $pid (sort(@{$bylast{$last}})) {
 8225:                 my $showscandata = $scandata{$pid};
 8226:                 my $showrecord = $record{$pid};
 8227:                 $showscandata =~ s/\s/&nbsp;/g;
 8228:                 $showrecord =~ s/\s/&nbsp;/g;
 8229:                 if ($scandata{$pid} eq $record{$pid}) {
 8230:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8231:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8232: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8233: '</tr>'."\n".
 8234: '<tr class="'.$css_class.'">'."\n".
 8235: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8236:                     $passed ++;
 8237:                 } else {
 8238:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8239:                     $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".
 8240: '</tr>'."\n".
 8241: '<tr class="'.$css_class.'">'."\n".
 8242: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8243: '</tr>'."\n";
 8244:                     $failed ++;
 8245:                 }
 8246:                 $numstudents ++;
 8247:             }
 8248:         }
 8249:     }
 8250:     $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>');
 8251:     $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>');
 8252:     if ($passed) {
 8253:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
 8254:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8255:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8256:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8257:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8258:                  $okstudents."\n".
 8259:                  &Apache::loncommon::end_data_table().'<br />');
 8260:     }
 8261:     if ($failed) {
 8262:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
 8263:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8264:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8265:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8266:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8267:                  $badstudents."\n".
 8268:                  &Apache::loncommon::end_data_table()).'<br />'.
 8269:                  &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.');  
 8270:     }
 8271:     $r->print('</form><br />'.$grading_menu_button);
 8272:     return;
 8273: }
 8274: 
 8275: sub verify_scantron_grading {
 8276:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 8277:         $scantron_config,$lettdig,$numletts) = @_;
 8278:     my ($record,%expected,%startpos);
 8279:     return ($counter,$record) if (!ref($resource));
 8280:     return ($counter,$record) if (!$resource->is_problem());
 8281:     my $symb = $resource->symb();
 8282:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 8283:     foreach my $part_id (@{$partids}) {
 8284:         $counter ++;
 8285:         $expected{$part_id} = 0;
 8286:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8287:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8288:             foreach my $item (@sub_lines) {
 8289:                 $expected{$part_id} += $item;
 8290:             }
 8291:         } else {
 8292:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8293:         }
 8294:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8295:     }
 8296:     if ($symb) {
 8297:         my %recorded;
 8298:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8299:         if ($returnhash{'version'}) {
 8300:             my %lasthash=();
 8301:             my $version;
 8302:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8303:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8304:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8305:                 }
 8306:             }
 8307:             foreach my $key (keys(%lasthash)) {
 8308:                 if ($key =~ /\.scantron$/) {
 8309:                     my $value = &unescape($lasthash{$key});
 8310:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8311:                     if ($value eq '') {
 8312:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8313:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8314:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8315:                             }
 8316:                         }
 8317:                     } else {
 8318:                         my @tocheck;
 8319:                         my @items = split(//,$value);
 8320:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8321:                             ($scantron_config->{'Qon'} eq 'number')) {
 8322:                             if (@items < $expected{$part_id}) {
 8323:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8324:                                 my @singles = split(//,$fragment);
 8325:                                 foreach my $pos (@singles) {
 8326:                                     if ($pos eq ' ') {
 8327:                                         push(@tocheck,$pos);
 8328:                                     } else {
 8329:                                         my $next = shift(@items);
 8330:                                         push(@tocheck,$next);
 8331:                                     }
 8332:                                 }
 8333:                             } else {
 8334:                                 @tocheck = @items;
 8335:                             }
 8336:                             foreach my $letter (@tocheck) {
 8337:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8338:                                     if ($letter !~ /^[A-J]$/) {
 8339:                                         $letter = $scantron_config->{'Qoff'};
 8340:                                     }
 8341:                                     $recorded{$part_id} .= $letter;
 8342:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8343:                                     my $digit;
 8344:                                     if ($letter !~ /^[A-J]$/) {
 8345:                                         $digit = $scantron_config->{'Qoff'};
 8346:                                     } else {
 8347:                                         $digit = $lettdig->{$letter};
 8348:                                     }
 8349:                                     $recorded{$part_id} .= $digit;
 8350:                                 }
 8351:                             }
 8352:                         } else {
 8353:                             @tocheck = @items;
 8354:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8355:                                 my $curr_sub = shift(@tocheck);
 8356:                                 my $digit;
 8357:                                 if ($curr_sub =~ /^[A-J]$/) {
 8358:                                     $digit = $lettdig->{$curr_sub}-1;
 8359:                                 }
 8360:                                 if ($curr_sub eq 'J') {
 8361:                                     $digit += scalar($numletts);
 8362:                                 }
 8363:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8364:                                     if ($j == $digit) {
 8365:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8366:                                     } else {
 8367:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8368:                                     }
 8369:                                 }
 8370:                             }
 8371:                         }
 8372:                     }
 8373:                 }
 8374:             }
 8375:         }
 8376:         foreach my $part_id (@{$partids}) {
 8377:             if ($recorded{$part_id} eq '') {
 8378:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8379:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8380:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8381:                     }
 8382:                 }
 8383:             }
 8384:             $record .= $recorded{$part_id};
 8385:         }
 8386:     }
 8387:     return ($counter,$record);
 8388: }
 8389: 
 8390: sub letter_to_digits { 
 8391:     my %lettdig = (
 8392:                     A => 1,
 8393:                     B => 2,
 8394:                     C => 3,
 8395:                     D => 4,
 8396:                     E => 5,
 8397:                     F => 6,
 8398:                     G => 7,
 8399:                     H => 8,
 8400:                     I => 9,
 8401:                     J => 0,
 8402:                   );
 8403:     return %lettdig;
 8404: }
 8405: 
 8406: 
 8407: #-------- end of section for handling grading scantron forms -------
 8408: #
 8409: #-------------------------------------------------------------------
 8410: 
 8411: #-------------------------- Menu interface -------------------------
 8412: #
 8413: #--- Show a Grading Menu button - Calls the next routine ---
 8414: sub show_grading_menu_form {
 8415:     my ($symb)=@_;
 8416:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8417: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8418: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8419: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8420: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8421: 	'</form>'."\n";
 8422:     return $result;
 8423: }
 8424: 
 8425: # -- Retrieve choices for grading form
 8426: sub savedState {
 8427:     my %savedState = ();
 8428:     if ($env{'form.saveState'}) {
 8429: 	foreach (split(/:/,$env{'form.saveState'})) {
 8430: 	    my ($key,$value) = split(/=/,$_,2);
 8431: 	    $savedState{$key} = $value;
 8432: 	}
 8433:     }
 8434:     return \%savedState;
 8435: }
 8436: 
 8437: sub grading_menu {
 8438:     my ($request) = @_;
 8439:     my ($symb)=&get_symb($request);
 8440:     if (!$symb) {return '';}
 8441:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8442:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8443: 
 8444:     $request->print($table);
 8445:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8446:                   'handgrade'=>$hdgrade,
 8447:                   'probTitle'=>$probTitle,
 8448:                   'command'=>'submit_options',
 8449:                   'saveState'=>"",
 8450:                   'gradingMenu'=>1,
 8451:                   'showgrading'=>"yes");
 8452:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8453:     my @menu = ({ url => $url,
 8454:                      name => &mt('Manual Grading/View Submissions'),
 8455:                      short_description =>
 8456:     &mt('Start the process of hand grading submissions.'),
 8457:                  });
 8458:     $fields{'command'} = 'csvform';
 8459:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8460:     push(@menu, { url => $url,
 8461:                    name => &mt('Upload Scores'),
 8462:                    short_description =>
 8463:             &mt('Specify a file containing the class scores for current resource.')});
 8464:     $fields{'command'} = 'processclicker';
 8465:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8466:     push(@menu, { url => $url,
 8467:                    name => &mt('Process Clicker'),
 8468:                    short_description =>
 8469:             &mt('Specify a file containing the clicker information for this resource.')});
 8470:     $fields{'command'} = 'scantron_selectphase';
 8471:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8472:     push(@menu, { url => $url,
 8473:                    name => &mt('Grade/Manage/Review Bubblesheets'),
 8474:                    short_description =>
 8475:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8476:     $fields{'command'} = 'verify';
 8477:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8478:     push(@menu, { url => "",
 8479:                    name => &mt('Verify Receipt'),
 8480:                    short_description =>
 8481:             &mt('')});
 8482:     # Create the menu
 8483:     my $Str;
 8484:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8485:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8486:     $Str .= '<input type="hidden" name="command" value="" />'.
 8487:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8488: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8489: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8490: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8491: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8492: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8493:     foreach my $menudata (@menu) {
 8494:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8495:             $Str .='    <h3><a '.
 8496:                 $menudata->{'jscript'}.
 8497:                 ' href="'.
 8498:                 $menudata->{'url'}.'" >'.
 8499:                 $menudata->{'name'}."</a></h3>\n";
 8500:         } else {
 8501:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8502:                 $menudata->{'jscript'}.
 8503:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8504:                 ' /> '.
 8505:                 &Apache::lonnet::recprefix($env{'request.course.id'}).
 8506:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8507:         }
 8508:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8509:             "\n";
 8510:     }
 8511:     $Str .="</form>\n";
 8512:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8513:     $request->print(<<GRADINGMENUJS);
 8514: <script type="text/javascript" language="javascript">
 8515:     function checkChoice(formname,val,cmdx) {
 8516: 	if (val <= 2) {
 8517: 	    var cmd = radioSelection(formname.radioChoice);
 8518: 	    var cmdsave = cmd;
 8519: 	} else {
 8520: 	    cmd = cmdx;
 8521: 	    cmdsave = 'submission';
 8522: 	}
 8523: 	formname.command.value = cmd;
 8524: 	if (val < 5) formname.submit();
 8525: 	if (val == 5) {
 8526: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8527: 	        return false;
 8528: 	    } else {
 8529: 	        formname.submit();
 8530: 	    }
 8531: 	}
 8532:     }
 8533: 
 8534:     function checkReceiptNo(formname,nospace) {
 8535: 	var receiptNo = formname.receipt.value;
 8536: 	var checkOpt = false;
 8537: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8538: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8539: 	if (checkOpt) {
 8540: 	    alert("$receiptalert");
 8541: 	    formname.receipt.value = "";
 8542: 	    formname.receipt.focus();
 8543: 	    return false;
 8544: 	}
 8545: 	return true;
 8546:     }
 8547: </script>
 8548: GRADINGMENUJS
 8549:     &commonJSfunctions($request);
 8550:     return $Str;    
 8551: }
 8552: 
 8553: 
 8554: #--- Displays the submissions first page -------
 8555: sub submit_options {
 8556:     my ($request) = @_;
 8557:     my ($symb)=&get_symb($request);
 8558:     if (!$symb) {return '';}
 8559:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8560: 
 8561:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8562:     $request->print(<<GRADINGMENUJS);
 8563: <script type="text/javascript" language="javascript">
 8564:     function checkChoice(formname,val,cmdx) {
 8565: 	if (val <= 2) {
 8566: 	    var cmd = radioSelection(formname.radioChoice);
 8567: 	    var cmdsave = cmd;
 8568: 	} else {
 8569: 	    cmd = cmdx;
 8570: 	    cmdsave = 'submission';
 8571: 	}
 8572: 	formname.command.value = cmd;
 8573: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8574: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8575: 	if (val < 5) formname.submit();
 8576: 	if (val == 5) {
 8577: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8578: 	    formname.submit();
 8579: 	}
 8580: 	if (val < 7) formname.submit();
 8581:     }
 8582: 
 8583:     function checkReceiptNo(formname,nospace) {
 8584: 	var receiptNo = formname.receipt.value;
 8585: 	var checkOpt = false;
 8586: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8587: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8588: 	if (checkOpt) {
 8589: 	    alert("$receiptalert");
 8590: 	    formname.receipt.value = "";
 8591: 	    formname.receipt.focus();
 8592: 	    return false;
 8593: 	}
 8594: 	return true;
 8595:     }
 8596: </script>
 8597: GRADINGMENUJS
 8598:     &commonJSfunctions($request);
 8599:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8600:     my $result;
 8601:     my (undef,$sections) = &getclasslist('all','0');
 8602:     my $savedState = &savedState();
 8603:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8604:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8605:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8606:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8607: 
 8608:     # Preselect sections
 8609:     my $selsec="";
 8610:     if (ref($sections)) {
 8611:         foreach my $section (sort(@$sections)) {
 8612:             $selsec.='<option value="'.$section.'" '.
 8613:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8614:         }
 8615:     }
 8616: 
 8617:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8618: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8619: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8620: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8621: 	'<input type="hidden" name="command"     value="" />'."\n".
 8622: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8623: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8624: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8625: 
 8626:     $result.='
 8627:     <div class="LC_grade_select_mode">
 8628:       <div class="LC_grade_select_mode_current">
 8629:         <h2>
 8630:           '.&mt('Grade Current Resource').'
 8631:         </h2>
 8632:         <div class="LC_grade_select_mode_body">
 8633:           <div class="LC_grades_resource_info">
 8634:            '.$table.'
 8635:           </div>
 8636:           <div class="LC_grade_select_mode_selector">
 8637:              <div class="LC_grade_select_mode_selector_header">
 8638:                 '.&mt('Sections').'
 8639:              </div>
 8640:              <div class="LC_grade_select_mode_selector_body">
 8641:                <select name="section" multiple="multiple" size="5">'."\n";
 8642:     if (ref($sections)) {
 8643:         foreach my $section (sort(@$sections)) {
 8644:             $result.='<option value="'.$section.'" '.
 8645:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8646:         }
 8647:     }
 8648:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8649:     $result.='
 8650:              </div>
 8651:           </div>
 8652:           <div class="LC_grade_select_mode_selector">
 8653:              <div class="LC_grade_select_mode_selector_header">
 8654:                 '.&mt('Groups').'
 8655:              </div>
 8656:              <div class="LC_grade_select_mode_selector_body">
 8657:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8658:              </div>
 8659:           </div>
 8660:           <div class="LC_grade_select_mode_selector">
 8661:              <div class="LC_grade_select_mode_selector_header">
 8662:                 '.&mt('Access Status').'
 8663:              </div>
 8664:              <div class="LC_grade_select_mode_selector_body">
 8665:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8666:              </div>
 8667:           </div>
 8668:           <div class="LC_grade_select_mode_selector">
 8669:              <div class="LC_grade_select_mode_selector_header">
 8670:                 '.&mt('Submission Status').'
 8671:              </div>
 8672:              <div class="LC_grade_select_mode_selector_body">
 8673:                <select name="submitonly" size="5">
 8674:                  <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8675:                  <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8676:                  <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8677:                  <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8678:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8679:                </select>
 8680:              </div>
 8681:           </div>
 8682:           <div class="LC_grade_select_mode_type_body">
 8683:             <div class="LC_grade_select_mode_type">
 8684:               <label>
 8685:                 <input type="radio" name="radioChoice" value="submission" '.
 8686:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8687:              &mt('Select individual students to grade and view submissions.').'
 8688:               </label>
 8689:             </div>
 8690:             <div class="LC_grade_select_mode_type">
 8691:               <label>
 8692:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8693:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8694:                     &mt('Grade all selected students in a grading table.').'
 8695:               </label>
 8696:             </div>
 8697:             <div class="LC_grade_select_mode_type">
 8698:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8699:             </div>
 8700:           </div>
 8701:         </div>
 8702:       </div>
 8703:       <div class="LC_grade_select_mode_page">
 8704:         <h2>
 8705:          '.&mt('Grade Complete Folder for One Student').'
 8706:         </h2>
 8707:         <div class="LC_grades_select_mode_body">
 8708:           <div class="LC_grade_select_mode_type_body">
 8709:             <div class="LC_grade_select_mode_type">
 8710:               <label>
 8711:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8712:           ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8713:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8714:               </label>
 8715:             </div>
 8716:             <div class="LC_grade_select_mode_type">
 8717:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8718:             </div>
 8719:           </div>
 8720:         </div>
 8721:       </div>
 8722:     </div>
 8723:   </form>';
 8724:     $result .= &show_grading_menu_form($symb);
 8725:     return $result;
 8726: }
 8727: 
 8728: sub reset_perm {
 8729:     undef(%perm);
 8730: }
 8731: 
 8732: sub init_perm {
 8733:     &reset_perm();
 8734:     foreach my $test_perm ('vgr','mgr','opa') {
 8735: 
 8736: 	my $scope = $env{'request.course.id'};
 8737: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8738: 
 8739: 	    $scope .= '/'.$env{'request.course.sec'};
 8740: 	    if ( $perm{$test_perm}=
 8741: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8742: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8743: 	    } else {
 8744: 		delete($perm{$test_perm});
 8745: 	    }
 8746: 	}
 8747:     }
 8748: }
 8749: 
 8750: sub gather_clicker_ids {
 8751:     my %clicker_ids;
 8752: 
 8753:     my $classlist = &Apache::loncoursedata::get_classlist();
 8754: 
 8755:     # Set up a couple variables.
 8756:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8757:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8758:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8759: 
 8760:     foreach my $student (keys(%$classlist)) {
 8761:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8762:         my $username = $classlist->{$student}->[$username_idx];
 8763:         my $domain   = $classlist->{$student}->[$domain_idx];
 8764:         my $clickers =
 8765: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8766:         foreach my $id (split(/\,/,$clickers)) {
 8767:             $id=~s/^[\#0]+//;
 8768:             $id=~s/[\-\:]//g;
 8769:             if (exists($clicker_ids{$id})) {
 8770: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8771:             } else {
 8772: 		$clicker_ids{$id}=$username.':'.$domain;
 8773:             }
 8774:         }
 8775:     }
 8776:     return %clicker_ids;
 8777: }
 8778: 
 8779: sub gather_adv_clicker_ids {
 8780:     my %clicker_ids;
 8781:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8782:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8783:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8784:     foreach my $element (sort(keys(%coursepersonnel))) {
 8785:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8786:             my ($puname,$pudom)=split(/\:/,$person);
 8787:             my $clickers =
 8788: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8789:             foreach my $id (split(/\,/,$clickers)) {
 8790: 		$id=~s/^[\#0]+//;
 8791:                 $id=~s/[\-\:]//g;
 8792: 		if (exists($clicker_ids{$id})) {
 8793: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8794: 		} else {
 8795: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8796: 		}
 8797:             }
 8798:         }
 8799:     }
 8800:     return %clicker_ids;
 8801: }
 8802: 
 8803: sub clicker_grading_parameters {
 8804:     return ('gradingmechanism' => 'scalar',
 8805:             'upfiletype' => 'scalar',
 8806:             'specificid' => 'scalar',
 8807:             'pcorrect' => 'scalar',
 8808:             'pincorrect' => 'scalar');
 8809: }
 8810: 
 8811: sub process_clicker {
 8812:     my ($r)=@_;
 8813:     my ($symb)=&get_symb($r);
 8814:     if (!$symb) {return '';}
 8815:     my $result=&checkforfile_js();
 8816:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8817:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8818:     $result.=$table;
 8819:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8820:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8821:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8822:         '</b></td></tr>'."\n";
 8823:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8824: # Attempt to restore parameters from last session, set defaults if not present
 8825:     my %Saveable_Parameters=&clicker_grading_parameters();
 8826:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8827:                                                  \%Saveable_Parameters);
 8828:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8829:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8830:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8831:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8832: 
 8833:     my %checked;
 8834:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8835:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8836:           $checked{$gradingmechanism}=' checked="checked"';
 8837:        }
 8838:     }
 8839: 
 8840:     my $upload=&mt("Upload File");
 8841:     my $type=&mt("Type");
 8842:     my $attendance=&mt("Award points just for participation");
 8843:     my $personnel=&mt("Correctness determined from response by course personnel");
 8844:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8845:     my $given=&mt("Correctness determined from given list of answers").' '.
 8846:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8847:     my $pcorrect=&mt("Percentage points for correct solution");
 8848:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8849:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8850: 						   ('iclicker' => 'i>clicker',
 8851:                                                     'interwrite' => 'interwrite PRS'));
 8852:     $symb = &Apache::lonenc::check_encrypt($symb);
 8853:     $result.=<<ENDUPFORM;
 8854: <script type="text/javascript">
 8855: function sanitycheck() {
 8856: // Accept only integer percentages
 8857:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8858:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8859: // Find out grading choice
 8860:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8861:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8862:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8863:       }
 8864:    }
 8865: // By default, new choice equals user selection
 8866:    newgradingchoice=gradingchoice;
 8867: // Not good to give more points for false answers than correct ones
 8868:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8869:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8870:    }
 8871: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8872:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8873:       document.forms.gradesupload.pcorrect.value=100;
 8874:       document.forms.gradesupload.pincorrect.value=100;
 8875:    }
 8876: // If the values are different, cannot be attendance only
 8877:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8878:        (gradingchoice=='attendance')) {
 8879:        newgradingchoice='personnel';
 8880:    }
 8881: // Change grading choice to new one
 8882:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8883:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8884:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8885:       } else {
 8886:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8887:       }
 8888:    }
 8889: // Remember the old state
 8890:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8891: }
 8892: </script>
 8893: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8894: <input type="hidden" name="symb" value="$symb" />
 8895: <input type="hidden" name="command" value="processclickerfile" />
 8896: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8897: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8898: <input type="file" name="upfile" size="50" />
 8899: <br /><label>$type: $selectform</label>
 8900: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8901: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8902: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8903: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8904: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
 8905: <br />&nbsp;&nbsp;&nbsp;
 8906: <input type="text" name="givenanswer" size="50" />
 8907: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8908: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8909: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8910: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8911: </form>
 8912: ENDUPFORM
 8913:     $result.='</td></tr></table>'."\n".
 8914:              '</td></tr></table><br /><br />'."\n";
 8915:     $result.=&show_grading_menu_form($symb);
 8916:     return $result;
 8917: }
 8918: 
 8919: sub process_clicker_file {
 8920:     my ($r)=@_;
 8921:     my ($symb)=&get_symb($r);
 8922:     if (!$symb) {return '';}
 8923: 
 8924:     my %Saveable_Parameters=&clicker_grading_parameters();
 8925:     &Apache::loncommon::store_course_settings('grades_clicker',
 8926:                                               \%Saveable_Parameters);
 8927: 
 8928:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8929:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8930: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8931: 	return $result.&show_grading_menu_form($symb);
 8932:     }
 8933:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8934:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8935:         return $result.&show_grading_menu_form($symb);
 8936:     }
 8937:     my $foundgiven=0;
 8938:     if ($env{'form.gradingmechanism'} eq 'given') {
 8939:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8940:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8941:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8942:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8943:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8944:         $foundgiven=$#answers+1;
 8945:     }
 8946:     my %clicker_ids=&gather_clicker_ids();
 8947:     my %correct_ids;
 8948:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8949: 	%correct_ids=&gather_adv_clicker_ids();
 8950:     }
 8951:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8952: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8953: 	   $correct_id=~tr/a-z/A-Z/;
 8954: 	   $correct_id=~s/\s//gs;
 8955: 	   $correct_id=~s/^[\#0]+//;
 8956:            $correct_id=~s/[\-\:]//g;
 8957:            if ($correct_id) {
 8958: 	      $correct_ids{$correct_id}='specified';
 8959:            }
 8960:         }
 8961:     }
 8962:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8963: 	$result.=&mt('Score based on attendance only');
 8964:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8965:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8966:     } else {
 8967: 	my $number=0;
 8968: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8969: 	foreach my $id (sort(keys(%correct_ids))) {
 8970: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8971: 	    if ($correct_ids{$id} eq 'specified') {
 8972: 		$result.=&mt('specified');
 8973: 	    } else {
 8974: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8975: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8976: 	    }
 8977: 	    $number++;
 8978: 	}
 8979:         $result.="</p>\n";
 8980: 	if ($number==0) {
 8981: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8982: 	    return $result.&show_grading_menu_form($symb);
 8983: 	}
 8984:     }
 8985:     if (length($env{'form.upfile'}) < 2) {
 8986:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8987: 		     '<span class="LC_error">',
 8988: 		     '</span>',
 8989: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8990:         return $result.&show_grading_menu_form($symb);
 8991:     }
 8992: 
 8993: # Were able to get all the info needed, now analyze the file
 8994: 
 8995:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8996:     $symb = &Apache::lonenc::check_encrypt($symb);
 8997:     my $heading=&mt('Scanning clicker file');
 8998:     $result.=(<<ENDHEADER);
 8999: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9000: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9001: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9002: <form method="post" action="/adm/grades" name="clickeranalysis">
 9003: <input type="hidden" name="symb" value="$symb" />
 9004: <input type="hidden" name="command" value="assignclickergrades" />
 9005: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 9006: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 9007: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 9008: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 9009: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 9010: ENDHEADER
 9011:     if ($env{'form.gradingmechanism'} eq 'given') {
 9012:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 9013:     } 
 9014:     my %responses;
 9015:     my @questiontitles;
 9016:     my $errormsg='';
 9017:     my $number=0;
 9018:     if ($env{'form.upfiletype'} eq 'iclicker') {
 9019: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 9020:     }
 9021:     if ($env{'form.upfiletype'} eq 'interwrite') {
 9022:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 9023:     }
 9024:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 9025:              '<input type="hidden" name="number" value="'.$number.'" />'.
 9026:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 9027:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 9028:              '<br />';
 9029:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 9030:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 9031:        return $result.&show_grading_menu_form($symb);
 9032:     } 
 9033: # Remember Question Titles
 9034: # FIXME: Possibly need delimiter other than ":"
 9035:     for (my $i=0;$i<$number;$i++) {
 9036:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 9037:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 9038:     }
 9039:     my $correct_count=0;
 9040:     my $student_count=0;
 9041:     my $unknown_count=0;
 9042: # Match answers with usernames
 9043: # FIXME: Possibly need delimiter other than ":"
 9044:     foreach my $id (keys(%responses)) {
 9045:        if ($correct_ids{$id}) {
 9046:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 9047:           $correct_count++;
 9048:        } elsif ($clicker_ids{$id}) {
 9049:           if ($clicker_ids{$id}=~/\,/) {
 9050: # More than one user with the same clicker!
 9051:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 9052:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9053:                            "<select name='multi".$id."'>";
 9054:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 9055:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 9056:              }
 9057:              $result.='</select>';
 9058:              $unknown_count++;
 9059:           } else {
 9060: # Good: found one and only one user with the right clicker
 9061:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 9062:              $student_count++;
 9063:           }
 9064:        } else {
 9065:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 9066:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 9067:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 9068:                    "\n".&mt("Domain").": ".
 9069:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 9070:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 9071:           $unknown_count++;
 9072:        }
 9073:     }
 9074:     $result.='<hr />'.
 9075:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 9076:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 9077:        if ($correct_count==0) {
 9078:           $errormsg.="Found no correct answers answers for grading!";
 9079:        } elsif ($correct_count>1) {
 9080:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 9081:        }
 9082:     }
 9083:     if ($number<1) {
 9084:        $errormsg.="Found no questions.";
 9085:     }
 9086:     if ($errormsg) {
 9087:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 9088:     } else {
 9089:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 9090:     }
 9091:     $result.='</form></td></tr></table>'."\n".
 9092:              '</td></tr></table><br /><br />'."\n";
 9093:     return $result.&show_grading_menu_form($symb);
 9094: }
 9095: 
 9096: sub iclicker_eval {
 9097:     my ($questiontitles,$responses)=@_;
 9098:     my $number=0;
 9099:     my $errormsg='';
 9100:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9101:         my %components=&Apache::loncommon::record_sep($line);
 9102:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9103: 	if ($entries[0] eq 'Question') {
 9104: 	    for (my $i=3;$i<$#entries;$i+=6) {
 9105: 		$$questiontitles[$number]=$entries[$i];
 9106: 		$number++;
 9107: 	    }
 9108: 	}
 9109: 	if ($entries[0]=~/^\#/) {
 9110: 	    my $id=$entries[0];
 9111: 	    my @idresponses;
 9112: 	    $id=~s/^[\#0]+//;
 9113: 	    for (my $i=0;$i<$number;$i++) {
 9114: 		my $idx=3+$i*6;
 9115: 		push(@idresponses,$entries[$idx]);
 9116: 	    }
 9117: 	    $$responses{$id}=join(',',@idresponses);
 9118: 	}
 9119:     }
 9120:     return ($errormsg,$number);
 9121: }
 9122: 
 9123: sub interwrite_eval {
 9124:     my ($questiontitles,$responses)=@_;
 9125:     my $number=0;
 9126:     my $errormsg='';
 9127:     my $skipline=1;
 9128:     my $questionnumber=0;
 9129:     my %idresponses=();
 9130:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 9131:         my %components=&Apache::loncommon::record_sep($line);
 9132:         my @entries=map {$components{$_}} (sort(keys(%components)));
 9133:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 9134:         if ($entries[1] eq 'Response') { $skipline=1; }
 9135:         next if $skipline;
 9136:         if ($entries[0]!=$questionnumber) {
 9137:            $questionnumber=$entries[0];
 9138:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 9139:            $number++;
 9140:         }
 9141:         my $id=$entries[4];
 9142:         $id=~s/^[\#0]+//;
 9143:         $id=~s/^v\d*\://i;
 9144:         $id=~s/[\-\:]//g;
 9145:         $idresponses{$id}[$number]=$entries[6];
 9146:     }
 9147:     foreach my $id (keys(%idresponses)) {
 9148:        $$responses{$id}=join(',',@{$idresponses{$id}});
 9149:        $$responses{$id}=~s/^\s*\,//;
 9150:     }
 9151:     return ($errormsg,$number);
 9152: }
 9153: 
 9154: sub assign_clicker_grades {
 9155:     my ($r)=@_;
 9156:     my ($symb)=&get_symb($r);
 9157:     if (!$symb) {return '';}
 9158: # See which part we are saving to
 9159:     my $res_error;
 9160:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
 9161:     if ($res_error) {
 9162:         return &navmap_errormsg();
 9163:     }
 9164: # FIXME: This should probably look for the first handgradeable part
 9165:     my $part=$$partlist[0];
 9166: # Start screen output
 9167:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 9168: 
 9169:     my $heading=&mt('Assigning grades based on clicker file');
 9170:     $result.=(<<ENDHEADER);
 9171: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 9172: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 9173: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 9174: ENDHEADER
 9175: # Get correct result
 9176: # FIXME: Possibly need delimiter other than ":"
 9177:     my @correct=();
 9178:     my $gradingmechanism=$env{'form.gradingmechanism'};
 9179:     my $number=$env{'form.number'};
 9180:     if ($gradingmechanism ne 'attendance') {
 9181:        foreach my $key (keys(%env)) {
 9182:           if ($key=~/^form\.correct\:/) {
 9183:              my @input=split(/\,/,$env{$key});
 9184:              for (my $i=0;$i<=$#input;$i++) {
 9185:                  if (($correct[$i]) && ($input[$i]) &&
 9186:                      ($correct[$i] ne $input[$i])) {
 9187:                     $result.='<br /><span class="LC_warning">'.
 9188:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 9189:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 9190:                  } elsif ($input[$i]) {
 9191:                     $correct[$i]=$input[$i];
 9192:                  }
 9193:              }
 9194:           }
 9195:        }
 9196:        for (my $i=0;$i<$number;$i++) {
 9197:           if (!$correct[$i]) {
 9198:              $result.='<br /><span class="LC_error">'.
 9199:                       &mt('No correct result given for question "[_1]"!',
 9200:                           $env{'form.question:'.$i}).'</span>';
 9201:           }
 9202:        }
 9203:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 9204:     }
 9205: # Start grading
 9206:     my $pcorrect=$env{'form.pcorrect'};
 9207:     my $pincorrect=$env{'form.pincorrect'};
 9208:     my $storecount=0;
 9209:     foreach my $key (keys(%env)) {
 9210:        my $user='';
 9211:        if ($key=~/^form\.student\:(.*)$/) {
 9212:           $user=$1;
 9213:        }
 9214:        if ($key=~/^form\.unknown\:(.*)$/) {
 9215:           my $id=$1;
 9216:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 9217:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 9218:           } elsif ($env{'form.multi'.$id}) {
 9219:              $user=$env{'form.multi'.$id};
 9220:           }
 9221:        }
 9222:        if ($user) { 
 9223:           my @answer=split(/\,/,$env{$key});
 9224:           my $sum=0;
 9225:           my $realnumber=$number;
 9226:           for (my $i=0;$i<$number;$i++) {
 9227:              if  ($correct[$i] eq '-') {
 9228:                 $realnumber--;
 9229:              } elsif ($answer[$i]) {
 9230:                 if ($gradingmechanism eq 'attendance') {
 9231:                    $sum+=$pcorrect;
 9232:                 } elsif ($correct[$i] eq '*') {
 9233:                    $sum+=$pcorrect;
 9234:                 } else {
 9235:                    if ($answer[$i] eq $correct[$i]) {
 9236:                       $sum+=$pcorrect;
 9237:                    } else {
 9238:                       $sum+=$pincorrect;
 9239:                    }
 9240:                 }
 9241:              }
 9242:           }
 9243:           my $ave=$sum/(100*$realnumber);
 9244: # Store
 9245:           my ($username,$domain)=split(/\:/,$user);
 9246:           my %grades=();
 9247:           $grades{"resource.$part.solved"}='correct_by_override';
 9248:           $grades{"resource.$part.awarded"}=$ave;
 9249:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9250:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9251:                                                  $env{'request.course.id'},
 9252:                                                  $domain,$username);
 9253:           if ($returncode ne 'ok') {
 9254:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9255:           } else {
 9256:              $storecount++;
 9257:           }
 9258:        }
 9259:     }
 9260: # We are done
 9261:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9262:              '</td></tr></table>'."\n".
 9263:              '</td></tr></table><br /><br />'."\n";
 9264:     return $result.&show_grading_menu_form($symb);
 9265: }
 9266: 
 9267: sub navmap_errormsg {
 9268:     return '<div class="LC_error">'.
 9269:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
 9270:            &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>').
 9271:            '</div>';
 9272: }
 9273: 
 9274: sub handler {
 9275:     my $request=$_[0];
 9276:     &reset_caches();
 9277:     if ($env{'browser.mathml'}) {
 9278: 	&Apache::loncommon::content_type($request,'text/xml');
 9279:     } else {
 9280: 	&Apache::loncommon::content_type($request,'text/html');
 9281:     }
 9282:     $request->send_http_header;
 9283:     return '' if $request->header_only;
 9284:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9285:     my $symb=&get_symb($request,1);
 9286:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9287:     my $command=$commands[0];
 9288: 
 9289:     if ($#commands > 0) {
 9290: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9291:     }
 9292: 
 9293:     $ssi_error = 0;
 9294:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 9295:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 9296:                                           {'bread_crumbs' => $brcrum}));
 9297:     if ($symb eq '' && $command eq '') {
 9298: 	if ($env{'user.adv'}) {
 9299: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9300: 		($env{'form.codethree'})) {
 9301: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9302: 		    $env{'form.codethree'};
 9303: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9304: 		    &Apache::lonnet::checkin($token);
 9305: 		if ($tsymb) {
 9306: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9307: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9308: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9309: 					  ('grade_username' => $tuname,
 9310: 					   'grade_domain' => $tudom,
 9311: 					   'grade_courseid' => $tcrsid,
 9312: 					   'grade_symb' => $tsymb)));
 9313: 		    } else {
 9314: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9315: 		    }
 9316: 		} else {
 9317: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9318: 		}
 9319: 	    } else {
 9320: 		$request->print(&Apache::lonxml::tokeninputfield());
 9321: 	    }
 9322: 	}
 9323:     } else {
 9324: 	&init_perm();
 9325: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9326: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9327: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9328: 	    &pickStudentPage($request);
 9329: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9330: 	    &displayPage($request);
 9331: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9332: 	    &updateGradeByPage($request);
 9333: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9334: 	    &processGroup($request);
 9335: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9336: 	    $request->print(&grading_menu($request));
 9337: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9338: 	    $request->print(&submit_options($request));
 9339: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9340: 	    $request->print(&viewgrades($request));
 9341: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9342: 	    $request->print(&processHandGrade($request));
 9343: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9344: 	    $request->print(&editgrades($request));
 9345: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9346: 	    $request->print(&verifyreceipt($request));
 9347:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9348:             $request->print(&process_clicker($request));
 9349:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9350:             $request->print(&process_clicker_file($request));
 9351:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9352:             $request->print(&assign_clicker_grades($request));
 9353: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9354: 	    $request->print(&upcsvScores_form($request));
 9355: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9356: 	    $request->print(&csvupload($request));
 9357: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9358: 	    $request->print(&csvuploadmap($request));
 9359: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9360: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9361: 		$request->print(&csvuploadoptions($request));
 9362: 	    } else {
 9363: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9364: 		    $env{'form.upfile_associate'} = 'reverse';
 9365: 		} else {
 9366: 		    $env{'form.upfile_associate'} = 'forward';
 9367: 		}
 9368: 		$request->print(&csvuploadmap($request));
 9369: 	    }
 9370: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9371: 	    $request->print(&csvuploadassign($request));
 9372: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9373: 	    $request->print(&scantron_selectphase($request));
 9374:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9375:  	    $request->print(&scantron_do_warning($request));
 9376: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9377: 	    $request->print(&scantron_validate_file($request));
 9378: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9379: 	    $request->print(&scantron_process_students($request));
 9380:  	} elsif ($command eq 'scantronupload' && 
 9381:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9382: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9383:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9384:  	} elsif ($command eq 'scantronupload_save' &&
 9385:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9386: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9387:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9388:  	} elsif ($command eq 'scantron_download' &&
 9389: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9390:  	    $request->print(&scantron_download_scantron_data($request));
 9391:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9392:             $request->print(&checkscantron_results($request));     
 9393: 	} elsif ($command) {
 9394: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
 9395: 	}
 9396:     }
 9397:     if ($ssi_error) {
 9398: 	&ssi_print_error($request);
 9399:     }
 9400:     $request->print(&Apache::loncommon::end_page());
 9401:     &reset_caches();
 9402:     return '';
 9403: }
 9404: 
 9405: 1;
 9406: 
 9407: __END__;
 9408: 
 9409: 
 9410: =head1 NAME
 9411: 
 9412: Apache::grades
 9413: 
 9414: =head1 SYNOPSIS
 9415: 
 9416: Handles the viewing of grades.
 9417: 
 9418: This is part of the LearningOnline Network with CAPA project
 9419: described at http://www.lon-capa.org.
 9420: 
 9421: =head1 OVERVIEW
 9422: 
 9423: Do an ssi with retries:
 9424: While I'd love to factor out this with the vesrion in lonprintout,
 9425: 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
 9426: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9427: 
 9428: At least the logic that drives this has been pulled out into loncommon.
 9429: 
 9430: 
 9431: 
 9432: ssi_with_retries - Does the server side include of a resource.
 9433:                      if the ssi call returns an error we'll retry it up to
 9434:                      the number of times requested by the caller.
 9435:                      If we still have a proble, no text is appended to the
 9436:                      output and we set some global variables.
 9437:                      to indicate to the caller an SSI error occurred.  
 9438:                      All of this is supposed to deal with the issues described
 9439:                      in LonCAPA BZ 5631 see:
 9440:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9441:                      by informing the user that this happened.
 9442: 
 9443: Parameters:
 9444:   resource   - The resource to include.  This is passed directly, without
 9445:                interpretation to lonnet::ssi.
 9446:   form       - The form hash parameters that guide the interpretation of the resource
 9447:                
 9448:   retries    - Number of retries allowed before giving up completely.
 9449: Returns:
 9450:   On success, returns the rendered resource identified by the resource parameter.
 9451: Side Effects:
 9452:   The following global variables can be set:
 9453:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9454:                               It is up to the caller to initialize this to false
 9455:                               if desired.
 9456:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9457:                               of the resource that could not be rendered by the ssi
 9458:                               call.
 9459:    ssi_error_message   - The error string fetched from the ssi response
 9460:                               in the event of an error.
 9461: 
 9462: 
 9463: =head1 HANDLER SUBROUTINE
 9464: 
 9465: ssi_with_retries()
 9466: 
 9467: =head1 SUBROUTINES
 9468: 
 9469: =over
 9470: 
 9471: =item scantron_get_correction() : 
 9472: 
 9473:    Builds the interface screen to interact with the operator to fix a
 9474:    specific error condition in a specific scanline
 9475: 
 9476:  Arguments:
 9477:     $r           - Apache request object
 9478:     $i           - number of the current scanline
 9479:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9480:     $scan_config - hash ref as returned from &get_scantron_config()
 9481:     $line        - full contents of the current scanline
 9482:     $error       - error condition, valid values are
 9483:                    'incorrectCODE', 'duplicateCODE',
 9484:                    'doublebubble', 'missingbubble',
 9485:                    'duplicateID', 'incorrectID'
 9486:     $arg         - extra information needed
 9487:        For errors:
 9488:          - duplicateID   - paper number that this studentID was seen before on
 9489:          - duplicateCODE - array ref of the paper numbers this CODE was
 9490:                            seen on before
 9491:          - incorrectCODE - current incorrect CODE 
 9492:          - doublebubble  - array ref of the bubble lines that have double
 9493:                            bubble errors
 9494:          - missingbubble - array ref of the bubble lines that have missing
 9495:                            bubble errors
 9496: 
 9497: =item  scantron_get_maxbubble() : 
 9498: 
 9499:    Arguments:
 9500:        $nav_error  - Reference to scalar which is a flag to indicate a
 9501:                       failure to retrieve a navmap object.
 9502:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
 9503:        calling routine should trap the error condition and display the warning
 9504:        found in &navmap_errormsg().
 9505: 
 9506:    Returns the maximum number of bubble lines that are expected to
 9507:    occur. Does this by walking the selected sequence rendering the
 9508:    resource and then checking &Apache::lonxml::get_problem_counter()
 9509:    for what the current value of the problem counter is.
 9510: 
 9511:    Caches the results to $env{'form.scantron_maxbubble'},
 9512:    $env{'form.scantron.bubble_lines.n'}, 
 9513:    $env{'form.scantron.first_bubble_line.n'} and
 9514:    $env{"form.scantron.sub_bubblelines.n"}
 9515:    which are the total number of bubble, lines, the number of bubble
 9516:    lines for response n and number of the first bubble line for response n,
 9517:    and a comma separated list of numbers of bubble lines for sub-questions
 9518:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9519: 
 9520: 
 9521: =item  scantron_validate_missingbubbles() : 
 9522: 
 9523:    Validates all scanlines in the selected file to not have any
 9524:     answers that don't have bubbles that have not been verified
 9525:     to be bubble free.
 9526: 
 9527: =item  scantron_process_students() : 
 9528: 
 9529:    Routine that does the actual grading of the bubble sheet information.
 9530: 
 9531:    The parsed scanline hash is added to %env 
 9532: 
 9533:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9534:    foreach resource , with the form data of
 9535: 
 9536: 	'submitted'     =>'scantron' 
 9537: 	'grade_target'  =>'grade',
 9538: 	'grade_username'=> username of student
 9539: 	'grade_domain'  => domain of student
 9540: 	'grade_courseid'=> of course
 9541: 	'grade_symb'    => symb of resource to grade
 9542: 
 9543:     This triggers a grading pass. The problem grading code takes care
 9544:     of converting the bubbled letter information (now in %env) into a
 9545:     valid submission.
 9546: 
 9547: =item  scantron_upload_scantron_data() :
 9548: 
 9549:     Creates the screen for adding a new bubble sheet data file to a course.
 9550: 
 9551: =item  scantron_upload_scantron_data_save() : 
 9552: 
 9553:    Adds a provided bubble information data file to the course if user
 9554:    has the correct privileges to do so. 
 9555: 
 9556: =item  valid_file() :
 9557: 
 9558:    Validates that the requested bubble data file exists in the course.
 9559: 
 9560: =item  scantron_download_scantron_data() : 
 9561: 
 9562:    Shows a list of the three internal files (original, corrected,
 9563:    skipped) for a specific bubble sheet data file that exists in the
 9564:    course.
 9565: 
 9566: =item  scantron_validate_ID() : 
 9567: 
 9568:    Validates all scanlines in the selected file to not have any
 9569:    invalid or underspecified student/employee IDs
 9570: 
 9571: =item navmap_errormsg() :
 9572: 
 9573:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
 9574:    Should be called whenever the request to instantiate a navmap object fails.  
 9575: 
 9576: =back
 9577: 
 9578: =cut

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