File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.556: download - view: text, annotated - select for diffs
Mon Mar 9 01:58:48 2009 UTC (15 years, 1 month ago) by weissno
Branches: MAIN
CVS tags: HEAD

consistent wording:
changed "student number" to "student/employee ID"
changed "student ID" to "student/employee ID"
changed "student and eyployee IDs" to "student/employee IDs"

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.556 2009/03/09 01:58:48 weissno 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) = @_;
  101: 
  102:     my $navmap   = Apache::lonnavmaps::navmap->new();
  103:     my $res      = $navmap->getBySymb($symb);
  104:     my $partlist = $res->parts();
  105:     my $url      = $res->src();
  106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  107: 
  108:     my @stores;
  109:     foreach my $part (@{ $partlist }) {
  110: 	foreach my $key (@metakeys) {
  111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  112: 	}
  113:     }
  114:     return @stores;
  115: }
  116: 
  117: # --- Get the symbolic name of a problem and the url
  118: sub get_symb {
  119:     my ($request,$silent) = @_;
  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  122:     if ($symb eq '') { 
  123: 	if (!$silent) {
  124: 	    $request->print("Unable to handle ambiguous references:$url:.");
  125: 	    return ();
  126: 	}
  127:     }
  128:     &Apache::lonenc::check_decrypt(\$symb);
  129:     return ($symb);
  130: }
  131: 
  132: #--- Format fullname, username:domain if different for display
  133: #--- Use anywhere where the student names are listed
  134: sub nameUserString {
  135:     my ($type,$fullname,$uname,$udom) = @_;
  136:     if ($type eq 'header') {
  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  138:     } else {
  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  141:     }
  142: }
  143: 
  144: #--- Get the partlist and the response type for a given problem. ---
  145: #--- Indicate if a response type is coded handgraded or not. ---
  146: sub response_type {
  147:     my ($symb) = shift;
  148: 
  149:     my $navmap = Apache::lonnavmaps::navmap->new();
  150:     my $res = $navmap->getBySymb($symb);
  151:     my $partlist = $res->parts();
  152:     my %vPart = 
  153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  154:     my (%response_types,%handgrade);
  155:     foreach my $part (@{ $partlist }) {
  156: 	next if (%vPart && !exists($vPart{$part}));
  157: 
  158: 	my @types = $res->responseType($part);
  159: 	my @ids = $res->responseIds($part);
  160: 	for (my $i=0; $i < scalar(@ids); $i++) {
  161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  162: 	    $handgrade{$part.'_'.$ids[$i]} = 
  163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  164: 				     '.handgrade',$symb);
  165: 	}
  166:     }
  167:     return ($partlist,\%handgrade,\%response_types);
  168: }
  169: 
  170: sub flatten_responseType {
  171:     my ($responseType) = @_;
  172:     my @part_response_id =
  173: 	map { 
  174: 	    my $part = $_;
  175: 	    map {
  176: 		[$part,$_]
  177: 		} sort(keys(%{ $responseType->{$part} }));
  178: 	} sort(keys(%$responseType));
  179:     return @part_response_id;
  180: }
  181: 
  182: sub get_display_part {
  183:     my ($partID,$symb)=@_;
  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  185:     if (defined($display) and $display ne '') {
  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  187:     } else {
  188: 	$display=$partID;
  189:     }
  190:     return $display;
  191: }
  192: 
  193: #--- Show resource title
  194: #--- and parts and response type
  195: sub showResourceInfo {
  196:     my ($symb,$probTitle,$checkboxes) = @_;
  197:     my $col=3;
  198:     if ($checkboxes) { $col=4; }
  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  200:     $result .='<table border="0">';
  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  202:     my %resptype = ();
  203:     my $hdgrade='no';
  204:     my %partsseen;
  205:     foreach my $partID (sort(keys(%$responseType))) {
  206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  208: 	    my $responsetype = $responseType->{$partID}->{$resID};
  209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  210: 	    $result.='<tr>';
  211: 	    if ($checkboxes) {
  212: 		if (exists($partsseen{$partID})) {
  213: 		    $result.="<td>&nbsp;</td>";
  214: 		} else {
  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  216: 		}
  217: 		$partsseen{$partID}=1;
  218: 	    }
  219: 	    my $display_part=&get_display_part($partID,$symb);
  220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  224: 	}
  225:     }
  226:     $result.='</table>'."\n";
  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  228: }
  229: 
  230: sub reset_caches {
  231:     &reset_analyze_cache();
  232:     &reset_perm();
  233: }
  234: 
  235: {
  236:     my %analyze_cache;
  237: 
  238:     sub reset_analyze_cache {
  239: 	undef(%analyze_cache);
  240:     }
  241: 
  242:     sub get_analyze {
  243: 	my ($symb,$uname,$udom,$no_increment)=@_;
  244: 	my $key = "$symb\0$uname\0$udom";
  245: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  246: 
  247: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  248: 	$url=&Apache::lonnet::clutter($url);
  249: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  250: 					   ('grade_target' => 'analyze',
  251: 					    'grade_domain' => $udom,
  252: 					    'grade_symb' => $symb,
  253: 					    'grade_courseid' => 
  254: 					    $env{'request.course.id'},
  255: 					    'grade_username' => $uname,
  256:                                             'grade_noincrement' => $no_increment));
  257: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  258: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  259: 	return $analyze_cache{$key} = \%analyze;
  260:     }
  261: 
  262:     sub get_order {
  263: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  264: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  265: 	return $analyze->{"$partid.$respid.shown"};
  266:     }
  267: 
  268:     sub get_radiobutton_correct_foil {
  269: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  270: 	my $analyze = &get_analyze($symb,$uname,$udom);
  271:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  272:         if (ref($foils) eq 'ARRAY') {
  273: 	    foreach my $foil (@{$foils}) {
  274: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  275: 		    return $foil;
  276: 	        }
  277: 	    }
  278: 	}
  279:     }
  280: 
  281:     sub scantron_partids_tograde {
  282:         my ($resource,$cid,$uname,$udom) = @_;
  283:         my (%analysis,@parts);
  284:         if (ref($resource)) {
  285:             my $symb = $resource->symb();
  286:             my $analyze = &get_analyze($symb,$uname,$udom);
  287:             if (ref($analyze) eq 'HASH') {
  288:                 %analysis = %{$analyze};
  289:             }
  290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
  291:                 foreach my $part (@{$analysis{'parts'}}) {
  292:                     my ($id,$respid) = split(/\./,$part);
  293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
  294:                         push(@parts,$part);
  295:                     }
  296:                 }
  297:             }
  298:         }
  299:         return (\%analysis,\@parts);
  300:     }
  301: 
  302: }
  303: 
  304: #--- Clean response type for display
  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
  306: #        response types only.
  307: sub cleanRecord {
  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  309: 	$uname,$udom) = @_;
  310:     my $grayFont = '<span class="LC_internal_info">';
  311:     if ($response =~ /^(option|rank)$/) {
  312: 	my %answer=&Apache::lonnet::str2hash($answer);
  313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  314: 	my ($toprow,$bottomrow);
  315: 	foreach my $foil (@$order) {
  316: 	    if ($grading{$foil} == 1) {
  317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  318: 	    } else {
  319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  320: 	    }
  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  322: 	}
  323: 	return '<blockquote><table border="1">'.
  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  327:     } elsif ($response eq 'match') {
  328: 	my %answer=&Apache::lonnet::str2hash($answer);
  329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  331: 	my ($toprow,$middlerow,$bottomrow);
  332: 	foreach my $foil (@$order) {
  333: 	    my $item=shift(@items);
  334: 	    if ($grading{$foil} == 1) {
  335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  337: 	    } else {
  338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  340: 	    }
  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  342: 	}
  343: 	return '<blockquote><table border="1">'.
  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  346: 	    $middlerow.'</tr>'.
  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  349:     } elsif ($response eq 'radiobutton') {
  350: 	my %answer=&Apache::lonnet::str2hash($answer);
  351: 	my ($toprow,$bottomrow);
  352: 	my $correct = 
  353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  354: 	foreach my $foil (@$order) {
  355: 	    if (exists($answer{$foil})) {
  356: 		if ($foil eq $correct) {
  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  358: 		} else {
  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  360: 		}
  361: 	    } else {
  362: 		$toprow.='<td>'.&mt('false').'</td>';
  363: 	    }
  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  365: 	}
  366: 	return '<blockquote><table border="1">'.
  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  369: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  370:     } elsif ($response eq 'essay') {
  371: 	if (! exists ($env{'form.'.$symb})) {
  372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  375: 
  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  381: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  382: 	}
  383: 	$answer =~ s-\n-<br />-g;
  384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  385:     } elsif ( $response eq 'organic') {
  386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  389: 	return $result;
  390:     } elsif ( $response eq 'Task') {
  391: 	if ( $answer eq 'SUBMITTED') {
  392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  394: 	    return $result;
  395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  397: 			       keys(%{$record}));
  398: 	    return join('<br />',($version,@matches));
  399: 			       
  400: 			       
  401: 	} else {
  402: 	    my $result =
  403: 		'<p>'
  404: 		.&mt('Overall result: [_1]',
  405: 		     $record->{$version."resource.$respid.$partid.status"})
  406: 		.'</p>';
  407: 	    
  408: 	    $result .= '<ul>';
  409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  410: 			     keys(%{$record}));
  411: 	    foreach my $grade (sort(@grade)) {
  412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  414: 				     $dim, $record->{$grade}).
  415: 			  '</li>';
  416: 	    }
  417: 	    $result.='</ul>';
  418: 	    return $result;
  419: 	}
  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  421: 	$answer = 
  422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  423: 							      $answer);
  424:     }
  425:     return $answer;
  426: }
  427: 
  428: #-- A couple of common js functions
  429: sub commonJSfunctions {
  430:     my $request = shift;
  431:     $request->print(<<COMMONJSFUNCTIONS);
  432: <script type="text/javascript" language="javascript">
  433:     function radioSelection(radioButton) {
  434: 	var selection=null;
  435: 	if (radioButton.length > 1) {
  436: 	    for (var i=0; i<radioButton.length; i++) {
  437: 		if (radioButton[i].checked) {
  438: 		    return radioButton[i].value;
  439: 		}
  440: 	    }
  441: 	} else {
  442: 	    if (radioButton.checked) return radioButton.value;
  443: 	}
  444: 	return selection;
  445:     }
  446: 
  447:     function pullDownSelection(selectOne) {
  448: 	var selection="";
  449: 	if (selectOne.length > 1) {
  450: 	    for (var i=0; i<selectOne.length; i++) {
  451: 		if (selectOne[i].selected) {
  452: 		    return selectOne[i].value;
  453: 		}
  454: 	    }
  455: 	} else {
  456:             // only one value it must be the selected one
  457: 	    return selectOne.value;
  458: 	}
  459:     }
  460: </script>
  461: COMMONJSFUNCTIONS
  462: }
  463: 
  464: #--- Dumps the class list with usernames,list of sections,
  465: #--- section, ids and fullnames for each user.
  466: sub getclasslist {
  467:     my ($getsec,$filterlist,$getgroup) = @_;
  468:     my @getsec;
  469:     my @getgroup;
  470:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  471:     if (!ref($getsec)) {
  472: 	if ($getsec ne '' && $getsec ne 'all') {
  473: 	    @getsec=($getsec);
  474: 	}
  475:     } else {
  476: 	@getsec=@{$getsec};
  477:     }
  478:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  479:     if (!ref($getgroup)) {
  480: 	if ($getgroup ne '' && $getgroup ne 'all') {
  481: 	    @getgroup=($getgroup);
  482: 	}
  483:     } else {
  484: 	@getgroup=@{$getgroup};
  485:     }
  486:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  487: 
  488:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  489:     # Bail out if we were unable to get the classlist
  490:     return if (! defined($classlist));
  491:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  492:     #
  493:     my %sections;
  494:     my %fullnames;
  495:     foreach my $student (keys(%$classlist)) {
  496:         my $end      = 
  497:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  498:         my $start    = 
  499:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  500:         my $id       = 
  501:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  502:         my $section  = 
  503:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  504:         my $fullname = 
  505:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  506:         my $status   = 
  507:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  508:         my $group   = 
  509:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  510: 	# filter students according to status selected
  511: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  512: 	    if (!($stu_status =~ $status)) {
  513: 		delete($classlist->{$student});
  514: 		next;
  515: 	    }
  516: 	}
  517: 	# filter students according to groups selected
  518: 	my @stu_groups = split(/,/,$group);
  519: 	if (@getgroup) {
  520: 	    my $exclude = 1;
  521: 	    foreach my $grp (@getgroup) {
  522: 	        foreach my $stu_group (@stu_groups) {
  523: 	            if ($stu_group eq $grp) {
  524: 	                $exclude = 0;
  525:     	            } 
  526: 	        }
  527:     	        if (($grp eq 'none') && !$group) {
  528:         	        $exclude = 0;
  529:         	}
  530: 	    }
  531: 	    if ($exclude) {
  532: 	        delete($classlist->{$student});
  533: 	    }
  534: 	}
  535: 	$section = ($section ne '' ? $section : 'none');
  536: 	if (&canview($section)) {
  537: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  538: 		$sections{$section}++;
  539: 		if ($classlist->{$student}) {
  540: 		    $fullnames{$student}=$fullname;
  541: 		}
  542: 	    } else {
  543: 		delete($classlist->{$student});
  544: 	    }
  545: 	} else {
  546: 	    delete($classlist->{$student});
  547: 	}
  548:     }
  549:     my %seen = ();
  550:     my @sections = sort(keys(%sections));
  551:     return ($classlist,\@sections,\%fullnames);
  552: }
  553: 
  554: sub canmodify {
  555:     my ($sec)=@_;
  556:     if ($perm{'mgr'}) {
  557: 	if (!defined($perm{'mgr_section'})) {
  558: 	    # can modify whole class
  559: 	    return 1;
  560: 	} else {
  561: 	    if ($sec eq $perm{'mgr_section'}) {
  562: 		#can modify the requested section
  563: 		return 1;
  564: 	    } else {
  565: 		# can't modify the request section
  566: 		return 0;
  567: 	    }
  568: 	}
  569:     }
  570:     #can't modify
  571:     return 0;
  572: }
  573: 
  574: sub canview {
  575:     my ($sec)=@_;
  576:     if ($perm{'vgr'}) {
  577: 	if (!defined($perm{'vgr_section'})) {
  578: 	    # can modify whole class
  579: 	    return 1;
  580: 	} else {
  581: 	    if ($sec eq $perm{'vgr_section'}) {
  582: 		#can modify the requested section
  583: 		return 1;
  584: 	    } else {
  585: 		# can't modify the request section
  586: 		return 0;
  587: 	    }
  588: 	}
  589:     }
  590:     #can't modify
  591:     return 0;
  592: }
  593: 
  594: #--- Retrieve the grade status of a student for all the parts
  595: sub student_gradeStatus {
  596:     my ($symb,$udom,$uname,$partlist) = @_;
  597:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  598:     my %partstatus = ();
  599:     foreach (@$partlist) {
  600: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  601: 	$status              = 'nothing' if ($status eq '');
  602: 	$partstatus{$_}      = $status;
  603: 	my $subkey           = "resource.$_.submitted_by";
  604: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  605:     }
  606:     return %partstatus;
  607: }
  608: 
  609: # hidden form and javascript that calls the form
  610: # Use by verifyscript and viewgrades
  611: # Shows a student's view of problem and submission
  612: sub jscriptNform {
  613:     my ($symb) = @_;
  614:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  615:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  616: 	'    function viewOneStudent(user,domain) {'."\n".
  617: 	'	document.onestudent.student.value = user;'."\n".
  618: 	'	document.onestudent.userdom.value = domain;'."\n".
  619: 	'	document.onestudent.submit();'."\n".
  620: 	'    }'."\n".
  621: 	'</script>'."\n";
  622:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  623: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  624: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  625: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  626: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  627: 	'<input type="hidden" name="command" value="submission" />'."\n".
  628: 	'<input type="hidden" name="student" value="" />'."\n".
  629: 	'<input type="hidden" name="userdom" value="" />'."\n".
  630: 	'</form>'."\n";
  631:     return $jscript;
  632: }
  633: 
  634: 
  635: 
  636: # Given the score (as a number [0-1] and the weight) what is the final
  637: # point value? This function will round to the nearest tenth, third,
  638: # or quarter if one of those is within the tolerance of .00001.
  639: sub compute_points {
  640:     my ($score, $weight) = @_;
  641:     
  642:     my $tolerance = .00001;
  643:     my $points = $score * $weight;
  644: 
  645:     # Check for nearness to 1/x.
  646:     my $check_for_nearness = sub {
  647:         my ($factor) = @_;
  648:         my $num = ($points * $factor) + $tolerance;
  649:         my $floored_num = floor($num);
  650:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  651:             return $floored_num / $factor;
  652:         }
  653:         return $points;
  654:     };
  655: 
  656:     $points = $check_for_nearness->(10);
  657:     $points = $check_for_nearness->(3);
  658:     $points = $check_for_nearness->(4);
  659:     
  660:     return $points;
  661: }
  662: 
  663: #------------------ End of general use routines --------------------
  664: 
  665: #
  666: # Find most similar essay
  667: #
  668: 
  669: sub most_similar {
  670:     my ($uname,$udom,$uessay,$old_essays)=@_;
  671: 
  672: # ignore spaces and punctuation
  673: 
  674:     $uessay=~s/\W+/ /gs;
  675: 
  676: # ignore empty submissions (occuring when only files are sent)
  677: 
  678:     unless ($uessay=~/\w+/) { return ''; }
  679: 
  680: # these will be returned. Do not care if not at least 50 percent similar
  681:     my $limit=0.6;
  682:     my $sname='';
  683:     my $sdom='';
  684:     my $scrsid='';
  685:     my $sessay='';
  686: # go through all essays ...
  687:     foreach my $tkey (keys(%$old_essays)) {
  688: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  689: # ... except the same student
  690:         next if (($tname eq $uname) && ($tdom eq $udom));
  691: 	my $tessay=$old_essays->{$tkey};
  692: 	$tessay=~s/\W+/ /gs;
  693: # String similarity gives up if not even limit
  694: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  695: # Found one
  696: 	if ($tsimilar>$limit) {
  697: 	    $limit=$tsimilar;
  698: 	    $sname=$tname;
  699: 	    $sdom=$tdom;
  700: 	    $scrsid=$tcrsid;
  701: 	    $sessay=$old_essays->{$tkey};
  702: 	}
  703:     }
  704:     if ($limit>0.6) {
  705:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  706:     } else {
  707:        return ('','','','',0);
  708:     }
  709: }
  710: 
  711: #-------------------------------------------------------------------
  712: 
  713: #------------------------------------ Receipt Verification Routines
  714: #
  715: #--- Check whether a receipt number is valid.---
  716: sub verifyreceipt {
  717:     my $request  = shift;
  718: 
  719:     my $courseid = $env{'request.course.id'};
  720:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  721: 	$env{'form.receipt'};
  722:     $receipt     =~ s/[^\-\d]//g;
  723:     my ($symb)   = &get_symb($request);
  724: 
  725:     my $title.=
  726: 	'<h3><span class="LC_info">'.
  727: 	&mt('Verifying  Receipt No. [_1]',$receipt).
  728: 	'</span></h3>'."\n".
  729: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  730: 	'</h4>'."\n";
  731: 
  732:     my ($string,$contents,$matches) = ('','',0);
  733:     my (undef,undef,$fullname) = &getclasslist('all','0');
  734:     
  735:     my $receiptparts=0;
  736:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  737: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  738:     my $parts=['0'];
  739:     if ($receiptparts) { ($parts)=&response_type($symb); }
  740:     
  741:     my $header = 
  742: 	&Apache::loncommon::start_data_table().
  743: 	&Apache::loncommon::start_data_table_header_row().
  744: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  745: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  746: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  747:     if ($receiptparts) {
  748: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  749:     }
  750:     $header.=
  751: 	&Apache::loncommon::end_data_table_header_row();
  752: 
  753:     foreach (sort 
  754: 	     {
  755: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  756: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  757: 		 }
  758: 		 return $a cmp $b;
  759: 	     } (keys(%$fullname))) {
  760: 	my ($uname,$udom)=split(/\:/);
  761: 	foreach my $part (@$parts) {
  762: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  763: 		$contents.=
  764: 		    &Apache::loncommon::start_data_table_row().
  765: 		    '<td>&nbsp;'."\n".
  766: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  767: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  768: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  769: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  770: 		if ($receiptparts) {
  771: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  772: 		}
  773: 		$contents.= 
  774: 		    &Apache::loncommon::end_data_table_row()."\n";
  775: 		
  776: 		$matches++;
  777: 	    }
  778: 	}
  779:     }
  780:     if ($matches == 0) {
  781: 	$string = $title.&mt('No match found for the above receipt.');
  782:     } else {
  783: 	$string = &jscriptNform($symb).$title.
  784: 	    '<p>'.
  785: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  786: 	    '</p>'.
  787: 	    $header.
  788: 	    $contents.
  789: 	    &Apache::loncommon::end_data_table()."\n";
  790:     }
  791:     return $string.&show_grading_menu_form($symb);
  792: }
  793: 
  794: #--- This is called by a number of programs.
  795: #--- Called from the Grading Menu - View/Grade an individual student
  796: #--- Also called directly when one clicks on the subm button 
  797: #    on the problem page.
  798: sub listStudents {
  799:     my ($request) = shift;
  800: 
  801:     my ($symb) = &get_symb($request);
  802:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  803:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  804:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  805:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  806:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  807:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  808:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  809: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  810: 
  811:     my $result='<h3><span class="LC_info">&nbsp;'
  812: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
  813: 	.'</span></h3>';
  814: 
  815:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  816: 
  817:     my %lt = ( 'multiple' =>
  818: 	       &mt("Please select a student or group of students before clicking on the Next button."),
  819: 	       'single'   =>
  820: 	       &mt("Please select the student before clicking on the Next button."),
  821: 	       );
  822:     %lt = &Apache::lonlocal::texthash(%lt);
  823:     $request->print(<<LISTJAVASCRIPT);
  824: <script type="text/javascript" language="javascript">
  825:     function checkSelect(checkBox) {
  826: 	var ctr=0;
  827: 	var sense="";
  828: 	if (checkBox.length > 1) {
  829: 	    for (var i=0; i<checkBox.length; i++) {
  830: 		if (checkBox[i].checked) {
  831: 		    ctr++;
  832: 		}
  833: 	    }
  834: 	    sense = '$lt{'multiple'}';
  835: 	} else {
  836: 	    if (checkBox.checked) {
  837: 		ctr = 1;
  838: 	    }
  839: 	    sense = '$lt{'single'}';
  840: 	}
  841: 	if (ctr == 0) {
  842: 	    alert(sense);
  843: 	    return false;
  844: 	}
  845: 	document.gradesub.submit();
  846:     }
  847: 
  848:     function reLoadList(formname) {
  849: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  850: 	formname.command.value = 'submission';
  851: 	formname.submit();
  852:     }
  853: </script>
  854: LISTJAVASCRIPT
  855: 
  856:     &commonJSfunctions($request);
  857:     $request->print($result);
  858: 
  859:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  860:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  861:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  862: 	"\n".$table;
  863: 	
  864:     $gradeTable .= 
  865: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  866: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  867: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  868: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
  869:     $gradeTable .= 
  870: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  871: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  872: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  873: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
  874: 
  875:     my $submission_options;
  876:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  877: 	$submission_options.=
  878: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  879:     }
  880:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  881:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  882:     $env{'form.Status'} = $saveStatus;
  883:     $submission_options.=
  884: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  885: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  886: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  887: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  888:     $gradeTable .= 
  889: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  890: 
  891:     $gradeTable .= 
  892:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  893: 	    '<select name="increment">'.
  894: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  895: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  896: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  897: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  898: 	    '</select>';
  899:     
  900:     $gradeTable .= 
  901:         &build_section_inputs().
  902: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  903: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  904: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  905: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  906: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  907: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  908: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  909: 
  910:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  911: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  912:     } else {
  913: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  914: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  915:     }
  916: 
  917:     $gradeTable.=&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.").'<br />'."\n".
  918: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  919: 
  920: # checkall buttons
  921:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  922:     $gradeTable.='<input type="button" '."\n".
  923: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  924: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  925:     $gradeTable.=&check_buttons();
  926:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  927:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  928:     $gradeTable.= &Apache::loncommon::start_data_table().
  929: 	&Apache::loncommon::start_data_table_header_row();
  930:     my $loop = 0;
  931:     while ($loop < 2) {
  932: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  933: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  934: 	if ($env{'form.showgrading'} eq 'yes' 
  935: 	    && $submitonly ne 'queued'
  936: 	    && $submitonly ne 'all') {
  937: 	    foreach my $part (sort(@$partlist)) {
  938: 		my $display_part=
  939: 		    &get_display_part((split(/_/,$part))[0],$symb);
  940: 		$gradeTable.=
  941: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  942: 	    }
  943: 	} elsif ($submitonly eq 'queued') {
  944: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  945: 	}
  946: 	$loop++;
  947: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  948:     }
  949:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  950: 
  951:     my $ctr = 0;
  952:     foreach my $student (sort 
  953: 			 {
  954: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  955: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  956: 			     }
  957: 			     return $a cmp $b;
  958: 			 }
  959: 			 (keys(%$fullname))) {
  960: 	my ($uname,$udom) = split(/:/,$student);
  961: 
  962: 	my %status = ();
  963: 
  964: 	if ($submitonly eq 'queued') {
  965: 	    my %queue_status = 
  966: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  967: 							$udom,$uname);
  968: 	    next if (!defined($queue_status{'gradingqueue'}));
  969: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  970: 	}
  971: 
  972: 	if ($env{'form.showgrading'} eq 'yes' 
  973: 	    && $submitonly ne 'queued'
  974: 	    && $submitonly ne 'all') {
  975: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  976: 	    my $submitted = 0;
  977: 	    my $graded = 0;
  978: 	    my $incorrect = 0;
  979: 	    foreach (keys(%status)) {
  980: 		$submitted = 1 if ($status{$_} ne 'nothing');
  981: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  982: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  983: 		
  984: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  985: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  986: 		    $submitted = 0;
  987: 		    my ($part)=split(/\./,$partid);
  988: 		    $gradeTable.='<input type="hidden" name="'.
  989: 			$student.':'.$part.':submitted_by" value="'.
  990: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  991: 		}
  992: 	    }
  993: 	    
  994: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  995: 				     $submitonly eq 'incorrect' ||
  996: 				     $submitonly eq 'graded'));
  997: 	    next if (!$graded && ($submitonly eq 'graded'));
  998: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  999: 	}
 1000: 
 1001: 	$ctr++;
 1002: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1003:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1004: 	if ( $perm{'vgr'} eq 'F' ) {
 1005: 	    if ($ctr%2 ==1) {
 1006: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1007: 	    }
 1008: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1009:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1010:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1011: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1012: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1013: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1014: 
 1015: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1016: 		foreach (sort(keys(%status))) {
 1017: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1018: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1019: 		}
 1020: 	    }
 1021: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1022: 	    if ($ctr%2 ==0) {
 1023: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1024: 	    }
 1025: 	}
 1026:     }
 1027:     if ($ctr%2 ==1) {
 1028: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1029: 	    if ($env{'form.showgrading'} eq 'yes' 
 1030: 		&& $submitonly ne 'queued'
 1031: 		&& $submitonly ne 'all') {
 1032: 		foreach (@$partlist) {
 1033: 		    $gradeTable.='<td>&nbsp;</td>';
 1034: 		}
 1035: 	    } elsif ($submitonly eq 'queued') {
 1036: 		$gradeTable.='<td>&nbsp;</td>';
 1037: 	    }
 1038: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1039:     }
 1040: 
 1041:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1042: 	'<input type="button" '.
 1043: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1044: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1045:     if ($ctr == 0) {
 1046: 	my $num_students=(scalar(keys(%$fullname)));
 1047: 	if ($num_students eq 0) {
 1048: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1049: 	} else {
 1050: 	    my $submissions='submissions';
 1051: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1052: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1053: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1054: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1055: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1056: 		    $num_students).
 1057: 		'</span><br />';
 1058: 	}
 1059:     } elsif ($ctr == 1) {
 1060: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1061:     }
 1062:     $gradeTable.=&show_grading_menu_form($symb);
 1063:     $request->print($gradeTable);
 1064:     return '';
 1065: }
 1066: 
 1067: #---- Called from the listStudents routine
 1068: 
 1069: sub check_script {
 1070:     my ($form, $type)=@_;
 1071:     my $chkallscript='<script type="text/javascript">
 1072:     function checkall() {
 1073:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1074:             ele = document.forms.'.$form.'.elements[i];
 1075:             if (ele.name == "'.$type.'") {
 1076:             document.forms.'.$form.'.elements[i].checked=true;
 1077:                                        }
 1078:         }
 1079:     }
 1080: 
 1081:     function checksec() {
 1082:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1083:             ele = document.forms.'.$form.'.elements[i];
 1084:            string = document.forms.'.$form.'.chksec.value;
 1085:            if
 1086:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1087:               document.forms.'.$form.'.elements[i].checked=true;
 1088:             }
 1089:         }
 1090:     }
 1091: 
 1092: 
 1093:     function uncheckall() {
 1094:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1095:             ele = document.forms.'.$form.'.elements[i];
 1096:             if (ele.name == "'.$type.'") {
 1097:             document.forms.'.$form.'.elements[i].checked=false;
 1098:                                        }
 1099:         }
 1100:     }
 1101: 
 1102: </script>'."\n";
 1103:     return $chkallscript;
 1104: }
 1105: 
 1106: sub check_buttons {
 1107:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1108:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1109:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1110:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1111:     return $buttons;
 1112: }
 1113: 
 1114: #     Displays the submissions for one student or a group of students
 1115: sub processGroup {
 1116:     my ($request)  = shift;
 1117:     my $ctr        = 0;
 1118:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1119:     my $total      = scalar(@stuchecked)-1;
 1120: 
 1121:     foreach my $student (@stuchecked) {
 1122: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1123: 	$env{'form.student'}        = $uname;
 1124: 	$env{'form.userdom'}        = $udom;
 1125: 	$env{'form.fullname'}       = $fullname;
 1126: 	&submission($request,$ctr,$total);
 1127: 	$ctr++;
 1128:     }
 1129:     return '';
 1130: }
 1131: 
 1132: #------------------------------------------------------------------------------------
 1133: #
 1134: #-------------------------- Next few routines handles grading by student, essentially
 1135: #                           handles essay response type problem/part
 1136: #
 1137: #--- Javascript to handle the submission page functionality ---
 1138: sub sub_page_js {
 1139:     my $request = shift;
 1140: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1141:     $request->print(<<SUBJAVASCRIPT);
 1142: <script type="text/javascript" language="javascript">
 1143:     function updateRadio(formname,id,weight) {
 1144: 	var gradeBox = formname["GD_BOX"+id];
 1145: 	var radioButton = formname["RADVAL"+id];
 1146: 	var oldpts = formname["oldpts"+id].value;
 1147: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1148: 	gradeBox.value = pts;
 1149: 	var resetbox = false;
 1150: 	if (isNaN(pts) || pts < 0) {
 1151: 	    alert("$alertmsg"+pts);
 1152: 	    for (var i=0; i<radioButton.length; i++) {
 1153: 		if (radioButton[i].checked) {
 1154: 		    gradeBox.value = i;
 1155: 		    resetbox = true;
 1156: 		}
 1157: 	    }
 1158: 	    if (!resetbox) {
 1159: 		formtextbox.value = "";
 1160: 	    }
 1161: 	    return;
 1162: 	}
 1163: 
 1164: 	if (pts > weight) {
 1165: 	    var resp = confirm("You entered a value ("+pts+
 1166: 			       ") greater than the weight for the part. Accept?");
 1167: 	    if (resp == false) {
 1168: 		gradeBox.value = oldpts;
 1169: 		return;
 1170: 	    }
 1171: 	}
 1172: 
 1173: 	for (var i=0; i<radioButton.length; i++) {
 1174: 	    radioButton[i].checked=false;
 1175: 	    if (pts == i && pts != "") {
 1176: 		radioButton[i].checked=true;
 1177: 	    }
 1178: 	}
 1179: 	updateSelect(formname,id);
 1180: 	formname["stores"+id].value = "0";
 1181:     }
 1182: 
 1183:     function writeBox(formname,id,pts) {
 1184: 	var gradeBox = formname["GD_BOX"+id];
 1185: 	if (checkSolved(formname,id) == 'update') {
 1186: 	    gradeBox.value = pts;
 1187: 	} else {
 1188: 	    var oldpts = formname["oldpts"+id].value;
 1189: 	    gradeBox.value = oldpts;
 1190: 	    var radioButton = formname["RADVAL"+id];
 1191: 	    for (var i=0; i<radioButton.length; i++) {
 1192: 		radioButton[i].checked=false;
 1193: 		if (i == oldpts) {
 1194: 		    radioButton[i].checked=true;
 1195: 		}
 1196: 	    }
 1197: 	}
 1198: 	formname["stores"+id].value = "0";
 1199: 	updateSelect(formname,id);
 1200: 	return;
 1201:     }
 1202: 
 1203:     function clearRadBox(formname,id) {
 1204: 	if (checkSolved(formname,id) == 'noupdate') {
 1205: 	    updateSelect(formname,id);
 1206: 	    return;
 1207: 	}
 1208: 	gradeSelect = formname["GD_SEL"+id];
 1209: 	for (var i=0; i<gradeSelect.length; i++) {
 1210: 	    if (gradeSelect[i].selected) {
 1211: 		var selectx=i;
 1212: 	    }
 1213: 	}
 1214: 	var stores = formname["stores"+id];
 1215: 	if (selectx == stores.value) { return };
 1216: 	var gradeBox = formname["GD_BOX"+id];
 1217: 	gradeBox.value = "";
 1218: 	var radioButton = formname["RADVAL"+id];
 1219: 	for (var i=0; i<radioButton.length; i++) {
 1220: 	    radioButton[i].checked=false;
 1221: 	}
 1222: 	stores.value = selectx;
 1223:     }
 1224: 
 1225:     function checkSolved(formname,id) {
 1226: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1227: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1228: 	    if (!reply) {return "noupdate";}
 1229: 	    formname.overRideScore.value = 'yes';
 1230: 	}
 1231: 	return "update";
 1232:     }
 1233: 
 1234:     function updateSelect(formname,id) {
 1235: 	formname["GD_SEL"+id][0].selected = true;
 1236: 	return;
 1237:     }
 1238: 
 1239: //=========== Check that a point is assigned for all the parts  ============
 1240:     function checksubmit(formname,val,total,parttot) {
 1241: 	formname.gradeOpt.value = val;
 1242: 	if (val == "Save & Next") {
 1243: 	    for (i=0;i<=total;i++) {
 1244: 		for (j=0;j<parttot;j++) {
 1245: 		    var partid = formname["partid"+i+"_"+j].value;
 1246: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1247: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1248: 			if (points == "") {
 1249: 			    var name = formname["name"+i].value;
 1250: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1251: 			    var resp = confirm("You did not assign a score for "+studentID+
 1252: 					       ", part "+partid+". Continue?");
 1253: 			    if (resp == false) {
 1254: 				formname["GD_BOX"+i+"_"+partid].focus();
 1255: 				return false;
 1256: 			    }
 1257: 			}
 1258: 		    }
 1259: 		    
 1260: 		}
 1261: 	    }
 1262: 	    
 1263: 	}
 1264: 	if (val == "Grade Student") {
 1265: 	    formname.showgrading.value = "yes";
 1266: 	    if (formname.Status.value == "") {
 1267: 		formname.Status.value = "Active";
 1268: 	    }
 1269: 	    formname.studentNo.value = total;
 1270: 	}
 1271: 	formname.submit();
 1272:     }
 1273: 
 1274: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1275:     function checkSubmitPage(formname,total) {
 1276: 	noscore = new Array(100);
 1277: 	var ptr = 0;
 1278: 	for (i=1;i<total;i++) {
 1279: 	    var partid = formname["q_"+i].value;
 1280: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1281: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1282: 		var status = formname["solved"+i+"_"+partid].value;
 1283: 		if (points == "" && status != "correct_by_student") {
 1284: 		    noscore[ptr] = i;
 1285: 		    ptr++;
 1286: 		}
 1287: 	    }
 1288: 	}
 1289: 	if (ptr != 0) {
 1290: 	    var sense = ptr == 1 ? ": " : "s: ";
 1291: 	    var prolist = "";
 1292: 	    if (ptr == 1) {
 1293: 		prolist = noscore[0];
 1294: 	    } else {
 1295: 		var i = 0;
 1296: 		while (i < ptr-1) {
 1297: 		    prolist += noscore[i]+", ";
 1298: 		    i++;
 1299: 		}
 1300: 		prolist += "and "+noscore[i];
 1301: 	    }
 1302: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1303: 	    if (resp == false) {
 1304: 		return false;
 1305: 	    }
 1306: 	}
 1307: 
 1308: 	formname.submit();
 1309:     }
 1310: </script>
 1311: SUBJAVASCRIPT
 1312: }
 1313: 
 1314: #--- javascript for essay type problem --
 1315: sub sub_page_kw_js {
 1316:     my $request = shift;
 1317:     my $iconpath = $request->dir_config('lonIconsURL');
 1318:     &commonJSfunctions($request);
 1319: 
 1320:     my $inner_js_msg_central=<<INNERJS;
 1321:     <script text="text/javascript">
 1322:     function checkInput() {
 1323:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1324:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1325:       var usrctr = document.msgcenter.usrctr.value;
 1326:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1327:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1328: 
 1329:       var msgchk = "";
 1330:       if (document.msgcenter.subchk.checked) {
 1331:          msgchk = "msgsub,";
 1332:       }
 1333:       var includemsg = 0;
 1334:       for (var i=1; i<=nmsg; i++) {
 1335:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1336:           var frmmsg = document.msgcenter["msg"+i];
 1337:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1338:           var showflg = opener.document.SCORE["shownOnce"+i];
 1339:           showflg.value = "1";
 1340:           var chkbox = document.msgcenter["msgn"+i];
 1341:           if (chkbox.checked) {
 1342:              msgchk += "savemsg"+i+",";
 1343:              includemsg = 1;
 1344:           }
 1345:       }
 1346:       if (document.msgcenter.newmsgchk.checked) {
 1347:          msgchk += "newmsg"+usrctr;
 1348:          includemsg = 1;
 1349:       }
 1350:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1351:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1352:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1353:       includemsg.value = msgchk;
 1354: 
 1355:       self.close()
 1356: 
 1357:     }
 1358:     </script>
 1359: INNERJS
 1360: 
 1361:     my $inner_js_highlight_central=<<INNERJS;
 1362:  <script type="text/javascript">
 1363:     function updateChoice(flag) {
 1364:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1365:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1366:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1367:       opener.document.SCORE.refresh.value = "on";
 1368:       if (opener.document.SCORE.keywords.value!=""){
 1369:          opener.document.SCORE.submit();
 1370:       }
 1371:       self.close()
 1372:     }
 1373: </script>
 1374: INNERJS
 1375: 
 1376:     my $start_page_msg_central = 
 1377:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1378: 				       {'js_ready'  => 1,
 1379: 					'only_body' => 1,
 1380: 					'bgcolor'   =>'#FFFFFF',});
 1381:     my $end_page_msg_central = 
 1382: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1383: 
 1384: 
 1385:     my $start_page_highlight_central = 
 1386:         &Apache::loncommon::start_page('Highlight Central',
 1387: 				       $inner_js_highlight_central,
 1388: 				       {'js_ready'  => 1,
 1389: 					'only_body' => 1,
 1390: 					'bgcolor'   =>'#FFFFFF',});
 1391:     my $end_page_highlight_central = 
 1392: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1393: 
 1394:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1395:     $docopen=~s/^document\.//;
 1396:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1397:     $request->print(<<SUBJAVASCRIPT);
 1398: <script type="text/javascript" language="javascript">
 1399: 
 1400: //===================== Show list of keywords ====================
 1401:   function keywords(formname) {
 1402:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1403:     if (nret==null) return;
 1404:     formname.keywords.value = nret;
 1405: 
 1406:     if (formname.keywords.value != "") {
 1407: 	formname.refresh.value = "on";
 1408: 	formname.submit();
 1409:     }
 1410:     return;
 1411:   }
 1412: 
 1413: //===================== Script to view submitted by ==================
 1414:   function viewSubmitter(submitter) {
 1415:     document.SCORE.refresh.value = "on";
 1416:     document.SCORE.NCT.value = "1";
 1417:     document.SCORE.unamedom0.value = submitter;
 1418:     document.SCORE.submit();
 1419:     return;
 1420:   }
 1421: 
 1422: //===================== Script to add keyword(s) ==================
 1423:   function getSel() {
 1424:     if (document.getSelection) txt = document.getSelection();
 1425:     else if (document.selection) txt = document.selection.createRange().text;
 1426:     else return;
 1427:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1428:     if (cleantxt=="") {
 1429: 	alert("$alertmsg");
 1430: 	return;
 1431:     }
 1432:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1433:     if (nret==null) return;
 1434:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1435:     if (document.SCORE.keywords.value != "") {
 1436: 	document.SCORE.refresh.value = "on";
 1437: 	document.SCORE.submit();
 1438:     }
 1439:     return;
 1440:   }
 1441: 
 1442: //====================== Script for composing message ==============
 1443:    // preload images
 1444:    img1 = new Image();
 1445:    img1.src = "$iconpath/mailbkgrd.gif";
 1446:    img2 = new Image();
 1447:    img2.src = "$iconpath/mailto.gif";
 1448: 
 1449:   function msgCenter(msgform,usrctr,fullname) {
 1450:     var Nmsg  = msgform.savemsgN.value;
 1451:     savedMsgHeader(Nmsg,usrctr,fullname);
 1452:     var subject = msgform.msgsub.value;
 1453:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1454:     re = /msgsub/;
 1455:     var shwsel = "";
 1456:     if (re.test(msgchk)) { shwsel = "checked" }
 1457:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1458:     displaySubject(checkEntities(subject),shwsel);
 1459:     for (var i=1; i<=Nmsg; i++) {
 1460: 	var testmsg = "savemsg"+i+",";
 1461: 	re = new RegExp(testmsg,"g");
 1462: 	shwsel = "";
 1463: 	if (re.test(msgchk)) { shwsel = "checked" }
 1464: 	var message = document.SCORE["savemsg"+i].value;
 1465: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1466: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1467: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1468:     }
 1469:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1470:     shwsel = "";
 1471:     re = /newmsg/;
 1472:     if (re.test(msgchk)) { shwsel = "checked" }
 1473:     newMsg(newmsg,shwsel);
 1474:     msgTail(); 
 1475:     return;
 1476:   }
 1477: 
 1478:   function checkEntities(strx) {
 1479:     if (strx.length == 0) return strx;
 1480:     var orgStr = ["&", "<", ">", '"']; 
 1481:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1482:     var counter = 0;
 1483:     while (counter < 4) {
 1484: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1485: 	counter++;
 1486:     }
 1487:     return strx;
 1488:   }
 1489: 
 1490:   function strReplace(strx, orgStr, newStr) {
 1491:     return strx.split(orgStr).join(newStr);
 1492:   }
 1493: 
 1494:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1495:     var height = 70*Nmsg+250;
 1496:     var scrollbar = "no";
 1497:     if (height > 600) {
 1498: 	height = 600;
 1499: 	scrollbar = "yes";
 1500:     }
 1501:     var xpos = (screen.width-600)/2;
 1502:     xpos = (xpos < 0) ? '0' : xpos;
 1503:     var ypos = (screen.height-height)/2-30;
 1504:     ypos = (ypos < 0) ? '0' : ypos;
 1505: 
 1506:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1507:     pWin.focus();
 1508:     pDoc = pWin.document;
 1509:     pDoc.$docopen;
 1510:     pDoc.write('$start_page_msg_central');
 1511: 
 1512:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1513:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1514:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1515: 
 1516:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1517:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1518:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1519: }
 1520:     function displaySubject(msg,shwsel) {
 1521:     pDoc = pWin.document;
 1522:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1523:     pDoc.write("<td>Subject<\\/td>");
 1524:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1525:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1526: }
 1527: 
 1528:   function displaySavedMsg(ctr,msg,shwsel) {
 1529:     pDoc = pWin.document;
 1530:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1531:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1532:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1533:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1534: }
 1535: 
 1536:   function newMsg(newmsg,shwsel) {
 1537:     pDoc = pWin.document;
 1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1539:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1540:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1541:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1542: }
 1543: 
 1544:   function msgTail() {
 1545:     pDoc = pWin.document;
 1546:     pDoc.write("<\\/table>");
 1547:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1548:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1549:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1550:     pDoc.write("<\\/form>");
 1551:     pDoc.write('$end_page_msg_central');
 1552:     pDoc.close();
 1553: }
 1554: 
 1555: //====================== Script for keyword highlight options ==============
 1556:   function kwhighlight() {
 1557:     var kwclr    = document.SCORE.kwclr.value;
 1558:     var kwsize   = document.SCORE.kwsize.value;
 1559:     var kwstyle  = document.SCORE.kwstyle.value;
 1560:     var redsel = "";
 1561:     var grnsel = "";
 1562:     var blusel = "";
 1563:     if (kwclr=="red")   {var redsel="checked"};
 1564:     if (kwclr=="green") {var grnsel="checked"};
 1565:     if (kwclr=="blue")  {var blusel="checked"};
 1566:     var sznsel = "";
 1567:     var sz1sel = "";
 1568:     var sz2sel = "";
 1569:     if (kwsize=="0")  {var sznsel="checked"};
 1570:     if (kwsize=="+1") {var sz1sel="checked"};
 1571:     if (kwsize=="+2") {var sz2sel="checked"};
 1572:     var synsel = "";
 1573:     var syisel = "";
 1574:     var sybsel = "";
 1575:     if (kwstyle=="")    {var synsel="checked"};
 1576:     if (kwstyle=="<i>") {var syisel="checked"};
 1577:     if (kwstyle=="<b>") {var sybsel="checked"};
 1578:     highlightCentral();
 1579:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1580:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1581:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1582:     highlightend();
 1583:     return;
 1584:   }
 1585: 
 1586:   function highlightCentral() {
 1587: //    if (window.hwdWin) window.hwdWin.close();
 1588:     var xpos = (screen.width-400)/2;
 1589:     xpos = (xpos < 0) ? '0' : xpos;
 1590:     var ypos = (screen.height-330)/2-30;
 1591:     ypos = (ypos < 0) ? '0' : ypos;
 1592: 
 1593:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1594:     hwdWin.focus();
 1595:     var hDoc = hwdWin.document;
 1596:     hDoc.$docopen;
 1597:     hDoc.write('$start_page_highlight_central');
 1598:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1599:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1600: 
 1601:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1602:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1603:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1604:   }
 1605: 
 1606:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1607:     var hDoc = hwdWin.document;
 1608:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1609:     hDoc.write("<td align=\\"left\\">");
 1610:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1611:     hDoc.write("<td align=\\"left\\">");
 1612:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1613:     hDoc.write("<td align=\\"left\\">");
 1614:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1615:     hDoc.write("<\\/tr>");
 1616:   }
 1617: 
 1618:   function highlightend() { 
 1619:     var hDoc = hwdWin.document;
 1620:     hDoc.write("<\\/table>");
 1621:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1622:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1623:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1624:     hDoc.write("<\\/form>");
 1625:     hDoc.write('$end_page_highlight_central');
 1626:     hDoc.close();
 1627:   }
 1628: 
 1629: </script>
 1630: SUBJAVASCRIPT
 1631: }
 1632: 
 1633: sub get_increment {
 1634:     my $increment = $env{'form.increment'};
 1635:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1636:         $increment != .1) {
 1637:         $increment = 1;
 1638:     }
 1639:     return $increment;
 1640: }
 1641: 
 1642: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1643: sub gradeBox {
 1644:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1645:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1646: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1647:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1648:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1649:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1650:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1651:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1652: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1653:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1654:     my $display_part= &get_display_part($partid,$symb);
 1655:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1656: 				       [$partid]);
 1657:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1658:     if ($last_resets{$partid}) {
 1659:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1660:     }
 1661:     $result.='<table border="0"><tr>';
 1662:     my $ctr = 0;
 1663:     my $thisweight = 0;
 1664:     my $increment = &get_increment();
 1665: 
 1666:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1667:     while ($thisweight<=$wgt) {
 1668: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1669: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1670: 	    $thisweight.')" value="'.$thisweight.'" '.
 1671: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1672: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1673:         $thisweight += $increment;
 1674: 	$ctr++;
 1675:     }
 1676:     $radio.='</tr></table>';
 1677: 
 1678:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1679: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1680: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1681: 	$wgt.')" /></td>'."\n";
 1682:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1683: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1684: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1685:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1686: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1687:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1688: 	$line.='<option></option>'.
 1689: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1690:     } else {
 1691: 	$line.='<option selected="selected"></option>'.
 1692: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1693:     }
 1694:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1695: 
 1696: 
 1697: 	#&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);
 1698:     $result .= 
 1699: 	    '<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>'.
 1700:     
 1701:     $result.='</tr></table>'."\n";
 1702:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1703: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1704: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1705: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1706:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1707:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1708:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1709:         $aggtries.'" />'."\n";
 1710:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1711:     return $result;
 1712: }
 1713: 
 1714: sub handback_box {
 1715:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1716:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1717:     my (@respids);
 1718:      my @part_response_id = &flatten_responseType($responseType);
 1719:     foreach my $part_response_id (@part_response_id) {
 1720:     	my ($part,$resp) = @{ $part_response_id };
 1721:         if ($part eq $partid) {
 1722:             push(@respids,$resp);
 1723:         }
 1724:     }
 1725:     my $result;
 1726:     foreach my $respid (@respids) {
 1727: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1728: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1729: 	next if (!@$files);
 1730: 	my $file_counter = 1;
 1731: 	foreach my $file (@$files) {
 1732: 	    if ($file =~ /\/portfolio\//) {
 1733:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1734:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1735:     	        $file_disp = "$name.$ext";
 1736:     	        $file = $file_path.$file_disp;
 1737:     	        $result.=&mt('Return commented version of [_1] to student.',
 1738:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1739:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1740:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1741:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1742:     	        $file_counter++;
 1743: 	    }
 1744: 	}
 1745:     }
 1746:     return $result;    
 1747: }
 1748: 
 1749: sub show_problem {
 1750:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1751:     my $rendered;
 1752:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1753:     &Apache::lonxml::remember_problem_counter();
 1754:     if ($mode eq 'both' or $mode eq 'text') {
 1755: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1756: 						       $env{'request.course.id'},
 1757: 						       undef,\%form);
 1758:     }
 1759:     if ($removeform) {
 1760: 	$rendered=~s|<form(.*?)>||g;
 1761: 	$rendered=~s|</form>||g;
 1762: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1763:     }
 1764:     my $companswer;
 1765:     if ($mode eq 'both' or $mode eq 'answer') {
 1766: 	&Apache::lonxml::restore_problem_counter();
 1767: 	$companswer=
 1768: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1769: 						    $env{'request.course.id'},
 1770: 						    %form);
 1771:     }
 1772:     if ($removeform) {
 1773: 	$companswer=~s|<form(.*?)>||g;
 1774: 	$companswer=~s|</form>||g;
 1775: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1776:     }
 1777:     $rendered=
 1778: 	'<div class="LC_grade_show_problem_header">'.
 1779: 	&mt('View of the problem').
 1780: 	'</div><div class="LC_grade_show_problem_problem">'.
 1781: 	$rendered.
 1782: 	'</div>';
 1783:     $companswer=
 1784: 	'<div class="LC_grade_show_problem_header">'.
 1785: 	&mt('Correct answer').
 1786: 	'</div><div class="LC_grade_show_problem_problem">'.
 1787: 	$companswer.
 1788: 	'</div>';
 1789:     my $result;
 1790:     if ($mode eq 'both') {
 1791: 	$result=$rendered.$companswer;
 1792:     } elsif ($mode eq 'text') {
 1793: 	$result=$rendered;
 1794:     } elsif ($mode eq 'answer') {
 1795: 	$result=$companswer;
 1796:     }
 1797:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1798:     return $result;
 1799: }
 1800: 
 1801: sub files_exist {
 1802:     my ($r, $symb) = @_;
 1803:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1804: 
 1805:     foreach my $student (@students) {
 1806:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1807:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1808: 					      $udom,$uname);
 1809:         my ($string,$timestamp)= &get_last_submission(\%record);
 1810:         foreach my $submission (@$string) {
 1811:             my ($partid,$respid) =
 1812: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1813:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1814: 					   \%record);
 1815:             return 1 if (@$files);
 1816:         }
 1817:     }
 1818:     return 0;
 1819: }
 1820: 
 1821: sub download_all_link {
 1822:     my ($r,$symb) = @_;
 1823:     my $all_students = 
 1824: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1825: 
 1826:     my $parts =
 1827: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1828: 
 1829:     my $identifier = &Apache::loncommon::get_cgi_id();
 1830:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1831:                              'cgi.'.$identifier.'.symb' => $symb,
 1832:                              'cgi.'.$identifier.'.parts' => $parts,});
 1833:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1834: 	      &mt('Download All Submitted Documents').'</a>');
 1835:     return
 1836: }
 1837: 
 1838: sub build_section_inputs {
 1839:     my $section_inputs;
 1840:     if ($env{'form.section'} eq '') {
 1841:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1842:     } else {
 1843:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1844:         foreach my $section (@sections) {
 1845:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1846:         }
 1847:     }
 1848:     return $section_inputs;
 1849: }
 1850: 
 1851: # --------------------------- show submissions of a student, option to grade 
 1852: sub submission {
 1853:     my ($request,$counter,$total) = @_;
 1854:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1855:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1856:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1857:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1858:     my $symb = &get_symb($request); 
 1859:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1860: 
 1861:     if (!&canview($usec)) {
 1862: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1863: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1864: 			$env{'request.course.id'}.')</span>');
 1865: 	$request->print(&show_grading_menu_form($symb));
 1866: 	return;
 1867:     }
 1868: 
 1869:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1870:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1871:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1872:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1873:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1874: 	'" src="'.$request->dir_config('lonIconsURL').
 1875: 	'/check.gif" height="16" border="0" />';
 1876: 
 1877:     my %old_essays;
 1878:     # header info
 1879:     if ($counter == 0) {
 1880: 	&sub_page_js($request);
 1881: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1882: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1883: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1884: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1885: 	    &download_all_link($request, $symb);
 1886: 	}
 1887: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1888: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1889: 
 1890: 	# option to display problem, only once else it cause problems 
 1891:         # with the form later since the problem has a form.
 1892: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1893: 	    my $mode;
 1894: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1895: 		$mode='both';
 1896: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1897: 		$mode='text';
 1898: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1899: 		$mode='answer';
 1900: 	    }
 1901: 	    &Apache::lonxml::clear_problem_counter();
 1902: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1903: 	}
 1904: 
 1905: 	# kwclr is the only variable that is guaranteed to be non blank 
 1906:         # if this subroutine has been called once.
 1907: 	my %keyhash = ();
 1908: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1909: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1910: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1911: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1912: 
 1913: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1914: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1915: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1916: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1917: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1918: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1919: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1920: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1921: 	}
 1922: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1923: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1924: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1925: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1926: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1927: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1928: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1929: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1930: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1931: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1932: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1933: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1934: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1935: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1936: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1937: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1938: 			&build_section_inputs().
 1939: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1940: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1941: 			'<input type="hidden" name="NCT"'.
 1942: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1943: 	if ($env{'form.handgrade'} eq 'yes') {
 1944: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1945: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1946: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1947: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1948: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1949: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1950: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1951: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1952: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1953: 	    }
 1954: 	}
 1955: 	
 1956: 	my ($cts,$prnmsg) = (1,'');
 1957: 	while ($cts <= $env{'form.savemsgN'}) {
 1958: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1959: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1960: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1961: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1962: 		'" />'."\n".
 1963: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1964: 	    $cts++;
 1965: 	}
 1966: 	$request->print($prnmsg);
 1967: 
 1968: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1969: #
 1970: # Print out the keyword options line
 1971: #
 1972: 	    $request->print(<<KEYWORDS);
 1973: &nbsp;<b>Keyword Options:</b>&nbsp;
 1974: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1975: <a href="#" onMouseDown="javascript:getSel(); return false"
 1976:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1977: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1978: KEYWORDS
 1979: #
 1980: # Load the other essays for similarity check
 1981: #
 1982:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1983: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1984: 	    $apath=&escape($apath);
 1985: 	    $apath=~s/\W/\_/gs;
 1986: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1987:         }
 1988:     }
 1989: 
 1990: # This is where output for one specific student would start
 1991:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 1992:     $request->print("\n\n".
 1993:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 1994: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 1995: 		    '<div class="LC_grade_show_user_body">'."\n");
 1996: 
 1997:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1998: 	my $mode;
 1999: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2000: 	    $mode='both';
 2001: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2002: 	    $mode='text';
 2003: 	} elsif ($env{'form.vAns'} eq 'all') {
 2004: 	    $mode='answer';
 2005: 	}
 2006: 	&Apache::lonxml::clear_problem_counter();
 2007: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2008:     }
 2009: 
 2010:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2011:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2012: 
 2013:     # Display student info
 2014:     $request->print(($counter == 0 ? '' : '<br />'));
 2015:     my $result='<div class="LC_grade_submissions">';
 2016:     
 2017:     $result.='<div class="LC_grade_submissions_header">';
 2018:     $result.= &mt('Submissions');
 2019:     $result.='<input type="hidden" name="name'.$counter.
 2020: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2021:     if ($env{'form.handgrade'} eq 'no') {
 2022: 	$result.='<span class="LC_grade_check_note">'.
 2023: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2024: 
 2025:     }
 2026: 
 2027: 
 2028: 
 2029:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2030:     my $fullname;
 2031:     my $col_fullnames = [];
 2032:     if ($env{'form.handgrade'} eq 'yes') {
 2033: 	(my $sub_result,$fullname,$col_fullnames)=
 2034: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2035: 				 $counter);
 2036: 	$result.=$sub_result;
 2037:     }
 2038:     $request->print($result."\n");
 2039:     $request->print('</div>'."\n");
 2040:     # print student answer/submission
 2041:     # Options are (1) Handgaded submission only
 2042:     #             (2) Last submission, includes submission that is not handgraded 
 2043:     #                  (for multi-response type part)
 2044:     #             (3) Last submission plus the parts info
 2045:     #             (4) The whole record for this student
 2046:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2047: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2048: 	
 2049: 	my $lastsubonly;
 2050: 
 2051: 	if ($$timestamp eq '') {
 2052: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2053: 	} else {
 2054: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2055: 
 2056: 	    my %seenparts;
 2057: 	    my @part_response_id = &flatten_responseType($responseType);
 2058: 	    foreach my $part (@part_response_id) {
 2059: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2060: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2061: 
 2062: 		my ($partid,$respid) = @{ $part };
 2063: 		my $display_part=&get_display_part($partid,$symb);
 2064: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2065: 		    if (exists($seenparts{$partid})) { next; }
 2066: 		    $seenparts{$partid}=1;
 2067: 		    my $submitby='<b>Part:</b> '.$display_part.
 2068: 			' <b>Collaborative submission by:</b> '.
 2069: 			'<a href="javascript:viewSubmitter(\''.
 2070: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2071: 			'\');" target="_self">'.
 2072: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2073: 		    $request->print($submitby);
 2074: 		    next;
 2075: 		}
 2076: 		my $responsetype = $responseType->{$partid}->{$respid};
 2077: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2078: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2079: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2080: 			' )</span>&nbsp; &nbsp;'.
 2081: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2082: 		    next;
 2083: 		}
 2084: 		foreach my $submission (@$string) {
 2085: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2086: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2087: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2088: 		    # Similarity check
 2089: 		    my $similar='';
 2090: 		    if($env{'form.checkPlag'}){
 2091: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2092: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2093: 			if ($osim) {
 2094: 			    $osim=int($osim*100.0);
 2095: 			    my %old_course_desc = 
 2096: 				&Apache::lonnet::coursedescription($ocrsid,
 2097: 								   {'one_time' => 1});
 2098: 
 2099: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2100: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2101: 				    $osim,
 2102: 				    &Apache::loncommon::plainname($oname,$odom),
 2103: 				    $oname,$odom,
 2104: 				    $old_course_desc{'description'},
 2105: 				    $old_course_desc{'num'},
 2106: 				    $old_course_desc{'domain'}).
 2107: 				'</span></h3><blockquote><i>'.
 2108: 				&keywords_highlight($oessay).
 2109: 				'</i></blockquote><hr />';
 2110: 			}
 2111: 		    }
 2112: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2113: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2114: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2115: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2116: 			my $display_part=&get_display_part($partid,$symb);
 2117: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2118: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2119: 			    ' )</span>&nbsp; &nbsp;';
 2120: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2121: 			if (@$files) {
 2122: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2123: 			    my $file_counter = 0;
 2124: 			    foreach my $file (@$files) {
 2125: 			        $file_counter++;
 2126: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2127: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2128: 			    }
 2129: 			    $lastsubonly.='<br />';
 2130: 			}
 2131: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2132: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2133: 					 $respid,\%record,$order,undef,$uname,$udom);
 2134: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2135: 			$lastsubonly.='</div>';
 2136: 		    }
 2137: 		}
 2138: 	    }
 2139: 	    $lastsubonly.='</div>'."\n";
 2140: 	}
 2141: 	$request->print($lastsubonly);
 2142:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2143: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2144: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2145:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2146: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2147: 								 $env{'request.course.id'},
 2148: 								 $last,'.submission',
 2149: 								 'Apache::grades::keywords_highlight'));
 2150:     }
 2151: 
 2152:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2153: 	.$udom.'" />'."\n");
 2154:     # return if view submission with no grading option
 2155:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2156: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2157: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2158: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2159: 	$toGrade.='</div>'."\n";
 2160: 	if (($env{'form.command'} eq 'submission') || 
 2161: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2162: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2163: 	}
 2164: 	$request->print($toGrade);
 2165: 	return;
 2166:     } else {
 2167: 	$request->print('</div>'."\n");
 2168:     }
 2169: 
 2170:     # essay grading message center
 2171:     if ($env{'form.handgrade'} eq 'yes') {
 2172: 	my $result='<div class="LC_grade_message_center">';
 2173:     
 2174: 	$result.='<div class="LC_grade_message_center_header">'.
 2175: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2176: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2177: 	my $msgfor = $givenn.' '.$lastname;
 2178: 	if (scalar(@$col_fullnames) > 0) {
 2179: 	    my $lastone = pop(@$col_fullnames);
 2180: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2181: 	}
 2182: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2183: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2184: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2185: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2186: 	    ',\''.$msgfor.'\');" target="_self">'.
 2187: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2188: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2189: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2190: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2191: 	    '<br />&nbsp;('.
 2192: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2193: 	$result.='</div></div>';
 2194: 	$request->print($result);
 2195:     }
 2196: 
 2197:     my %seen = ();
 2198:     my @partlist;
 2199:     my @gradePartRespid;
 2200:     my @part_response_id = &flatten_responseType($responseType);
 2201:     $request->print('<div class="LC_grade_assign">'.
 2202: 		    
 2203: 		    '<div class="LC_grade_assign_header">'.
 2204: 		    &mt('Assign Grades').'</div>'.
 2205: 		    '<div class="LC_grade_assign_body">');
 2206:     foreach my $part_response_id (@part_response_id) {
 2207:     	my ($partid,$respid) = @{ $part_response_id };
 2208: 	my $part_resp = join('_',@{ $part_response_id });
 2209: 	next if ($seen{$partid} > 0);
 2210: 	$seen{$partid}++;
 2211: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2212: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2213: 	push(@partlist,$partid);
 2214: 	push(@gradePartRespid,$partid.'.'.$respid);
 2215: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2216:     }
 2217:     $request->print('</div></div>');
 2218: 
 2219:     $request->print('<div class="LC_grade_info_links">');
 2220:     if ($perm{'vgr'}) {
 2221: 	$request->print(
 2222: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2223: 						   $uname,$udom,'check'));
 2224:     }
 2225:     if ($perm{'opa'}) {
 2226: 	$request->print(
 2227: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2228: 					 $uname,$udom,$symb,'check'));
 2229:     }
 2230:     $request->print('</div>');
 2231: 
 2232:     $result='<input type="hidden" name="partlist'.$counter.
 2233: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2234:     $result.='<input type="hidden" name="gradePartRespid'.
 2235: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2236:     my $ctr = 0;
 2237:     while ($ctr < scalar(@partlist)) {
 2238: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2239: 	    $partlist[$ctr].'" />'."\n";
 2240: 	$ctr++;
 2241:     }
 2242:     $request->print($result.''."\n");
 2243: 
 2244: # Done with printing info for one student
 2245: 
 2246:     $request->print('</div>');#LC_grade_show_user_body
 2247:     $request->print('</div>');#LC_grade_show_user
 2248: 
 2249: 
 2250:     # print end of form
 2251:     if ($counter == $total) {
 2252: 	my $endform='<table border="0"><tr><td>'."\n";
 2253: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2254: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2255: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2256: 	my $ntstu ='<select name="NTSTU">'.
 2257: 	    '<option>1</option><option>2</option>'.
 2258: 	    '<option>3</option><option>5</option>'.
 2259: 	    '<option>7</option><option>10</option></select>'."\n";
 2260: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2261: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2262: 	$endform.=&mt('[quant,_1,student]',$ntstu);
 2263: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2264: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2265: 	    '<input type="button" value="'.&mt('Next').'" '.
 2266: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2267: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2268:         $endform.="<input type='hidden' value='".&get_increment().
 2269:             "' name='increment' />";
 2270: 	$endform.='</td></tr></table></form>';
 2271: 	$endform.=&show_grading_menu_form($symb);
 2272: 	$request->print($endform);
 2273:     }
 2274:     return '';
 2275: }
 2276: 
 2277: sub check_collaborators {
 2278:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2279:     my ($result,@col_fullnames);
 2280:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2281:     foreach my $part (keys(%$handgrade)) {
 2282: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2283: 					'.maxcollaborators',
 2284: 					$symb,$udom,$uname);
 2285: 	next if ($ncol <= 0);
 2286: 	$part =~ s/\_/\./g;
 2287: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2288: 	my (@good_collaborators, @bad_collaborators);
 2289: 	foreach my $possible_collaborator
 2290: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2291: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2292: 	    next if ($possible_collaborator eq '');
 2293: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2294: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2295: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2296: 	    # Doing this grep allows 'fuzzy' specification
 2297: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2298: 			       keys(%$classlist));
 2299: 	    if (! scalar(@matches)) {
 2300: 		push(@bad_collaborators, $possible_collaborator);
 2301: 	    } else {
 2302: 		push(@good_collaborators, @matches);
 2303: 	    }
 2304: 	}
 2305: 	if (scalar(@good_collaborators) != 0) {
 2306: 	    $result.='<br />'.&mt('Collaborators: ');
 2307: 	    foreach my $name (@good_collaborators) {
 2308: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2309: 		push(@col_fullnames, $givenn.' '.$lastname);
 2310: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2311: 	    }
 2312: 	    $result.='<br />'."\n";
 2313: 	    my ($part)=split(/\./,$part);
 2314: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2315: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2316: 		"\n";
 2317: 	}
 2318: 	if (scalar(@bad_collaborators) > 0) {
 2319: 	    $result.='<div class="LC_warning">';
 2320: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2321: 	    $result .= '</div>';
 2322: 	}         
 2323: 	if (scalar(@bad_collaborators > $ncol)) {
 2324: 	    $result .= '<div class="LC_warning">';
 2325: 	    $result .= &mt('This student has submitted too many '.
 2326: 		'collaborators.  Maximum is [_1].',$ncol);
 2327: 	    $result .= '</div>';
 2328: 	}
 2329:     }
 2330:     return ($result,$fullname,\@col_fullnames);
 2331: }
 2332: 
 2333: #--- Retrieve the last submission for all the parts
 2334: sub get_last_submission {
 2335:     my ($returnhash)=@_;
 2336:     my (@string,$timestamp);
 2337:     if ($$returnhash{'version'}) {
 2338: 	my %lasthash=();
 2339: 	my ($version);
 2340: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2341: 	    foreach my $key (sort(split(/\:/,
 2342: 					$$returnhash{$version.':keys'}))) {
 2343: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2344: 		$timestamp = 
 2345: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2346: 	    }
 2347: 	}
 2348: 	foreach my $key (keys(%lasthash)) {
 2349: 	    next if ($key !~ /\.submission$/);
 2350: 
 2351: 	    my ($partid,$foo) = split(/submission$/,$key);
 2352: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2353: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2354: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2355: 	}
 2356:     }
 2357:     if (!@string) {
 2358: 	$string[0] =
 2359: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
 2360:     }
 2361:     return (\@string,\$timestamp);
 2362: }
 2363: 
 2364: #--- High light keywords, with style choosen by user.
 2365: sub keywords_highlight {
 2366:     my $string    = shift;
 2367:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2368:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2369:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2370:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2371:     foreach my $keyword (@keylist) {
 2372: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2373:     }
 2374:     return $string;
 2375: }
 2376: 
 2377: #--- Called from submission routine
 2378: sub processHandGrade {
 2379:     my ($request) = shift;
 2380:     my $symb   = &get_symb($request);
 2381:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2382:     my $button = $env{'form.gradeOpt'};
 2383:     my $ngrade = $env{'form.NCT'};
 2384:     my $ntstu  = $env{'form.NTSTU'};
 2385:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2386:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2387: 
 2388:     if ($button eq 'Save & Next') {
 2389: 	my $ctr = 0;
 2390: 	while ($ctr < $ngrade) {
 2391: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2392: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2393: 	    if ($errorflag eq 'no_score') {
 2394: 		$ctr++;
 2395: 		next;
 2396: 	    }
 2397: 	    if ($errorflag eq 'not_allowed') {
 2398: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2399: 		$ctr++;
 2400: 		next;
 2401: 	    }
 2402: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2403: 	    my ($subject,$message,$msgstatus) = ('','','');
 2404: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2405:             my ($feedurl,$showsymb) =
 2406: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2407: 	    my $messagetail;
 2408: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2409: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2410: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2411: 		$subject.=' ['.$restitle.']';
 2412: 		my (@msgnum) = split(/,/,$includemsg);
 2413: 		foreach (@msgnum) {
 2414: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2415: 		}
 2416: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2417: 		if ($env{'form.withgrades'.$ctr}) {
 2418: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2419: 		    $messagetail = " for <a href=\"".
 2420: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2421: 		}
 2422: 		$msgstatus = 
 2423:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2424: 						     $message.$messagetail,
 2425:                                                      undef,$feedurl,undef,
 2426:                                                      undef,undef,$showsymb,
 2427:                                                      $restitle);
 2428: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2429: 				$msgstatus);
 2430: 	    }
 2431: 	    if ($env{'form.collaborator'.$ctr}) {
 2432: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2433: 		foreach my $collabstr (@collabstrs) {
 2434: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2435: 		    foreach my $collaborator (@collaborators) {
 2436: 			my ($errorflag,$pts,$wgt) = 
 2437: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2438: 					   $env{'form.unamedom'.$ctr},$part);
 2439: 			if ($errorflag eq 'not_allowed') {
 2440: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2441: 			    next;
 2442: 			} elsif ($message ne '') {
 2443: 			    my ($baseurl,$showsymb) = 
 2444: 				&get_feedurl_and_symb($symb,$collaborator,
 2445: 						      $udom);
 2446: 			    if ($env{'form.withgrades'.$ctr}) {
 2447: 				$messagetail = " for <a href=\"".
 2448:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2449: 			    }
 2450: 			    $msgstatus = 
 2451: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2452: 			}
 2453: 		    }
 2454: 		}
 2455: 	    }
 2456: 	    $ctr++;
 2457: 	}
 2458:     }
 2459: 
 2460:     if ($env{'form.handgrade'} eq 'yes') {
 2461: 	# Keywords sorted in alphabatical order
 2462: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2463: 	my %keyhash = ();
 2464: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2465: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2466: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2467: 	$env{'form.keywords'} = join(' ',@keywords);
 2468: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2469: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2470: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2471: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2472: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2473: 
 2474: 	# message center - Order of message gets changed. Blank line is eliminated.
 2475: 	# New messages are saved in env for the next student.
 2476: 	# All messages are saved in nohist_handgrade.db
 2477: 	my ($ctr,$idx) = (1,1);
 2478: 	while ($ctr <= $env{'form.savemsgN'}) {
 2479: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2480: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2481: 		$idx++;
 2482: 	    }
 2483: 	    $ctr++;
 2484: 	}
 2485: 	$ctr = 0;
 2486: 	while ($ctr < $ngrade) {
 2487: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2488: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2489: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2490: 		$idx++;
 2491: 	    }
 2492: 	    $ctr++;
 2493: 	}
 2494: 	$env{'form.savemsgN'} = --$idx;
 2495: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2496: 	my $putresult = &Apache::lonnet::put
 2497: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2498:     }
 2499:     # Called by Save & Refresh from Highlight Attribute Window
 2500:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2501:     if ($env{'form.refresh'} eq 'on') {
 2502: 	my ($ctr,$total) = (0,0);
 2503: 	while ($ctr < $ngrade) {
 2504: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2505: 	    $ctr++;
 2506: 	}
 2507: 	$env{'form.NTSTU'}=$ngrade;
 2508: 	$ctr = 0;
 2509: 	while ($ctr < $total) {
 2510: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2511: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2512: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2513: 	    &submission($request,$ctr,$total-1);
 2514: 	    $ctr++;
 2515: 	}
 2516: 	return '';
 2517:     }
 2518: 
 2519: # Go directly to grade student - from submission or link from chart page
 2520:     if ($button eq 'Grade Student') {
 2521: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2522: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2523: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2524: 	$env{'form.fullname'} = $$fullname{$processUser};
 2525: 	&submission($request,0,0);
 2526: 	return '';
 2527:     }
 2528: 
 2529:     # Get the next/previous one or group of students
 2530:     my $firststu = $env{'form.unamedom0'};
 2531:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2532:     my $ctr = 2;
 2533:     while ($laststu eq '') {
 2534: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2535: 	$ctr++;
 2536: 	$laststu = $firststu if ($ctr > $ngrade);
 2537:     }
 2538: 
 2539:     my (@parsedlist,@nextlist);
 2540:     my ($nextflg) = 0;
 2541:     foreach my $item (sort 
 2542: 	     {
 2543: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2544: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2545: 		 }
 2546: 		 return $a cmp $b;
 2547: 	     } (keys(%$fullname))) {
 2548: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2549: 	    push(@parsedlist,$item);
 2550: 	}
 2551: 	$nextflg = 1 if ($item eq $laststu);
 2552: 	if ($button eq 'Previous') {
 2553: 	    last if ($item eq $firststu);
 2554: 	    push(@parsedlist,$item);
 2555: 	}
 2556:     }
 2557:     $ctr = 0;
 2558:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2559:     my ($partlist) = &response_type($symb);
 2560:     foreach my $student (@parsedlist) {
 2561: 	my $submitonly=$env{'form.submitonly'};
 2562: 	my ($uname,$udom) = split(/:/,$student);
 2563: 	
 2564: 	if ($submitonly eq 'queued') {
 2565: 	    my %queue_status = 
 2566: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2567: 							$udom,$uname);
 2568: 	    next if (!defined($queue_status{'gradingqueue'}));
 2569: 	}
 2570: 
 2571: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2572: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2573: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2574: 	    my $submitted = 0;
 2575: 	    my $ungraded = 0;
 2576: 	    my $incorrect = 0;
 2577: 	    foreach my $item (keys(%status)) {
 2578: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2579: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2580: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2581: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2582: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2583: 		    $submitted = 0;
 2584: 		}
 2585: 	    }
 2586: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2587: 				     $submitonly eq 'incorrect' ||
 2588: 				     $submitonly eq 'graded'));
 2589: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2590: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2591: 	}
 2592: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2593: 	last if ($ctr == $ntstu);
 2594: 	$ctr++;
 2595:     }
 2596: 
 2597:     $ctr = 0;
 2598:     my $total = scalar(@nextlist)-1;
 2599: 
 2600:     foreach (sort(@nextlist)) {
 2601: 	my ($uname,$udom,$submitter) = split(/:/);
 2602: 	$env{'form.student'}  = $uname;
 2603: 	$env{'form.userdom'}  = $udom;
 2604: 	$env{'form.fullname'} = $$fullname{$_};
 2605: 	&submission($request,$ctr,$total);
 2606: 	$ctr++;
 2607:     }
 2608:     if ($total < 0) {
 2609: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2610: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2611: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2612: 	$the_end.=&show_grading_menu_form($symb);
 2613: 	$request->print($the_end);
 2614:     }
 2615:     return '';
 2616: }
 2617: 
 2618: #---- Save the score and award for each student, if changed
 2619: sub saveHandGrade {
 2620:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2621:     my @version_parts;
 2622:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2623: 					   $env{'request.course.id'});
 2624:     if (!&canmodify($usec)) { return('not_allowed'); }
 2625:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2626:     my @parts_graded;
 2627:     my %newrecord  = ();
 2628:     my ($pts,$wgt) = ('','');
 2629:     my %aggregate = ();
 2630:     my $aggregateflag = 0;
 2631:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2632:     foreach my $new_part (@parts) {
 2633: 	#collaborator ($submi may vary for different parts
 2634: 	if ($submitter && $new_part ne $part) { next; }
 2635: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2636: 	if ($dropMenu eq 'excused') {
 2637: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2638: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2639: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2640: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2641: 		}
 2642: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2643: 	    }
 2644: 	} elsif ($dropMenu eq 'reset status'
 2645: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2646: 	    foreach my $key (keys(%record)) {
 2647: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2648: 	    }
 2649: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2650: 		"$env{'user.name'}:$env{'user.domain'}";
 2651:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2652: 
 2653:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2654: 					       [$new_part]);
 2655:             my $aggtries =$totaltries;
 2656:             if ($last_resets{$new_part}) {
 2657:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2658: 					   $new_part);
 2659:             }
 2660: 
 2661:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2662:             if ($aggtries > 0) {
 2663:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2664:                 $aggregateflag = 1;
 2665:             }
 2666: 	} elsif ($dropMenu eq '') {
 2667: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2668: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2669: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2670: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2671: 		next;
 2672: 	    }
 2673: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2674: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2675: 	    my $partial= $pts/$wgt;
 2676: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2677: 		#do not update score for part if not changed.
 2678:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2679: 		next;
 2680: 	    } else {
 2681: 	        push(@parts_graded,$new_part);
 2682: 	    }
 2683: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2684: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2685: 	    }
 2686: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2687: 	    if ($partial == 0) {
 2688: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2689: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2690: 		}
 2691: 	    } else {
 2692: 		if ($record{$reckey} ne 'correct_by_override') {
 2693: 		    $newrecord{$reckey} = 'correct_by_override';
 2694: 		}
 2695: 	    }	    
 2696: 	    if ($submitter && 
 2697: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2698: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2699: 	    }
 2700: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2701: 		"$env{'user.name'}:$env{'user.domain'}";
 2702: 	}
 2703: 	# unless problem has been graded, set flag to version the submitted files
 2704: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2705: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2706: 	        $dropMenu eq 'reset status')
 2707: 	   {
 2708: 	    push(@version_parts,$new_part);
 2709: 	}
 2710:     }
 2711:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2712:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2713: 
 2714:     if (%newrecord) {
 2715:         if (@version_parts) {
 2716:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2717:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2718: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2719: 	    foreach my $new_part (@version_parts) {
 2720: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2721: 				$new_part,\%newrecord);
 2722: 	    }
 2723:         }
 2724: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2725: 				$env{'request.course.id'},$domain,$stuname);
 2726: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2727: 				     $cdom,$cnum,$domain,$stuname);
 2728:     }
 2729:     if ($aggregateflag) {
 2730:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2731: 			      $cdom,$cnum);
 2732:     }
 2733:     return ('',$pts,$wgt);
 2734: }
 2735: 
 2736: sub check_and_remove_from_queue {
 2737:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2738:     my @ungraded_parts;
 2739:     foreach my $part (@{$parts}) {
 2740: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2741: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2742: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2743: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2744: 		) {
 2745: 	    push(@ungraded_parts, $part);
 2746: 	}
 2747:     }
 2748:     if ( !@ungraded_parts ) {
 2749: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2750: 					       $cnum,$domain,$stuname);
 2751:     }
 2752: }
 2753: 
 2754: sub handback_files {
 2755:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2756:     my $portfolio_root = '/userfiles/portfolio';
 2757:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2758: 
 2759:     my @part_response_id = &flatten_responseType($responseType);
 2760:     foreach my $part_response_id (@part_response_id) {
 2761:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2762: 	my $part_resp = join('_',@{ $part_response_id });
 2763:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2764:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2765:                 my $file_counter = 1;
 2766: 		my $file_msg;
 2767:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2768:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2769:                     my ($directory,$answer_file) = 
 2770:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2771:                     my ($answer_name,$answer_ver,$answer_ext) =
 2772: 		        &file_name_version_ext($answer_file);
 2773: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2774:                     my $getpropath = 1;
 2775: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2776: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2777:                     # fix file name
 2778:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2779:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2780:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2781:             	                                $save_file_name);
 2782:                     if ($result !~ m|^/uploaded/|) {
 2783:                         $request->print('<br /><span class="LC_error">'.
 2784:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2785:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2786:                                         '</span>');
 2787:                     } else {
 2788:                         # mark the file as read only
 2789:                         my @files = ($save_file_name);
 2790:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2791:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2792: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2793: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2794: 			}
 2795:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2796: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2797: 
 2798:                     }
 2799:                     $request->print("<br />".$fname." will be the uploaded file name");
 2800:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2801:                     $file_counter++;
 2802:                 }
 2803: 		my $subject = "File Handed Back by Instructor ";
 2804: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2805: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2806: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2807: 		$message .= " and can be found in your portfolio space.";
 2808: 		my ($feedurl,$showsymb) = 
 2809: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2810:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2811: 		my $msgstatus = 
 2812:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2813: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2814:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2815:             }
 2816:         }
 2817:     return;
 2818: }
 2819: 
 2820: sub get_feedurl_and_symb {
 2821:     my ($symb,$uname,$udom) = @_;
 2822:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2823:     $url = &Apache::lonnet::clutter($url);
 2824:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2825: 					$symb,$udom,$uname);
 2826:     if ($encrypturl =~ /^yes$/i) {
 2827: 	&Apache::lonenc::encrypted(\$url,1);
 2828: 	&Apache::lonenc::encrypted(\$symb,1);
 2829:     }
 2830:     return ($url,$symb);
 2831: }
 2832: 
 2833: sub get_submitted_files {
 2834:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2835:     my @files;
 2836:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2837:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2838:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2839:     	    push(@files,$file_url.$file);
 2840:         }
 2841:     }
 2842:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2843:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2844:     }
 2845:     return (\@files);
 2846: }
 2847: 
 2848: # ----------- Provides number of tries since last reset.
 2849: sub get_num_tries {
 2850:     my ($record,$last_reset,$part) = @_;
 2851:     my $timestamp = '';
 2852:     my $num_tries = 0;
 2853:     if ($$record{'version'}) {
 2854:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2855:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2856:                 $timestamp = $$record{$version.':timestamp'};
 2857:                 if ($timestamp > $last_reset) {
 2858:                     $num_tries ++;
 2859:                 } else {
 2860:                     last;
 2861:                 }
 2862:             }
 2863:         }
 2864:     }
 2865:     return $num_tries;
 2866: }
 2867: 
 2868: # ----------- Determine decrements required in aggregate totals 
 2869: sub decrement_aggs {
 2870:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2871:     my %decrement = (
 2872:                         attempts => 0,
 2873:                         users => 0,
 2874:                         correct => 0
 2875:                     );
 2876:     $decrement{'attempts'} = $aggtries;
 2877:     if ($solvedstatus =~ /^correct/) {
 2878:         $decrement{'correct'} = 1;
 2879:     }
 2880:     if ($aggtries == $totaltries) {
 2881:         $decrement{'users'} = 1;
 2882:     }
 2883:     foreach my $type (keys(%decrement)) {
 2884:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2885:     }
 2886:     return;
 2887: }
 2888: 
 2889: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2890: sub get_last_resets {
 2891:     my ($symb,$courseid,$partids) =@_;
 2892:     my %last_resets;
 2893:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2894:     my $cname = $env{'course.'.$courseid.'.num'};
 2895:     my @keys;
 2896:     foreach my $part (@{$partids}) {
 2897: 	push(@keys,"$symb\0$part\0resettime");
 2898:     }
 2899:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2900: 				     $cdom,$cname);
 2901:     foreach my $part (@{$partids}) {
 2902: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2903:     }
 2904:     return %last_resets;
 2905: }
 2906: 
 2907: # ----------- Handles creating versions for portfolio files as answers
 2908: sub version_portfiles {
 2909:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2910:     my $version_parts = join('|',@$v_flag);
 2911:     my @returned_keys;
 2912:     my $parts = join('|', @$parts_graded);
 2913:     my $portfolio_root = '/userfiles/portfolio';
 2914:     foreach my $key (keys(%$record)) {
 2915:         my $new_portfiles;
 2916:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2917:             my @versioned_portfiles;
 2918:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2919:             foreach my $file (@portfiles) {
 2920:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2921:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2922: 		my ($answer_name,$answer_ver,$answer_ext) =
 2923: 		    &file_name_version_ext($answer_file);
 2924:                 my $getpropath = 1;    
 2925:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2926:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2927:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2928:                 if ($new_answer ne 'problem getting file') {
 2929:                     push(@versioned_portfiles, $directory.$new_answer);
 2930:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2931:                         [$directory.$new_answer],
 2932:                         [$symb,$env{'request.course.id'},'graded']);
 2933:                 }
 2934:             }
 2935:             $$record{$key} = join(',',@versioned_portfiles);
 2936:             push(@returned_keys,$key);
 2937:         }
 2938:     } 
 2939:     return (@returned_keys);   
 2940: }
 2941: 
 2942: sub get_next_version {
 2943:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2944:     my $version;
 2945:     foreach my $row (@$dir_list) {
 2946:         my ($file) = split(/\&/,$row,2);
 2947:         my ($file_name,$file_version,$file_ext) =
 2948: 	    &file_name_version_ext($file);
 2949:         if (($file_name eq $answer_name) && 
 2950: 	    ($file_ext eq $answer_ext)) {
 2951:                 # gets here if filename and extension match, regardless of version
 2952:                 if ($file_version ne '') {
 2953:                 # a versioned file is found  so save it for later
 2954:                 if ($file_version > $version) {
 2955: 		    $version = $file_version;
 2956: 	        }
 2957:             }
 2958:         }
 2959:     } 
 2960:     $version ++;
 2961:     return($version);
 2962: }
 2963: 
 2964: sub version_selected_portfile {
 2965:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2966:     my ($answer_name,$answer_ver,$answer_ext) =
 2967:         &file_name_version_ext($file_name);
 2968:     my $new_answer;
 2969:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2970:     if($env{'form.copy'} eq '-1') {
 2971:         $new_answer = 'problem getting file';
 2972:     } else {
 2973:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2974:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2975:                             $stu_name,$domain,'copy',
 2976: 		        '/portfolio'.$directory.$new_answer);
 2977:     }    
 2978:     return ($new_answer);
 2979: }
 2980: 
 2981: sub file_name_version_ext {
 2982:     my ($file)=@_;
 2983:     my @file_parts = split(/\./, $file);
 2984:     my ($name,$version,$ext);
 2985:     if (@file_parts > 1) {
 2986: 	$ext=pop(@file_parts);
 2987: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2988: 	    $version=pop(@file_parts);
 2989: 	}
 2990: 	$name=join('.',@file_parts);
 2991:     } else {
 2992: 	$name=join('.',@file_parts);
 2993:     }
 2994:     return($name,$version,$ext);
 2995: }
 2996: 
 2997: #--------------------------------------------------------------------------------------
 2998: #
 2999: #-------------------------- Next few routines handles grading by section or whole class
 3000: #
 3001: #--- Javascript to handle grading by section or whole class
 3002: sub viewgrades_js {
 3003:     my ($request) = shift;
 3004: 
 3005:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3006:     $request->print(<<VIEWJAVASCRIPT);
 3007: <script type="text/javascript" language="javascript">
 3008:    function writePoint(partid,weight,point) {
 3009: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3010: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3011: 	if (point == "textval") {
 3012: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3013: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3014: 		alert("$alertmsg"+parseFloat(point));
 3015: 		var resetbox = false;
 3016: 		for (var i=0; i<radioButton.length; i++) {
 3017: 		    if (radioButton[i].checked) {
 3018: 			textbox.value = i;
 3019: 			resetbox = true;
 3020: 		    }
 3021: 		}
 3022: 		if (!resetbox) {
 3023: 		    textbox.value = "";
 3024: 		}
 3025: 		return;
 3026: 	    }
 3027: 	    if (parseFloat(point) > parseFloat(weight)) {
 3028: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3029: 				   ") greater than the weight for the part. Accept?");
 3030: 		if (resp == false) {
 3031: 		    textbox.value = "";
 3032: 		    return;
 3033: 		}
 3034: 	    }
 3035: 	    for (var i=0; i<radioButton.length; i++) {
 3036: 		radioButton[i].checked=false;
 3037: 		if (parseFloat(point) == i) {
 3038: 		    radioButton[i].checked=true;
 3039: 		}
 3040: 	    }
 3041: 
 3042: 	} else {
 3043: 	    textbox.value = parseFloat(point);
 3044: 	}
 3045: 	for (i=0;i<document.classgrade.total.value;i++) {
 3046: 	    var user = document.classgrade["ctr"+i].value;
 3047: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3048: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3049: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3050: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3051: 	    if (saveval != "correct") {
 3052: 		scorename.value = point;
 3053: 		if (selname[0].selected != true) {
 3054: 		    selname[0].selected = true;
 3055: 		}
 3056: 	    }
 3057: 	}
 3058: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3059:     }
 3060: 
 3061:     function writeRadText(partid,weight) {
 3062: 	var selval   = document.classgrade["SELVAL_"+partid];
 3063: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3064:         var override = document.classgrade["FORCE_"+partid].checked;
 3065: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3066: 	if (selval[1].selected || selval[2].selected) {
 3067: 	    for (var i=0; i<radioButton.length; i++) {
 3068: 		radioButton[i].checked=false;
 3069: 
 3070: 	    }
 3071: 	    textbox.value = "";
 3072: 
 3073: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3074: 		var user = document.classgrade["ctr"+i].value;
 3075: 		user = user.replace(new RegExp(':', 'g'),"_");
 3076: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3077: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3078: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3079: 		if ((saveval != "correct") || override) {
 3080: 		    scorename.value = "";
 3081: 		    if (selval[1].selected) {
 3082: 			selname[1].selected = true;
 3083: 		    } else {
 3084: 			selname[2].selected = true;
 3085: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3086: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3087: 		    }
 3088: 		}
 3089: 	    }
 3090: 	} else {
 3091: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3092: 		var user = document.classgrade["ctr"+i].value;
 3093: 		user = user.replace(new RegExp(':', 'g'),"_");
 3094: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3095: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3096: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3097: 		if ((saveval != "correct") || override) {
 3098: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3099: 		    selname[0].selected = true;
 3100: 		}
 3101: 	    }
 3102: 	}	    
 3103:     }
 3104: 
 3105:     function changeSelect(partid,user) {
 3106: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3107: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3108: 	var point  = textbox.value;
 3109: 	var weight = document.classgrade["weight_"+partid].value;
 3110: 
 3111: 	if (isNaN(point) || parseFloat(point) < 0) {
 3112: 	    alert("$alertmsg"+parseFloat(point));
 3113: 	    textbox.value = "";
 3114: 	    return;
 3115: 	}
 3116: 	if (parseFloat(point) > parseFloat(weight)) {
 3117: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3118: 			       ") greater than the weight of the part. Accept?");
 3119: 	    if (resp == false) {
 3120: 		textbox.value = "";
 3121: 		return;
 3122: 	    }
 3123: 	}
 3124: 	selval[0].selected = true;
 3125:     }
 3126: 
 3127:     function changeOneScore(partid,user) {
 3128: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3129: 	if (selval[1].selected || selval[2].selected) {
 3130: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3131: 	    if (selval[2].selected) {
 3132: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3133: 	    }
 3134:         }
 3135:     }
 3136: 
 3137:     function resetEntry(numpart) {
 3138: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3139: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3140: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3141: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3142: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3143: 	    for (var i=0; i<radioButton.length; i++) {
 3144: 		radioButton[i].checked=false;
 3145: 
 3146: 	    }
 3147: 	    textbox.value = "";
 3148: 	    selval[0].selected = true;
 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 resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3154: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3155: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3156: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3157: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3158: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3159: 		if (saveselval == "excused") {
 3160: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3161: 		} else {
 3162: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3163: 		}
 3164: 	    }
 3165: 	}
 3166:     }
 3167: 
 3168: </script>
 3169: VIEWJAVASCRIPT
 3170: }
 3171: 
 3172: #--- show scores for a section or whole class w/ option to change/update a score
 3173: sub viewgrades {
 3174:     my ($request) = shift;
 3175:     &viewgrades_js($request);
 3176: 
 3177:     my ($symb) = &get_symb($request);
 3178:     #need to make sure we have the correct data for later EXT calls, 
 3179:     #thus invalidate the cache
 3180:     &Apache::lonnet::devalidatecourseresdata(
 3181:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3182:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3183:     &Apache::lonnet::clear_EXT_cache_status();
 3184: 
 3185:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3186:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3187: 
 3188:     #view individual student submission form - called using Javascript viewOneStudent
 3189:     $result.=&jscriptNform($symb);
 3190: 
 3191:     #beginning of class grading form
 3192:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3193:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3194: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3195: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3196: 	&build_section_inputs().
 3197: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3198: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3199: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3200: 
 3201:     my $sectionClass;
 3202:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3203:     if ($env{'form.section'} eq 'all') {
 3204: 	$sectionClass=&mt('Class');
 3205:     } elsif ($env{'form.section'} eq 'none') {
 3206: 	$sectionClass=&mt('Students in no Section');
 3207:     } else {
 3208: 	$sectionClass=&mt('Students in Section(s) [_1]');
 3209:     }
 3210:     $result.=
 3211: 	'<h3>'.
 3212: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
 3213:     $result.= &Apache::loncommon::start_data_table();
 3214:     #radio buttons/text box for assigning points for a section or class.
 3215:     #handles different parts of a problem
 3216:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3217:     my %weight = ();
 3218:     my $ctsparts = 0;
 3219:     my %seen = ();
 3220:     my @part_response_id = &flatten_responseType($responseType);
 3221:     foreach my $part_response_id (@part_response_id) {
 3222:     	my ($partid,$respid) = @{ $part_response_id };
 3223: 	my $part_resp = join('_',@{ $part_response_id });
 3224: 	next if $seen{$partid};
 3225: 	$seen{$partid}++;
 3226: 	my $handgrade=$$handgrade{$part_resp};
 3227: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3228: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3229: 
 3230: 	my $display_part=&get_display_part($partid,$symb);
 3231: 	my $radio.='<table border="0"><tr>';  
 3232: 	my $ctr = 0;
 3233: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3234: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3235: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3236: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3237: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3238: 	    $ctr++;
 3239: 	}
 3240: 	$radio.='</tr></table>';
 3241: 	my $line = '<input type="text" name="TEXTVAL_'.
 3242: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3243: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3244: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3245: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3246: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3247: 		$weight{$partid}.')"> '.
 3248: 	    '<option selected="selected"> </option>'.
 3249: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3250: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3251: 	    '</select></td>'.
 3252:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3253: 	$line.='<input type="hidden" name="partid_'.
 3254: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3255: 	$line.='<input type="hidden" name="weight_'.
 3256: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3257: 
 3258: 	$result.=
 3259: 	    &Apache::loncommon::start_data_table_row()."\n".
 3260: 	    '<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>'.
 3261: 	    &Apache::loncommon::end_data_table_row()."\n";
 3262: 	$ctsparts++;
 3263:     }
 3264:     $result.=&Apache::loncommon::end_data_table()."\n".
 3265: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3266:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3267: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3268: 
 3269:     #table listing all the students in a section/class
 3270:     #header of table
 3271:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
 3272: 			 $section_display.'</h3>';
 3273:     $result.= &Apache::loncommon::start_data_table().
 3274: 	&Apache::loncommon::start_data_table_header_row().
 3275: 	'<th>'.&mt('No.').'</th>'.
 3276: 	'<th>'.&nameUserString('header')."</th>\n";
 3277:     my (@parts) = sort(&getpartlist($symb));
 3278:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3279:     my @partids = ();
 3280:     foreach my $part (@parts) {
 3281: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3282:         my $narrowtext = &mt('Tries');
 3283: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
 3284: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3285: 	my ($partid) = &split_part_type($part);
 3286:         push(@partids,$partid);
 3287: 	my $display_part=&get_display_part($partid,$symb);
 3288: 	if ($display =~ /^Partial Credit Factor/) {
 3289: 	    $result.='<th>'.
 3290: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3291: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3292: 	    next;
 3293: 	    
 3294: 	} else {
 3295: 	    if ($display =~ /Problem Status/) {
 3296: 		my $grade_status_mt = &mt('Grade Status');
 3297: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3298: 	    }
 3299: 	    my $part_mt = &mt('Part:');
 3300: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3301: 	}
 3302: 
 3303: 	$result.='<th>'.$display.'</th>'."\n";
 3304:     }
 3305:     $result.=&Apache::loncommon::end_data_table_header_row();
 3306: 
 3307:     my %last_resets = 
 3308: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3309: 
 3310:     #get info for each student
 3311:     #list all the students - with points and grade status
 3312:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3313:     my $ctr = 0;
 3314:     foreach (sort 
 3315: 	     {
 3316: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3317: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3318: 		 }
 3319: 		 return $a cmp $b;
 3320: 	     } (keys(%$fullname))) {
 3321: 	$ctr++;
 3322: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3323: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3324:     }
 3325:     $result.=&Apache::loncommon::end_data_table();
 3326:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3327:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3328: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3329:     if (scalar(%$fullname) eq 0) {
 3330: 	my $colspan=3+scalar(@parts);
 3331: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3332:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3333: 	$result='<span class="LC_warning">'.
 3334: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3335: 	        $section_display, $stu_status).
 3336: 	    '</span>';
 3337:     }
 3338:     $result.=&show_grading_menu_form($symb);
 3339:     return $result;
 3340: }
 3341: 
 3342: #--- call by previous routine to display each student
 3343: sub viewstudentgrade {
 3344:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3345:     my ($uname,$udom) = split(/:/,$student);
 3346:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3347:     my %aggregates = (); 
 3348:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3349: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3350: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3351: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3352: 	'\');" target="_self">'.$fullname.'</a> '.
 3353: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3354:     $student=~s/:/_/; # colon doen't work in javascript for names
 3355:     foreach my $apart (@$parts) {
 3356: 	my ($part,$type) = &split_part_type($apart);
 3357: 	my $score=$record{"resource.$part.$type"};
 3358:         $result.='<td align="center">';
 3359:         my ($aggtries,$totaltries);
 3360:         unless (exists($aggregates{$part})) {
 3361: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3362: 
 3363: 	    $aggtries = $totaltries;
 3364:             if ($$last_resets{$part}) {  
 3365:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3366: 					   $part);
 3367:             }
 3368:             $result.='<input type="hidden" name="'.
 3369:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3370:             $result.='<input type="hidden" name="'.
 3371:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3372:             $aggregates{$part} = 1;
 3373:         }
 3374: 	if ($type eq 'awarded') {
 3375: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3376: 	    $result.='<input type="hidden" name="'.
 3377: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3378: 	    $result.='<input type="text" name="'.
 3379: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3380: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3381: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3382: 	} elsif ($type eq 'solved') {
 3383: 	    my ($status,$foo)=split(/_/,$score,2);
 3384: 	    $status = 'nothing' if ($status eq '');
 3385: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3386: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3387: 	    $result.='&nbsp;<select name="'.
 3388: 		'GD_'.$student.'_'.$part.'_solved" '.
 3389: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3390: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3391: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3392: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3393: 	    $result.="</select>&nbsp;</td>\n";
 3394: 	} else {
 3395: 	    $result.='<input type="hidden" name="'.
 3396: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3397: 		    "\n";
 3398: 	    $result.='<input type="text" name="'.
 3399: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3400: 		'value="'.$score.'" size="4" /></td>'."\n";
 3401: 	}
 3402:     }
 3403:     $result.=&Apache::loncommon::end_data_table_row();
 3404:     return $result;
 3405: }
 3406: 
 3407: #--- change scores for all the students in a section/class
 3408: #    record does not get update if unchanged
 3409: sub editgrades {
 3410:     my ($request) = @_;
 3411: 
 3412:     my $symb=&get_symb($request);
 3413:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3414:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3415:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3416:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3417: 
 3418:     my $result= &Apache::loncommon::start_data_table().
 3419: 	&Apache::loncommon::start_data_table_header_row().
 3420: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3421: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3422:     my %scoreptr = (
 3423: 		    'correct'  =>'correct_by_override',
 3424: 		    'incorrect'=>'incorrect_by_override',
 3425: 		    'excused'  =>'excused',
 3426: 		    'ungraded' =>'ungraded_attempted',
 3427: 		    'nothing'  => '',
 3428: 		    );
 3429:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3430: 
 3431:     my (@partid);
 3432:     my %weight = ();
 3433:     my %columns = ();
 3434:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3435: 
 3436:     my (@parts) = sort(&getpartlist($symb));
 3437:     my $header;
 3438:     while ($ctr < $env{'form.totalparts'}) {
 3439: 	my $partid = $env{'form.partid_'.$ctr};
 3440: 	push(@partid,$partid);
 3441: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3442: 	$ctr++;
 3443:     }
 3444:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3445:     foreach my $partid (@partid) {
 3446: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3447: 	    '<th align="center">'.&mt('New Score').'</th>';
 3448: 	$columns{$partid}=2;
 3449: 	foreach my $stores (@parts) {
 3450: 	    my ($part,$type) = &split_part_type($stores);
 3451: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3452: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3453: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3454: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3455:             my $narrowtext = &mt('Tries');
 3456: 	    $display =~ s/Number of Attempts/$narrowtext/;
 3457: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3458: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3459: 	    $columns{$partid}+=2;
 3460: 	}
 3461:     }
 3462:     foreach my $partid (@partid) {
 3463: 	my $display_part=&get_display_part($partid,$symb);
 3464: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3465: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3466: 	    '</th>';
 3467: 
 3468:     }
 3469:     $result .= &Apache::loncommon::end_data_table_header_row().
 3470: 	&Apache::loncommon::start_data_table_header_row().
 3471: 	$header.
 3472: 	&Apache::loncommon::end_data_table_header_row();
 3473:     my @noupdate;
 3474:     my ($updateCtr,$noupdateCtr) = (1,1);
 3475:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3476: 	my $line;
 3477: 	my $user = $env{'form.ctr'.$i};
 3478: 	my ($uname,$udom)=split(/:/,$user);
 3479: 	my %newrecord;
 3480: 	my $updateflag = 0;
 3481: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3482: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3483: 	if (!&canmodify($usec)) {
 3484: 	    my $numcols=scalar(@partid)*4+2;
 3485: 	    push(@noupdate,
 3486: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3487: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3488: 	    next;
 3489: 	}
 3490:         my %aggregate = ();
 3491:         my $aggregateflag = 0;
 3492: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3493: 	foreach (@partid) {
 3494: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3495: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3496: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3497: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3498: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3499: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3500: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3501: 	    my $score;
 3502: 	    if ($partial eq '') {
 3503: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3504: 	    } elsif ($partial > 0) {
 3505: 		$score = 'correct_by_override';
 3506: 	    } elsif ($partial == 0) {
 3507: 		$score = 'incorrect_by_override';
 3508: 	    }
 3509: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3510: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3511: 
 3512: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3513: 		"$env{'user.name'}:$env{'user.domain'}";
 3514: 	    if ($dropMenu eq 'reset status' &&
 3515: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3516: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3517: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3518: 		$newrecord{'resource.'.$_.'.award'} = '';
 3519: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3520: 		$updateflag = 1;
 3521:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3522:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3523:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3524:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3525:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3526:                     $aggregateflag = 1;
 3527:                 }
 3528: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3529: 		$updateflag = 1;
 3530: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3531: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3532: 		$rec_update++;
 3533: 	    }
 3534: 
 3535: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3536: 		'<td align="center">'.$awarded.
 3537: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3538: 
 3539: 
 3540: 	    my $partid=$_;
 3541: 	    foreach my $stores (@parts) {
 3542: 		my ($part,$type) = &split_part_type($stores);
 3543: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3544: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3545: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3546: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3547: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3548: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3549: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3550: 		    $updateflag=1;
 3551: 		}
 3552: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3553: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3554: 	    }
 3555: 	}
 3556: 	$line.="\n";
 3557: 
 3558: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3559: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3560: 
 3561: 	if ($updateflag) {
 3562: 	    $count++;
 3563: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3564: 				    $udom,$uname);
 3565: 
 3566: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3567: 					      $cnum,$udom,$uname)) {
 3568: 		# need to figure out if should be in queue.
 3569: 		my %record =  
 3570: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3571: 					     $udom,$uname);
 3572: 		my $all_graded = 1;
 3573: 		my $none_graded = 1;
 3574: 		foreach my $part (@parts) {
 3575: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3576: 			$all_graded = 0;
 3577: 		    } else {
 3578: 			$none_graded = 0;
 3579: 		    }
 3580: 		}
 3581: 
 3582: 		if ($all_graded || $none_graded) {
 3583: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3584: 							   $symb,$cdom,$cnum,
 3585: 							   $udom,$uname);
 3586: 		}
 3587: 	    }
 3588: 
 3589: 	    $result.=&Apache::loncommon::start_data_table_row().
 3590: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3591: 		&Apache::loncommon::end_data_table_row();
 3592: 	    $updateCtr++;
 3593: 	} else {
 3594: 	    push(@noupdate,
 3595: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3596: 	    $noupdateCtr++;
 3597: 	}
 3598:         if ($aggregateflag) {
 3599:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3600: 				  $cdom,$cnum);
 3601:         }
 3602:     }
 3603:     if (@noupdate) {
 3604: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3605: 	my $numcols=scalar(@partid)*4+2;
 3606: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3607: 	    '<td align="center" colspan="'.$numcols.'">'.
 3608: 	    &mt('No Changes Occurred For the Students Below').
 3609: 	    '</td>'.
 3610: 	    &Apache::loncommon::end_data_table_row();
 3611: 	foreach my $line (@noupdate) {
 3612: 	    $result.=
 3613: 		&Apache::loncommon::start_data_table_row().
 3614: 		$line.
 3615: 		&Apache::loncommon::end_data_table_row();
 3616: 	}
 3617:     }
 3618:     $result .= &Apache::loncommon::end_data_table().
 3619: 	&show_grading_menu_form($symb);
 3620:     my $msg = '<p><b>'.
 3621: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3622: 	    $rec_update,$count).'</b><br />'.
 3623: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3624: 	'</b></p>';
 3625:     return $title.$msg.$result;
 3626: }
 3627: 
 3628: sub split_part_type {
 3629:     my ($partstr) = @_;
 3630:     my ($temp,@allparts)=split(/_/,$partstr);
 3631:     my $type=pop(@allparts);
 3632:     my $part=join('_',@allparts);
 3633:     return ($part,$type);
 3634: }
 3635: 
 3636: #------------- end of section for handling grading by section/class ---------
 3637: #
 3638: #----------------------------------------------------------------------------
 3639: 
 3640: 
 3641: #----------------------------------------------------------------------------
 3642: #
 3643: #-------------------------- Next few routines handles grading by csv upload
 3644: #
 3645: #--- Javascript to handle csv upload
 3646: sub csvupload_javascript_reverse_associate {
 3647:     my $error1=&mt('You need to specify the username or ID');
 3648:     my $error2=&mt('You need to specify at least one grading field');
 3649:   return(<<ENDPICK);
 3650:   function verify(vf) {
 3651:     var foundsomething=0;
 3652:     var founduname=0;
 3653:     var foundID=0;
 3654:     for (i=0;i<=vf.nfields.value;i++) {
 3655:       tw=eval('vf.f'+i+'.selectedIndex');
 3656:       if (i==0 && tw!=0) { foundID=1; }
 3657:       if (i==1 && tw!=0) { founduname=1; }
 3658:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3659:     }
 3660:     if (founduname==0 && foundID==0) {
 3661: 	alert('$error1');
 3662: 	return;
 3663:     }
 3664:     if (foundsomething==0) {
 3665: 	alert('$error2');
 3666: 	return;
 3667:     }
 3668:     vf.submit();
 3669:   }
 3670:   function flip(vf,tf) {
 3671:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3672:     var i;
 3673:     for (i=0;i<=vf.nfields.value;i++) {
 3674:       //can not pick the same destination field for both name and domain
 3675:       if (((i ==0)||(i ==1)) && 
 3676:           ((tf==0)||(tf==1)) && 
 3677:           (i!=tf) &&
 3678:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3679:         eval('vf.f'+i+'.selectedIndex=0;')
 3680:       }
 3681:     }
 3682:   }
 3683: ENDPICK
 3684: }
 3685: 
 3686: sub csvupload_javascript_forward_associate {
 3687:     my $error1=&mt('You need to specify the username or ID');
 3688:     my $error2=&mt('You need to specify at least one grading field');
 3689:   return(<<ENDPICK);
 3690:   function verify(vf) {
 3691:     var foundsomething=0;
 3692:     var founduname=0;
 3693:     var foundID=0;
 3694:     for (i=0;i<=vf.nfields.value;i++) {
 3695:       tw=eval('vf.f'+i+'.selectedIndex');
 3696:       if (tw==1) { foundID=1; }
 3697:       if (tw==2) { founduname=1; }
 3698:       if (tw>3) { foundsomething=1; }
 3699:     }
 3700:     if (founduname==0 && foundID==0) {
 3701: 	alert('$error1');
 3702: 	return;
 3703:     }
 3704:     if (foundsomething==0) {
 3705: 	alert('$error2');
 3706: 	return;
 3707:     }
 3708:     vf.submit();
 3709:   }
 3710:   function flip(vf,tf) {
 3711:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3712:     var i;
 3713:     //can not pick the same destination field twice
 3714:     for (i=0;i<=vf.nfields.value;i++) {
 3715:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3716:         eval('vf.f'+i+'.selectedIndex=0;')
 3717:       }
 3718:     }
 3719:   }
 3720: ENDPICK
 3721: }
 3722: 
 3723: sub csvuploadmap_header {
 3724:     my ($request,$symb,$datatoken,$distotal)= @_;
 3725:     my $javascript;
 3726:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3727: 	$javascript=&csvupload_javascript_reverse_associate();
 3728:     } else {
 3729: 	$javascript=&csvupload_javascript_forward_associate();
 3730:     }
 3731: 
 3732:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3733:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3734:     my $ignore=&mt('Ignore First Line');
 3735:     $symb = &Apache::lonenc::check_encrypt($symb);
 3736:     $request->print(<<ENDPICK);
 3737: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3738: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3739: $result
 3740: <hr />
 3741: <h3>Identify fields</h3>
 3742: Total number of records found in file: $distotal <hr />
 3743: Enter as many fields as you can. The system will inform you and bring you back
 3744: to this page if the data selected is insufficient to run your class.<hr />
 3745: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3746: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3747: <input type="hidden" name="associate"  value="" />
 3748: <input type="hidden" name="phase"      value="three" />
 3749: <input type="hidden" name="datatoken"  value="$datatoken" />
 3750: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3751: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3752: <input type="hidden" name="upfile_associate" 
 3753:                                        value="$env{'form.upfile_associate'}" />
 3754: <input type="hidden" name="symb"       value="$symb" />
 3755: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3756: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3757: <input type="hidden" name="command"    value="csvuploadoptions" />
 3758: <hr />
 3759: <script type="text/javascript" language="Javascript">
 3760: $javascript
 3761: </script>
 3762: ENDPICK
 3763:     return '';
 3764: 
 3765: }
 3766: 
 3767: sub csvupload_fields {
 3768:     my ($symb) = @_;
 3769:     my (@parts) = &getpartlist($symb);
 3770:     my @fields=(['ID','Student/Employee ID'],
 3771: 		['username','Student Username'],
 3772: 		['domain','Student Domain']);
 3773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3774:     foreach my $part (sort(@parts)) {
 3775: 	my @datum;
 3776: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3777: 	my $name=$part;
 3778: 	if  (!$display) { $display = $name; }
 3779: 	@datum=($name,$display);
 3780: 	if ($name=~/^stores_(.*)_awarded/) {
 3781: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3782: 	}
 3783: 	push(@fields,\@datum);
 3784:     }
 3785:     return (@fields);
 3786: }
 3787: 
 3788: sub csvuploadmap_footer {
 3789:     my ($request,$i,$keyfields) =@_;
 3790:     $request->print(<<ENDPICK);
 3791: </table>
 3792: <input type="hidden" name="nfields" value="$i" />
 3793: <input type="hidden" name="keyfields" value="$keyfields" />
 3794: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3795: </form>
 3796: ENDPICK
 3797: }
 3798: 
 3799: sub checkforfile_js {
 3800:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3801:     my $result =<<CSVFORMJS;
 3802: <script type="text/javascript" language="javascript">
 3803:     function checkUpload(formname) {
 3804: 	if (formname.upfile.value == "") {
 3805: 	    alert("$alertmsg");
 3806: 	    return false;
 3807: 	}
 3808: 	formname.submit();
 3809:     }
 3810:     </script>
 3811: CSVFORMJS
 3812:     return $result;
 3813: }
 3814: 
 3815: sub upcsvScores_form {
 3816:     my ($request) = shift;
 3817:     my ($symb)=&get_symb($request);
 3818:     if (!$symb) {return '';}
 3819:     my $result=&checkforfile_js();
 3820:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3821:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3822:     $result.=$table;
 3823:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3824:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3825:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3826: 	'</b></td></tr>'."\n";
 3827:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3828:     my $upload=&mt("Upload Scores");
 3829:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3830:     my $ignore=&mt('Ignore First Line');
 3831:     $symb = &Apache::lonenc::check_encrypt($symb);
 3832:     $result.=<<ENDUPFORM;
 3833: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3834: <input type="hidden" name="symb" value="$symb" />
 3835: <input type="hidden" name="command" value="csvuploadmap" />
 3836: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3837: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3838: $upfile_select
 3839: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3840: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3841: </form>
 3842: ENDUPFORM
 3843:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3844:                            &mt("How do I create a CSV file from a spreadsheet"))
 3845:     .'</td></tr></table>'."\n";
 3846:     $result.='</td></tr></table><br /><br />'."\n";
 3847:     $result.=&show_grading_menu_form($symb);
 3848:     return $result;
 3849: }
 3850: 
 3851: 
 3852: sub csvuploadmap {
 3853:     my ($request)= @_;
 3854:     my ($symb)=&get_symb($request);
 3855:     if (!$symb) {return '';}
 3856: 
 3857:     my $datatoken;
 3858:     if (!$env{'form.datatoken'}) {
 3859: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3860:     } else {
 3861: 	$datatoken=$env{'form.datatoken'};
 3862: 	&Apache::loncommon::load_tmp_file($request);
 3863:     }
 3864:     my @records=&Apache::loncommon::upfile_record_sep();
 3865:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3866:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3867:     my ($i,$keyfields);
 3868:     if (@records) {
 3869: 	my @fields=&csvupload_fields($symb);
 3870: 
 3871: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3872: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3873: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3874: 							  \@fields);
 3875: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3876: 	    chop($keyfields);
 3877: 	} else {
 3878: 	    unshift(@fields,['none','']);
 3879: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3880: 							    \@fields);
 3881:             foreach my $rec (@records) {
 3882:                 my %temp = &Apache::loncommon::record_sep($rec);
 3883:                 if (%temp) {
 3884:                     $keyfields=join(',',sort(keys(%temp)));
 3885:                     last;
 3886:                 }
 3887:             }
 3888: 	}
 3889:     }
 3890:     &csvuploadmap_footer($request,$i,$keyfields);
 3891:     $request->print(&show_grading_menu_form($symb));
 3892: 
 3893:     return '';
 3894: }
 3895: 
 3896: sub csvuploadoptions {
 3897:     my ($request)= @_;
 3898:     my ($symb)=&get_symb($request);
 3899:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3900:     my $ignore=&mt('Ignore First Line');
 3901:     $request->print(<<ENDPICK);
 3902: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3903: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3904: <input type="hidden" name="command"    value="csvuploadassign" />
 3905: <!--
 3906: <p>
 3907: <label>
 3908:    <input type="checkbox" name="show_full_results" />
 3909:    Show a table of all changes
 3910: </label>
 3911: </p>
 3912: -->
 3913: <p>
 3914: <label>
 3915:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3916:    Overwrite any existing score
 3917: </label>
 3918: </p>
 3919: ENDPICK
 3920:     my %fields=&get_fields();
 3921:     if (!defined($fields{'domain'})) {
 3922: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3923: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3924:     }
 3925:     foreach my $key (sort(keys(%env))) {
 3926: 	if ($key !~ /^form\.(.*)$/) { next; }
 3927: 	my $cleankey=$1;
 3928: 	if ($cleankey eq 'command') { next; }
 3929: 	$request->print('<input type="hidden" name="'.$cleankey.
 3930: 			'"  value="'.$env{$key}.'" />'."\n");
 3931:     }
 3932:     # FIXME do a check for any duplicated user ids...
 3933:     # FIXME do a check for any invalid user ids?...
 3934:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3935: <hr /></form>'."\n");
 3936:     $request->print(&show_grading_menu_form($symb));
 3937:     return '';
 3938: }
 3939: 
 3940: sub get_fields {
 3941:     my %fields;
 3942:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3943:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3944: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3945: 	    if ($env{'form.f'.$i} ne 'none') {
 3946: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3947: 	    }
 3948: 	} else {
 3949: 	    if ($env{'form.f'.$i} ne 'none') {
 3950: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3951: 	    }
 3952: 	}
 3953:     }
 3954:     return %fields;
 3955: }
 3956: 
 3957: sub csvuploadassign {
 3958:     my ($request)= @_;
 3959:     my ($symb)=&get_symb($request);
 3960:     if (!$symb) {return '';}
 3961:     my $error_msg = '';
 3962:     &Apache::loncommon::load_tmp_file($request);
 3963:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3964:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3965:     my %fields=&get_fields();
 3966:     $request->print('<h3>Assigning Grades</h3>');
 3967:     my $courseid=$env{'request.course.id'};
 3968:     my ($classlist) = &getclasslist('all',0);
 3969:     my @notallowed;
 3970:     my @skipped;
 3971:     my $countdone=0;
 3972:     foreach my $grade (@gradedata) {
 3973: 	my %entries=&Apache::loncommon::record_sep($grade);
 3974: 	my $domain;
 3975: 	if ($entries{$fields{'domain'}}) {
 3976: 	    $domain=$entries{$fields{'domain'}};
 3977: 	} else {
 3978: 	    $domain=$env{'form.default_domain'};
 3979: 	}
 3980: 	$domain=~s/\s//g;
 3981: 	my $username=$entries{$fields{'username'}};
 3982: 	$username=~s/\s//g;
 3983: 	if (!$username) {
 3984: 	    my $id=$entries{$fields{'ID'}};
 3985: 	    $id=~s/\s//g;
 3986: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3987: 	    $username=$ids{$id};
 3988: 	}
 3989: 	if (!exists($$classlist{"$username:$domain"})) {
 3990: 	    my $id=$entries{$fields{'ID'}};
 3991: 	    $id=~s/\s//g;
 3992: 	    if ($id) {
 3993: 		push(@skipped,"$id:$domain");
 3994: 	    } else {
 3995: 		push(@skipped,"$username:$domain");
 3996: 	    }
 3997: 	    next;
 3998: 	}
 3999: 	my $usec=$classlist->{"$username:$domain"}[5];
 4000: 	if (!&canmodify($usec)) {
 4001: 	    push(@notallowed,"$username:$domain");
 4002: 	    next;
 4003: 	}
 4004: 	my %points;
 4005: 	my %grades;
 4006: 	foreach my $dest (keys(%fields)) {
 4007: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4008: 		$dest eq 'domain') { next; }
 4009: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4010: 	    if ($dest=~/stores_(.*)_points/) {
 4011: 		my $part=$1;
 4012: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4013: 					      $symb,$domain,$username);
 4014:                 if ($wgt) {
 4015:                     $entries{$fields{$dest}}=~s/\s//g;
 4016:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4017:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4018:                                           : 'correct_by_override';
 4019:                     $grades{"resource.$part.awarded"}=$pcr;
 4020:                     $grades{"resource.$part.solved"}=$award;
 4021:                     $points{$part}=1;
 4022:                 } else {
 4023:                     $error_msg = "<br />" .
 4024:                         &mt("Some point values were assigned"
 4025:                             ." for problems with a weight "
 4026:                             ."of zero. These values were "
 4027:                             ."ignored.");
 4028:                 }
 4029: 	    } else {
 4030: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4031: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4032: 		my $store_key=$dest;
 4033: 		$store_key=~s/^stores/resource/;
 4034: 		$store_key=~s/_/\./g;
 4035: 		$grades{$store_key}=$entries{$fields{$dest}};
 4036: 	    }
 4037: 	}
 4038: 	if (! %grades) { 
 4039:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4040:         } else {
 4041: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4042: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4043: 					   $env{'request.course.id'},
 4044: 					   $domain,$username);
 4045: 	   if ($result eq 'ok') {
 4046: 	      $request->print('.');
 4047: 	   } else {
 4048: 	      $request->print("<p><span class=\"LC_error\">".
 4049:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4050:                                   "$username:$domain",$result)."</span></p>");
 4051: 	   }
 4052: 	   $request->rflush();
 4053: 	   $countdone++;
 4054:         }
 4055:     }
 4056:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4057:     if (@skipped) {
 4058: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4059: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4060:     }
 4061:     if (@notallowed) {
 4062: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4063: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4064:     }
 4065:     $request->print("<br />\n");
 4066:     $request->print(&show_grading_menu_form($symb));
 4067:     return $error_msg;
 4068: }
 4069: #------------- end of section for handling csv file upload ---------
 4070: #
 4071: #-------------------------------------------------------------------
 4072: #
 4073: #-------------- Next few routines handle grading by page/sequence
 4074: #
 4075: #--- Select a page/sequence and a student to grade
 4076: sub pickStudentPage {
 4077:     my ($request) = shift;
 4078: 
 4079:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4080:     $request->print(<<LISTJAVASCRIPT);
 4081: <script type="text/javascript" language="javascript">
 4082: 
 4083: function checkPickOne(formname) {
 4084:     if (radioSelection(formname.student) == null) {
 4085: 	alert("$alertmsg");
 4086: 	return;
 4087:     }
 4088:     ptr = pullDownSelection(formname.selectpage);
 4089:     formname.page.value = formname["page"+ptr].value;
 4090:     formname.title.value = formname["title"+ptr].value;
 4091:     formname.submit();
 4092: }
 4093: 
 4094: </script>
 4095: LISTJAVASCRIPT
 4096:     &commonJSfunctions($request);
 4097:     my ($symb) = &get_symb($request);
 4098:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4099:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4100:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4101: 
 4102:     my $result='<h3><span class="LC_info">&nbsp;'.
 4103: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4104: 
 4105:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4106:     my ($titles,$symbx) = &getSymbMap();
 4107:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4108: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4109: #    my $type=($curpage =~ /\.(page|sequence)/);
 4110:     my $select = '<select name="selectpage">'."\n";
 4111:     my $ctr=0;
 4112:     foreach (@$titles) {
 4113: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4114: 	$select.='<option value="'.$ctr.'" '.
 4115: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4116: 	    '>'.$showtitle.'</option>'."\n";
 4117: 	$ctr++;
 4118:     }
 4119:     $select.= '</select>';
 4120:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
 4121: 
 4122:     $ctr=0;
 4123:     foreach (@$titles) {
 4124: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4125: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4126: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4127: 	$ctr++;
 4128:     }
 4129:     $result.='<input type="hidden" name="page" />'."\n".
 4130: 	'<input type="hidden" name="title" />'."\n";
 4131: 
 4132:     my $options =
 4133: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4134: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4135:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
 4136: 
 4137:     $options =
 4138: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4139: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4140: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4141:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
 4142:     
 4143:     $result.=&build_section_inputs();
 4144:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4145:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4146: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4147: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4148: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4149: 
 4150:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
 4151: 
 4152:     $result.='&nbsp;<input type="button" '.
 4153: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4154: 
 4155:     $request->print($result);
 4156: 
 4157:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4158: 	&Apache::loncommon::start_data_table().
 4159: 	&Apache::loncommon::start_data_table_header_row().
 4160: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4161: 	'<th>'.&nameUserString('header').'</th>'.
 4162: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4163: 	'<th>'.&nameUserString('header').'</th>'.
 4164: 	&Apache::loncommon::end_data_table_header_row();
 4165:  
 4166:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4167:     my $ptr = 1;
 4168:     foreach my $student (sort 
 4169: 			 {
 4170: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4171: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4172: 			     }
 4173: 			     return $a cmp $b;
 4174: 			 } (keys(%$fullname))) {
 4175: 	my ($uname,$udom) = split(/:/,$student);
 4176: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4177:                                   : '</td>');
 4178: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4179: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4180: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4181: 	$studentTable.=
 4182: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4183:                          : '');
 4184: 	$ptr++;
 4185:     }
 4186:     if ($ptr%2 == 0) {
 4187: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4188: 	    &Apache::loncommon::end_data_table_row();
 4189:     }
 4190:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4191:     $studentTable.='<input type="button" '.
 4192: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
 4193: 
 4194:     $studentTable.=&show_grading_menu_form($symb);
 4195:     $request->print($studentTable);
 4196: 
 4197:     return '';
 4198: }
 4199: 
 4200: sub getSymbMap {
 4201:     my $navmap = Apache::lonnavmaps::navmap->new();
 4202: 
 4203:     my %symbx = ();
 4204:     my @titles = ();
 4205:     my $minder = 0;
 4206: 
 4207:     # Gather every sequence that has problems.
 4208:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4209: 					       1,0,1);
 4210:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4211: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4212: 	    my $title = $minder.'.'.
 4213: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4214: 	    push(@titles, $title); # minder in case two titles are identical
 4215: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4216: 	    $minder++;
 4217: 	}
 4218:     }
 4219:     return \@titles,\%symbx;
 4220: }
 4221: 
 4222: #
 4223: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4224: sub displayPage {
 4225:     my ($request) = shift;
 4226: 
 4227:     my ($symb) = &get_symb($request);
 4228:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4229:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4230:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4231:     my $pageTitle = $env{'form.page'};
 4232:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4233:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4234:     my $usec=$classlist->{$env{'form.student'}}[5];
 4235: 
 4236:     #need to make sure we have the correct data for later EXT calls, 
 4237:     #thus invalidate the cache
 4238:     &Apache::lonnet::devalidatecourseresdata(
 4239:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4240:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4241:     &Apache::lonnet::clear_EXT_cache_status();
 4242: 
 4243:     if (!&canview($usec)) {
 4244: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4245: 	$request->print(&show_grading_menu_form($symb));
 4246: 	return;
 4247:     }
 4248:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4249:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4250: 	'</h3>'."\n";
 4251:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4252:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4253: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4254:     } else {
 4255: 	delete($env{'form.CODE'});
 4256:     }
 4257:     &sub_page_js($request);
 4258:     $request->print($result);
 4259: 
 4260:     my $navmap = Apache::lonnavmaps::navmap->new();
 4261:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4262:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4263:     if (!$map) {
 4264: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4265: 	$request->print(&show_grading_menu_form($symb));
 4266: 	return; 
 4267:     }
 4268:     my $iterator = $navmap->getIterator($map->map_start(),
 4269: 					$map->map_finish());
 4270: 
 4271:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4272: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4273: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4274: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4275: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4276: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4277: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4278: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4279: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4280: 
 4281:     if (defined($env{'form.CODE'})) {
 4282: 	$studentTable.=
 4283: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4284:     }
 4285:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4286: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4287: 
 4288:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4289: 	&Apache::loncommon::start_data_table().
 4290: 	&Apache::loncommon::start_data_table_header_row().
 4291: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4292: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4293: 	&Apache::loncommon::end_data_table_header_row();
 4294: 
 4295:     &Apache::lonxml::clear_problem_counter();
 4296:     my ($depth,$question,$prob) = (1,1,1);
 4297:     $iterator->next(); # skip the first BEGIN_MAP
 4298:     my $curRes = $iterator->next(); # for "current resource"
 4299:     while ($depth > 0) {
 4300:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4301:         if($curRes == $iterator->END_MAP) { $depth--; }
 4302: 
 4303:         if (ref($curRes) && $curRes->is_problem()) {
 4304: 	    my $parts = $curRes->parts();
 4305:             my $title = $curRes->compTitle();
 4306: 	    my $symbx = $curRes->symb();
 4307: 	    $studentTable.=
 4308: 		&Apache::loncommon::start_data_table_row().
 4309: 		'<td align="center" valign="top" >'.$prob.
 4310: 		(scalar(@{$parts}) == 1 ? '' 
 4311: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4312: 							scalar(@{$parts}))
 4313: 		 ).
 4314: 		 '</td>';
 4315: 	    $studentTable.='<td valign="top">';
 4316: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4317: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4318: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4319: 					     undef,'both',\%form);
 4320: 	    } else {
 4321: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4322: 		$companswer =~ s|<form(.*?)>||g;
 4323: 		$companswer =~ s|</form>||g;
 4324: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4325: #		    $companswer =~ s/$1/ /ms;
 4326: #		    $request->print('match='.$1."<br />\n");
 4327: #		}
 4328: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4329: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4330: 	    }
 4331: 
 4332: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4333: 
 4334: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4335: 		if ($record{'version'} eq '') {
 4336: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4337: 		} else {
 4338: 		    my %responseType = ();
 4339: 		    foreach my $partid (@{$parts}) {
 4340: 			my @responseIds =$curRes->responseIds($partid);
 4341: 			my @responseType =$curRes->responseType($partid);
 4342: 			my %responseIds;
 4343: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4344: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4345: 			}
 4346: 			$responseType{$partid} = \%responseIds;
 4347: 		    }
 4348: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4349: 
 4350: 		}
 4351: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4352: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4353: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4354: 									$env{'request.course.id'},
 4355: 									'','.submission');
 4356:  
 4357: 	    }
 4358: 	    if (&canmodify($usec)) {
 4359: 		foreach my $partid (@{$parts}) {
 4360: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4361: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4362: 		    $question++;
 4363: 		}
 4364: 		$prob++;
 4365: 	    }
 4366: 	    $studentTable.='</td></tr>';
 4367: 
 4368: 	}
 4369:         $curRes = $iterator->next();
 4370:     }
 4371: 
 4372:     $studentTable.='</table>'."\n".
 4373: 	'<input type="button" value="'.&mt('Save').'" '.
 4374: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4375: 	'</form>'."\n";
 4376:     $studentTable.=&show_grading_menu_form($symb);
 4377:     $request->print($studentTable);
 4378: 
 4379:     return '';
 4380: }
 4381: 
 4382: sub displaySubByDates {
 4383:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4384:     my $isCODE=0;
 4385:     my $isTask = ($symb =~/\.task$/);
 4386:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4387:     my $studentTable=&Apache::loncommon::start_data_table().
 4388: 	&Apache::loncommon::start_data_table_header_row().
 4389: 	'<th>'.&mt('Date/Time').'</th>'.
 4390: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4391: 	'<th>'.&mt('Submission').'</th>'.
 4392: 	'<th>'.&mt('Status').'</th>'.
 4393: 	&Apache::loncommon::end_data_table_header_row();
 4394:     my ($version);
 4395:     my %mark;
 4396:     my %orders;
 4397:     $mark{'correct_by_student'} = $checkIcon;
 4398:     if (!exists($$record{'1:timestamp'})) {
 4399: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4400:     }
 4401: 
 4402:     my $interaction;
 4403:     my $no_increment = 1;
 4404:     for ($version=1;$version<=$$record{'version'};$version++) {
 4405: 	my $timestamp = 
 4406: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4407: 	if (exists($$record{$version.':resource.0.version'})) {
 4408: 	    $interaction = $$record{$version.':resource.0.version'};
 4409: 	}
 4410: 
 4411: 	my $where = ($isTask ? "$version:resource.$interaction"
 4412: 		             : "$version:resource");
 4413: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4414: 	    '<td>'.$timestamp.'</td>';
 4415: 	if ($isCODE) {
 4416: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4417: 	}
 4418: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4419: 	my @displaySub = ();
 4420: 	foreach my $partid (@{$parts}) {
 4421: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4422: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4423: 	    
 4424: 
 4425: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4426: 	    my $display_part=&get_display_part($partid,$symb);
 4427: 	    foreach my $matchKey (@matchKey) {
 4428: 		if (exists($$record{$version.':'.$matchKey}) &&
 4429: 		    $$record{$version.':'.$matchKey} ne '') {
 4430: 
 4431: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4432: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4433: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4434: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4435: 			$responseId.')</span>&nbsp;<b>';
 4436: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4437: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4438: 		    } else {
 4439: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4440: 					    $$record{"$where.$partid.tries"});
 4441: 		    }
 4442: 		    my $responseType=($isTask ? 'Task'
 4443:                                               : $responseType->{$partid}->{$responseId});
 4444: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4445: 		    if (!exists($orders{$partid}->{$responseId})) {
 4446: 			$orders{$partid}->{$responseId}=
 4447: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4448:                                        $no_increment);
 4449: 		    }
 4450: 		    $displaySub[0].='</b>&nbsp; '.
 4451: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4452: 		}
 4453: 	    }
 4454: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4455: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4456: 				    $$record{"$where.$partid.checkedin"},
 4457: 				    $$record{"$where.$partid.checkedin.slot"}).
 4458: 					'<br />';
 4459: 	    }
 4460: 	    if (exists $$record{"$where.$partid.award"}) {
 4461: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4462: 		    lc($$record{"$where.$partid.award"}).' '.
 4463: 		    $mark{$$record{"$where.$partid.solved"}}.
 4464: 		    '<br />';
 4465: 	    }
 4466: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4467: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4468: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4469: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4470: 		$displaySub[2].=
 4471: 		    $$record{"$version:resource.$partid.regrader"}.
 4472: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4473: 	    }
 4474: 	}
 4475: 	# needed because old essay regrader has not parts info
 4476: 	if (exists $$record{"$version:resource.regrader"}) {
 4477: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4478: 	}
 4479: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4480: 	if ($displaySub[2]) {
 4481: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4482: 	}
 4483: 	$studentTable.='&nbsp;</td>'.
 4484: 	    &Apache::loncommon::end_data_table_row();
 4485:     }
 4486:     $studentTable.=&Apache::loncommon::end_data_table();
 4487:     return $studentTable;
 4488: }
 4489: 
 4490: sub updateGradeByPage {
 4491:     my ($request) = shift;
 4492: 
 4493:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4494:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4495:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4496:     my $pageTitle = $env{'form.page'};
 4497:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4498:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4499:     my $usec=$classlist->{$env{'form.student'}}[5];
 4500:     if (!&canmodify($usec)) {
 4501: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4502: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4503: 	return;
 4504:     }
 4505:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4506:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4507: 	'</h3>'."\n";
 4508: 
 4509:     $request->print($result);
 4510: 
 4511:     my $navmap = Apache::lonnavmaps::navmap->new();
 4512:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4513:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4514:     if (!$map) {
 4515: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4516: 	my ($symb)=&get_symb($request);
 4517: 	$request->print(&show_grading_menu_form($symb));
 4518: 	return; 
 4519:     }
 4520:     my $iterator = $navmap->getIterator($map->map_start(),
 4521: 					$map->map_finish());
 4522: 
 4523:     my $studentTable=
 4524: 	&Apache::loncommon::start_data_table().
 4525: 	&Apache::loncommon::start_data_table_header_row().
 4526: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4527: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4528: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4529: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4530: 	&Apache::loncommon::end_data_table_header_row();
 4531: 
 4532:     $iterator->next(); # skip the first BEGIN_MAP
 4533:     my $curRes = $iterator->next(); # for "current resource"
 4534:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4535:     while ($depth > 0) {
 4536:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4537:         if($curRes == $iterator->END_MAP) { $depth--; }
 4538: 
 4539:         if (ref($curRes) && $curRes->is_problem()) {
 4540: 	    my $parts = $curRes->parts();
 4541:             my $title = $curRes->compTitle();
 4542: 	    my $symbx = $curRes->symb();
 4543: 	    $studentTable.=
 4544: 		&Apache::loncommon::start_data_table_row().
 4545: 		'<td align="center" valign="top" >'.$prob.
 4546: 		(scalar(@{$parts}) == 1 ? '' 
 4547:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4548: 		.')').'</td>';
 4549: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4550: 
 4551: 	    my %newrecord=();
 4552: 	    my @displayPts=();
 4553:             my %aggregate = ();
 4554:             my $aggregateflag = 0;
 4555: 	    foreach my $partid (@{$parts}) {
 4556: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4557: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4558: 
 4559: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4560: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4561: 		my $partial = $newpts/$wgt;
 4562: 		my $score;
 4563: 		if ($partial > 0) {
 4564: 		    $score = 'correct_by_override';
 4565: 		} elsif ($newpts ne '') { #empty is taken as 0
 4566: 		    $score = 'incorrect_by_override';
 4567: 		}
 4568: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4569: 		if ($dropMenu eq 'excused') {
 4570: 		    $partial = '';
 4571: 		    $score = 'excused';
 4572: 		} elsif ($dropMenu eq 'reset status'
 4573: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4574: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4575: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4576: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4577: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4578: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4579: 		    $changeflag++;
 4580: 		    $newpts = '';
 4581:                     
 4582:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4583:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4584:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4585:                     if ($aggtries > 0) {
 4586:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4587:                         $aggregateflag = 1;
 4588:                     }
 4589: 		}
 4590: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4591: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4592: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4593: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4594: 		    '&nbsp;<br />';
 4595: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4596: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4597: 		    '&nbsp;<br />';
 4598: 		$question++;
 4599: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4600: 
 4601: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4602: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4603: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4604: 		    if (scalar(keys(%newrecord)) > 0);
 4605: 
 4606: 		$changeflag++;
 4607: 	    }
 4608: 	    if (scalar(keys(%newrecord)) > 0) {
 4609: 		my %record = 
 4610: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4611: 					     $udom,$uname);
 4612: 
 4613: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4614: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4615: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4616: 		    $newrecord{'resource.CODE'} = '';
 4617: 		}
 4618: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4619: 					$udom,$uname);
 4620: 		%record = &Apache::lonnet::restore($symbx,
 4621: 						   $env{'request.course.id'},
 4622: 						   $udom,$uname);
 4623: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4624: 					     $cdom,$cnum,$udom,$uname);
 4625: 	    }
 4626: 	    
 4627:             if ($aggregateflag) {
 4628:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4629:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4630:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4631:             }
 4632: 
 4633: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4634: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4635: 		&Apache::loncommon::end_data_table_row();
 4636: 
 4637: 	    $prob++;
 4638: 	}
 4639:         $curRes = $iterator->next();
 4640:     }
 4641: 
 4642:     $studentTable.=&Apache::loncommon::end_data_table();
 4643:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4644:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4645: 		  &mt('The scores were changed for [quant,_1,problem].',
 4646: 		  $changeflag));
 4647:     $request->print($grademsg.$studentTable);
 4648: 
 4649:     return '';
 4650: }
 4651: 
 4652: #-------- end of section for handling grading by page/sequence ---------
 4653: #
 4654: #-------------------------------------------------------------------
 4655: 
 4656: #--------------------Scantron Grading-----------------------------------
 4657: #
 4658: #------ start of section for handling grading by page/sequence ---------
 4659: 
 4660: =pod
 4661: 
 4662: =head1 Bubble sheet grading routines
 4663: 
 4664:   For this documentation:
 4665: 
 4666:    'scanline' refers to the full line of characters
 4667:    from the file that we are parsing that represents one entire sheet
 4668: 
 4669:    'bubble line' refers to the data
 4670:    representing the line of bubbles that are on the physical bubble sheet
 4671: 
 4672: 
 4673: The overall process is that a scanned in bubble sheet data is uploaded
 4674: into a course. When a user wants to grade, they select a
 4675: sequence/folder of resources, a file of bubble sheet info, and pick
 4676: one of the predefined configurations for what each scanline looks
 4677: like.
 4678: 
 4679: Next each scanline is checked for any errors of either 'missing
 4680: bubbles' (it's an error because it may have been mis-scanned
 4681: because too light bubbling), 'double bubble' (each bubble line should
 4682: have no more that one letter picked), invalid or duplicated CODE,
 4683: invalid student/employee ID
 4684: 
 4685: If the CODE option is used that determines the randomization of the
 4686: homework problems, either way the student/employee ID is looked up into a
 4687: username:domain.
 4688: 
 4689: During the validation phase the instructor can choose to skip scanlines. 
 4690: 
 4691: After the validation phase, there are now 3 bubble sheet files
 4692: 
 4693:   scantron_original_filename (unmodified original file)
 4694:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4695:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4696: 
 4697: Also there is a separate hash nohist_scantrondata that contains extra
 4698: correction information that isn't representable in the bubble sheet
 4699: file (see &scantron_getfile() for more information)
 4700: 
 4701: After all scanlines are either valid, marked as valid or skipped, then
 4702: foreach line foreach problem in the picked sequence, an ssi request is
 4703: made that simulates a user submitting their selected letter(s) against
 4704: the homework problem.
 4705: 
 4706: =over 4
 4707: 
 4708: 
 4709: 
 4710: =item defaultFormData
 4711: 
 4712:   Returns html hidden inputs used to hold context/default values.
 4713: 
 4714:  Arguments:
 4715:   $symb - $symb of the current resource 
 4716: 
 4717: =cut
 4718: 
 4719: sub defaultFormData {
 4720:     my ($symb)=@_;
 4721:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4722:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4723:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4724: }
 4725: 
 4726: 
 4727: =pod 
 4728: 
 4729: =item getSequenceDropDown
 4730: 
 4731:    Return html dropdown of possible sequences to grade
 4732:  
 4733:  Arguments:
 4734:    $symb - $symb of the current resource 
 4735: 
 4736: =cut
 4737: 
 4738: sub getSequenceDropDown {
 4739:     my ($symb)=@_;
 4740:     my $result='<select name="selectpage">'."\n";
 4741:     my ($titles,$symbx) = &getSymbMap();
 4742:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4743:     my $ctr=0;
 4744:     foreach (@$titles) {
 4745: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4746: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4747: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4748: 	    '>'.$showtitle.'</option>'."\n";
 4749: 	$ctr++;
 4750:     }
 4751:     $result.= '</select>';
 4752:     return $result;
 4753: }
 4754: 
 4755: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4756:                                    # key is zero-based index - 0, 1, 2 ...
 4757: 
 4758: my %first_bubble_line;             # First bubble line no. for each bubble.
 4759: 
 4760: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4761:                                    # matchresponse or rankresponse, where 
 4762:                                    # an individual response can have multiple 
 4763:                                    # lines
 4764: 
 4765: my %responsetype_per_response;     # responsetype for each response
 4766: 
 4767: # Save and restore the bubble lines array to the form env.
 4768: 
 4769: 
 4770: sub save_bubble_lines {
 4771:     foreach my $line (keys(%bubble_lines_per_response)) {
 4772: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4773: 	$env{"form.scantron.first_bubble_line.$line"} =
 4774: 	    $first_bubble_line{$line};
 4775:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4776:             $subdivided_bubble_lines{$line};
 4777:         $env{"form.scantron.responsetype.$line"} =
 4778:             $responsetype_per_response{$line};
 4779:     }
 4780: }
 4781: 
 4782: 
 4783: sub restore_bubble_lines {
 4784:     my $line = 0;
 4785:     %bubble_lines_per_response = ();
 4786:     while ($env{"form.scantron.bubblelines.$line"}) {
 4787: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4788: 	$bubble_lines_per_response{$line} = $value;
 4789: 	$first_bubble_line{$line}  =
 4790: 	    $env{"form.scantron.first_bubble_line.$line"};
 4791:         $subdivided_bubble_lines{$line} =
 4792:             $env{"form.scantron.sub_bubblelines.$line"};
 4793:         $responsetype_per_response{$line} =
 4794:             $env{"form.scantron.responsetype.$line"};
 4795: 	$line++;
 4796:     }
 4797: }
 4798: 
 4799: #  Given the parsed scanline, get the response for 
 4800: #  'answer' number n:
 4801: 
 4802: sub get_response_bubbles {
 4803:     my ($parsed_line, $response)  = @_;
 4804: 
 4805:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4806:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4807:     
 4808:     my $selected = "";
 4809: 
 4810:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4811: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4812: 	$bubble_line++;
 4813:     }
 4814:     return $selected;
 4815: }
 4816: 
 4817: =pod 
 4818: 
 4819: =item scantron_filenames
 4820: 
 4821:    Returns a list of the scantron files in the current course 
 4822: 
 4823: =cut
 4824: 
 4825: sub scantron_filenames {
 4826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4827:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4828:     my $getpropath = 1;
 4829:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4830:                                        $getpropath);
 4831:     my @possiblenames;
 4832:     foreach my $filename (sort(@files)) {
 4833: 	($filename)=split(/&/,$filename);
 4834: 	if ($filename!~/^scantron_orig_/) { next ; }
 4835: 	$filename=~s/^scantron_orig_//;
 4836: 	push(@possiblenames,$filename);
 4837:     }
 4838:     return @possiblenames;
 4839: }
 4840: 
 4841: =pod 
 4842: 
 4843: =item scantron_uploads
 4844: 
 4845:    Returns  html drop-down list of scantron files in current course.
 4846: 
 4847:  Arguments:
 4848:    $file2grade - filename to set as selected in the dropdown
 4849: 
 4850: =cut
 4851: 
 4852: sub scantron_uploads {
 4853:     my ($file2grade) = @_;
 4854:     my $result=	'<select name="scantron_selectfile">';
 4855:     $result.="<option></option>";
 4856:     foreach my $filename (sort(&scantron_filenames())) {
 4857: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4858:     }
 4859:     $result.="</select>";
 4860:     return $result;
 4861: }
 4862: 
 4863: =pod 
 4864: 
 4865: =item scantron_scantab
 4866: 
 4867:   Returns html drop down of the scantron formats in the scantronformat.tab
 4868:   file.
 4869: 
 4870: =cut
 4871: 
 4872: sub scantron_scantab {
 4873:     my $result='<select name="scantron_format">'."\n";
 4874:     $result.='<option></option>'."\n";
 4875:     my @lines = &get_scantronformat_file();
 4876:     if (@lines > 0) {
 4877:         foreach my $line (@lines) {
 4878:             next if (($line =~ /^\#/) || ($line eq ''));
 4879: 	    my ($name,$descrip)=split(/:/,$line);
 4880: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4881:         }
 4882:     }
 4883:     $result.='</select>'."\n";
 4884:     return $result;
 4885: }
 4886: 
 4887: =pod
 4888: 
 4889: =item get_scantronformat_file
 4890: 
 4891:   Returns an array containing lines from the scantron format file for
 4892:   the domain of the course.
 4893: 
 4894:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4895:   lines are from this file.
 4896: 
 4897:   Otherwise, if a default.tab has been published in RES space by the 
 4898:   domainconfig user, lines are from this file.
 4899: 
 4900:   Otherwise, fall back to getting lines from the legacy file on the
 4901:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4902: 
 4903: =cut
 4904: 
 4905: sub get_scantronformat_file {
 4906:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4907:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4908:     my $gottab = 0;
 4909:     my @lines;
 4910:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4911:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4912:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4913:             if ($formatfile ne '-1') {
 4914:                 @lines = split("\n",$formatfile,-1);
 4915:                 $gottab = 1;
 4916:             }
 4917:         }
 4918:     }
 4919:     if (!$gottab) {
 4920:         my $confname = $cdom.'-domainconfig';
 4921:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4922:         my $formatfile =  &Apache::lonnet::getfile($default);
 4923:         if ($formatfile ne '-1') {
 4924:             @lines = split("\n",$formatfile,-1);
 4925:             $gottab = 1;
 4926:         }
 4927:     }
 4928:     if (!$gottab) {
 4929:         my @domains = &Apache::lonnet::current_machine_domains();
 4930:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4931:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4932:             @lines = <$fh>;
 4933:             close($fh);
 4934:         } else {
 4935:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4936:             @lines = <$fh>;
 4937:             close($fh);
 4938:         }
 4939:     }
 4940:     return @lines;
 4941: }
 4942: 
 4943: =pod 
 4944: 
 4945: =item scantron_CODElist
 4946: 
 4947:   Returns html drop down of the saved CODE lists from current course,
 4948:   generated from earlier printings.
 4949: 
 4950: =cut
 4951: 
 4952: sub scantron_CODElist {
 4953:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4954:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4955:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4956:     my $namechoice='<option></option>';
 4957:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4958: 	if ($name =~ /^error: 2 /) { next; }
 4959: 	if ($name =~ /^type\0/) { next; }
 4960: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4961:     }
 4962:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4963:     return $namechoice;
 4964: }
 4965: 
 4966: =pod 
 4967: 
 4968: =item scantron_CODEunique
 4969: 
 4970:   Returns the html for "Each CODE to be used once" radio.
 4971: 
 4972: =cut
 4973: 
 4974: sub scantron_CODEunique {
 4975:     my $result='<span class="LC_nobreak">
 4976:                  <label><input type="radio" name="scantron_CODEunique"
 4977:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4978:                 </span>
 4979:                 <span class="LC_nobreak">
 4980:                  <label><input type="radio" name="scantron_CODEunique"
 4981:                         value="no" />'.&mt('No').' </label>
 4982:                 </span>';
 4983:     return $result;
 4984: }
 4985: 
 4986: =pod 
 4987: 
 4988: =item scantron_selectphase
 4989: 
 4990:   Generates the initial screen to start the bubble sheet process.
 4991:   Allows for - starting a grading run.
 4992:              - downloading existing scan data (original, corrected
 4993:                                                 or skipped info)
 4994: 
 4995:              - uploading new scan data
 4996: 
 4997:  Arguments:
 4998:   $r          - The Apache request object
 4999:   $file2grade - name of the file that contain the scanned data to score
 5000: 
 5001: =cut
 5002: 
 5003: sub scantron_selectphase {
 5004:     my ($r,$file2grade) = @_;
 5005:     my ($symb)=&get_symb($r);
 5006:     if (!$symb) {return '';}
 5007:     my $sequence_selector=&getSequenceDropDown($symb);
 5008:     my $default_form_data=&defaultFormData($symb);
 5009:     my $grading_menu_button=&show_grading_menu_form($symb);
 5010:     my $file_selector=&scantron_uploads($file2grade);
 5011:     my $format_selector=&scantron_scantab();
 5012:     my $CODE_selector=&scantron_CODElist();
 5013:     my $CODE_unique=&scantron_CODEunique();
 5014:     my $result;
 5015: 
 5016:     $ssi_error = 0;
 5017: 
 5018:     # Chunk of form to prompt for a file to grade and how:
 5019: 
 5020:     $result.= '
 5021:     <br />
 5022:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5023:     <input type="hidden" name="command" value="scantron_warning" />
 5024:     '.$default_form_data.'
 5025:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5026:        '.&Apache::loncommon::start_data_table_header_row().'
 5027:             <th colspan="2">
 5028:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5029:             </th>
 5030:        '.&Apache::loncommon::end_data_table_header_row().'
 5031:        '.&Apache::loncommon::start_data_table_row().'
 5032:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5033:        '.&Apache::loncommon::end_data_table_row().'
 5034:        '.&Apache::loncommon::start_data_table_row().'
 5035:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5036:        '.&Apache::loncommon::end_data_table_row().'
 5037:        '.&Apache::loncommon::start_data_table_row().'
 5038:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5039:        '.&Apache::loncommon::end_data_table_row().'
 5040:        '.&Apache::loncommon::start_data_table_row().'
 5041:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5042:        '.&Apache::loncommon::end_data_table_row().'
 5043:        '.&Apache::loncommon::start_data_table_row().'
 5044:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5045:        '.&Apache::loncommon::end_data_table_row().'
 5046:        '.&Apache::loncommon::start_data_table_row().'
 5047: 	    <td> '.&mt('Options:').' </td>
 5048:             <td>
 5049: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5050:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5051:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5052: 	    </td>
 5053:        '.&Apache::loncommon::end_data_table_row().'
 5054:        '.&Apache::loncommon::start_data_table_row().'
 5055:             <td colspan="2">
 5056:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5057:             </td>
 5058:        '.&Apache::loncommon::end_data_table_row().'
 5059:     '.&Apache::loncommon::end_data_table().'
 5060:     </form>
 5061: ';
 5062:    
 5063:     $r->print($result);
 5064: 
 5065:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5066:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5067: 
 5068: 	# Chunk of form to prompt for a scantron file upload.
 5069: 
 5070:         $r->print('
 5071:     <br />
 5072:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5073:        '.&Apache::loncommon::start_data_table_header_row().'
 5074:             <th>
 5075:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5076:             </th>
 5077:        '.&Apache::loncommon::end_data_table_header_row().'
 5078:        '.&Apache::loncommon::start_data_table_row().'
 5079:             <td>
 5080: ');
 5081:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5082:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5083:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5084:     $r->print('
 5085:               <script type="text/javascript" language="javascript">
 5086:     function checkUpload(formname) {
 5087: 	if (formname.upfile.value == "") {
 5088: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5089: 	    return false;
 5090: 	}
 5091: 	formname.submit();
 5092:     }
 5093:               </script>
 5094: 
 5095:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5096:                 '.$default_form_data.'
 5097:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5098:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5099:                 <input name="command" value="scantronupload_save" type="hidden" />
 5100:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5101:                 <br />
 5102:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5103:               </form>
 5104: ');
 5105: 
 5106:         $r->print('
 5107:             </td>
 5108:        '.&Apache::loncommon::end_data_table_row().'
 5109:        '.&Apache::loncommon::end_data_table().'
 5110: ');
 5111:     }
 5112: 
 5113:     # Chunk of the form that prompts to view a scoring office file,
 5114:     # corrected file, skipped records in a file.
 5115: 
 5116:     $r->print('
 5117:    <br />
 5118:    <form action="/adm/grades" name="scantron_download">
 5119:      '.$default_form_data.'
 5120:      <input type="hidden" name="command" value="scantron_download" />
 5121:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5122:        '.&Apache::loncommon::start_data_table_header_row().'
 5123:               <th>
 5124:                 &nbsp;'.&mt('Download a scoring office file').'
 5125:               </th>
 5126:        '.&Apache::loncommon::end_data_table_header_row().'
 5127:        '.&Apache::loncommon::start_data_table_row().'
 5128:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5129:                 <br />
 5130:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5131:        '.&Apache::loncommon::end_data_table_row().'
 5132:      '.&Apache::loncommon::end_data_table().'
 5133:    </form>
 5134:    <br />
 5135: ');
 5136: 
 5137:     &Apache::lonpickcode::code_list($r,2);
 5138: 
 5139:     $r->print('<br /><form method="post" name="checkscantron">'.
 5140:              $default_form_data."\n".
 5141:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5142:              &Apache::loncommon::start_data_table_header_row()."\n".
 5143:              '<th colspan="2">
 5144:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5145:              '</th>'."\n".
 5146:               &Apache::loncommon::end_data_table_header_row()."\n".
 5147:               &Apache::loncommon::start_data_table_row()."\n".
 5148:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5149:               '<td> '.$sequence_selector.' </td>'.
 5150:               &Apache::loncommon::end_data_table_row()."\n".
 5151:               &Apache::loncommon::start_data_table_row()."\n".
 5152:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5153:               '<td> '.$file_selector.' </td>'."\n".
 5154:               &Apache::loncommon::end_data_table_row()."\n".
 5155:               &Apache::loncommon::start_data_table_row()."\n".
 5156:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5157:               '<td> '.$format_selector.' </td>'."\n".
 5158:               &Apache::loncommon::end_data_table_row()."\n".
 5159:               &Apache::loncommon::start_data_table_row()."\n".
 5160:               '<td colspan="2">'."\n".
 5161:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5162:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5163:               '</td>'."\n".
 5164:               &Apache::loncommon::end_data_table_row()."\n".
 5165:               &Apache::loncommon::end_data_table()."\n".
 5166:               '</form><br />');
 5167:     $r->print($grading_menu_button);
 5168:     return;
 5169: }
 5170: 
 5171: =pod
 5172: 
 5173: =item get_scantron_config
 5174: 
 5175:    Parse and return the scantron configuration line selected as a
 5176:    hash of configuration file fields.
 5177: 
 5178:  Arguments:
 5179:     which - the name of the configuration to parse from the file.
 5180: 
 5181: 
 5182:  Returns:
 5183:             If the named configuration is not in the file, an empty
 5184:             hash is returned.
 5185:     a hash with the fields
 5186:       name         - internal name for the this configuration setup
 5187:       description  - text to display to operator that describes this config
 5188:       CODElocation - if 0 or the string 'none'
 5189:                           - no CODE exists for this config
 5190:                      if -1 || the string 'letter'
 5191:                           - a CODE exists for this config and is
 5192:                             a string of letters
 5193:                      Unsupported value (but planned for future support)
 5194:                           if a positive integer
 5195:                                - The CODE exists as the first n items from
 5196:                                  the question section of the form
 5197:                           if the string 'number'
 5198:                                - The CODE exists for this config and is
 5199:                                  a string of numbers
 5200:       CODEstart   - (only matter if a CODE exists) column in the line where
 5201:                      the CODE starts
 5202:       CODElength  - length of the CODE
 5203:       IDstart     - column where the student/employee ID number starts
 5204:       IDlength    - length of the student/employee ID info
 5205:       Qstart      - column where the information from the bubbled
 5206:                     'questions' start
 5207:       Qlength     - number of columns comprising a single bubble line from
 5208:                     the sheet. (usually either 1 or 10)
 5209:       Qon         - either a single character representing the character used
 5210:                     to signal a bubble was chosen in the positional setup, or
 5211:                     the string 'letter' if the letter of the chosen bubble is
 5212:                     in the final, or 'number' if a number representing the
 5213:                     chosen bubble is in the file (1->A 0->J)
 5214:       Qoff        - the character used to represent that a bubble was
 5215:                     left blank
 5216:       PaperID     - if the scanning process generates a unique number for each
 5217:                     sheet scanned the column that this ID number starts in
 5218:       PaperIDlength - number of columns that comprise the unique ID number
 5219:                       for the sheet of paper
 5220:       FirstName   - column that the first name starts in
 5221:       FirstNameLength - number of columns that the first name spans
 5222:  
 5223:       LastName    - column that the last name starts in
 5224:       LastNameLength - number of columns that the last name spans
 5225: 
 5226: =cut
 5227: 
 5228: sub get_scantron_config {
 5229:     my ($which) = @_;
 5230:     my @lines = &get_scantronformat_file();
 5231:     my %config;
 5232:     #FIXME probably should move to XML it has already gotten a bit much now
 5233:     foreach my $line (@lines) {
 5234: 	my ($name,$descrip)=split(/:/,$line);
 5235: 	if ($name ne $which ) { next; }
 5236: 	chomp($line);
 5237: 	my @config=split(/:/,$line);
 5238: 	$config{'name'}=$config[0];
 5239: 	$config{'description'}=$config[1];
 5240: 	$config{'CODElocation'}=$config[2];
 5241: 	$config{'CODEstart'}=$config[3];
 5242: 	$config{'CODElength'}=$config[4];
 5243: 	$config{'IDstart'}=$config[5];
 5244: 	$config{'IDlength'}=$config[6];
 5245: 	$config{'Qstart'}=$config[7];
 5246:  	$config{'Qlength'}=$config[8];
 5247: 	$config{'Qoff'}=$config[9];
 5248: 	$config{'Qon'}=$config[10];
 5249: 	$config{'PaperID'}=$config[11];
 5250: 	$config{'PaperIDlength'}=$config[12];
 5251: 	$config{'FirstName'}=$config[13];
 5252: 	$config{'FirstNamelength'}=$config[14];
 5253: 	$config{'LastName'}=$config[15];
 5254: 	$config{'LastNamelength'}=$config[16];
 5255: 	last;
 5256:     }
 5257:     return %config;
 5258: }
 5259: 
 5260: =pod 
 5261: 
 5262: =item username_to_idmap
 5263: 
 5264:     creates a hash keyed by student/employee ID with values of the corresponding
 5265:     student username:domain.
 5266: 
 5267:   Arguments:
 5268: 
 5269:     $classlist - reference to the class list hash. This is a hash
 5270:                  keyed by student name:domain  whose elements are references
 5271:                  to arrays containing various chunks of information
 5272:                  about the student. (See loncoursedata for more info).
 5273: 
 5274:   Returns
 5275:     %idmap - the constructed hash
 5276: 
 5277: =cut
 5278: 
 5279: sub username_to_idmap {
 5280:     my ($classlist)= @_;
 5281:     my %idmap;
 5282:     foreach my $student (keys(%$classlist)) {
 5283: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5284: 	    $student;
 5285:     }
 5286:     return %idmap;
 5287: }
 5288: 
 5289: =pod
 5290: 
 5291: =item scantron_fixup_scanline
 5292: 
 5293:    Process a requested correction to a scanline.
 5294: 
 5295:   Arguments:
 5296:     $scantron_config   - hash from &get_scantron_config()
 5297:     $scan_data         - hash of correction information 
 5298:                           (see &scantron_getfile())
 5299:     $line              - existing scanline
 5300:     $whichline         - line number of the passed in scanline
 5301:     $field             - type of change to process 
 5302:                          (either 
 5303:                           'ID'     -> correct the student/employee ID number
 5304:                           'CODE'   -> correct the CODE
 5305:                           'answer' -> fixup the submitted answers)
 5306:     
 5307:    $args               - hash of additional info,
 5308:                           - 'ID' 
 5309:                                'newid' -> studentID to use in replacement
 5310:                                           of existing one
 5311:                           - 'CODE' 
 5312:                                'CODE_ignore_dup' - set to true if duplicates
 5313:                                                    should be ignored.
 5314: 	                       'CODE' - is new code or 'use_unfound'
 5315:                                         if the existing unfound code should
 5316:                                         be used as is
 5317:                           - 'answer'
 5318:                                'response' - new answer or 'none' if blank
 5319:                                'question' - the bubble line to change
 5320:                                'questionnum' - the question identifier,
 5321:                                                may include subquestion. 
 5322: 
 5323:   Returns:
 5324:     $line - the modified scanline
 5325: 
 5326:   Side effects: 
 5327:     $scan_data - may be updated
 5328: 
 5329: =cut
 5330: 
 5331: 
 5332: sub scantron_fixup_scanline {
 5333:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5334:     if ($field eq 'ID') {
 5335: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5336: 	    return ($line,1,'New value too large');
 5337: 	}
 5338: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5339: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5340: 				     $args->{'newid'});
 5341: 	}
 5342: 	substr($line,$$scantron_config{'IDstart'}-1,
 5343: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5344: 	if ($args->{'newid'}=~/^\s*$/) {
 5345: 	    &scan_data($scan_data,"$whichline.user",
 5346: 		       $args->{'username'}.':'.$args->{'domain'});
 5347: 	}
 5348:     } elsif ($field eq 'CODE') {
 5349: 	if ($args->{'CODE_ignore_dup'}) {
 5350: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5351: 	}
 5352: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5353: 	if ($args->{'CODE'} ne 'use_unfound') {
 5354: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5355: 		return ($line,1,'New CODE value too large');
 5356: 	    }
 5357: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5358: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5359: 	    }
 5360: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5361: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5362: 	}
 5363:     } elsif ($field eq 'answer') {
 5364: 	my $length=$scantron_config->{'Qlength'};
 5365: 	my $off=$scantron_config->{'Qoff'};
 5366: 	my $on=$scantron_config->{'Qon'};
 5367: 	my $answer=${off}x$length;
 5368: 	if ($args->{'response'} eq 'none') {
 5369: 	    &scan_data($scan_data,
 5370: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5371: 	} else {
 5372: 	    if ($on eq 'letter') {
 5373: 		my @alphabet=('A'..'Z');
 5374: 		$answer=$alphabet[$args->{'response'}];
 5375: 	    } elsif ($on eq 'number') {
 5376: 		$answer=$args->{'response'}+1;
 5377: 		if ($answer == 10) { $answer = '0'; }
 5378: 	    } else {
 5379: 		substr($answer,$args->{'response'},1)=$on;
 5380: 	    }
 5381: 	    &scan_data($scan_data,
 5382: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5383: 	}
 5384: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5385: 	substr($line,$where-1,$length)=$answer;
 5386:     }
 5387:     return $line;
 5388: }
 5389: 
 5390: =pod
 5391: 
 5392: =item scan_data
 5393: 
 5394:     Edit or look up  an item in the scan_data hash.
 5395: 
 5396:   Arguments:
 5397:     $scan_data  - The hash (see scantron_getfile)
 5398:     $key        - shorthand of the key to edit (actual key is
 5399:                   scantronfilename_key).
 5400:     $data        - New value of the hash entry.
 5401:     $delete      - If true, the entry is removed from the hash.
 5402: 
 5403:   Returns:
 5404:     The new value of the hash table field (undefined if deleted).
 5405: 
 5406: =cut
 5407: 
 5408: 
 5409: sub scan_data {
 5410:     my ($scan_data,$key,$value,$delete)=@_;
 5411:     my $filename=$env{'form.scantron_selectfile'};
 5412:     if (defined($value)) {
 5413: 	$scan_data->{$filename.'_'.$key} = $value;
 5414:     }
 5415:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5416:     return $scan_data->{$filename.'_'.$key};
 5417: }
 5418: 
 5419: # ----- These first few routines are general use routines.----
 5420: 
 5421: # Return the number of occurences of a pattern in a string.
 5422: 
 5423: sub occurence_count {
 5424:     my ($string, $pattern) = @_;
 5425: 
 5426:     my @matches = ($string =~ /$pattern/g);
 5427: 
 5428:     return scalar(@matches);
 5429: }
 5430: 
 5431: 
 5432: # Take a string known to have digits and convert all the
 5433: # digits into letters in the range J,A..I.
 5434: 
 5435: sub digits_to_letters {
 5436:     my ($input) = @_;
 5437: 
 5438:     my @alphabet = ('J', 'A'..'I');
 5439: 
 5440:     my @input    = split(//, $input);
 5441:     my $output ='';
 5442:     for (my $i = 0; $i < scalar(@input); $i++) {
 5443: 	if ($input[$i] =~ /\d/) {
 5444: 	    $output .= $alphabet[$input[$i]];
 5445: 	} else {
 5446: 	    $output .= $input[$i];
 5447: 	}
 5448:     }
 5449:     return $output;
 5450: }
 5451: 
 5452: =pod 
 5453: 
 5454: =item scantron_parse_scanline
 5455: 
 5456:   Decodes a scanline from the selected scantron file
 5457: 
 5458:  Arguments:
 5459:     line             - The text of the scantron file line to process
 5460:     whichline        - Line number
 5461:     scantron_config  - Hash describing the format of the scantron lines.
 5462:     scan_data        - Hash of extra information about the scanline
 5463:                        (see scantron_getfile for more information)
 5464:     just_header      - True if should not process question answers but only
 5465:                        the stuff to the left of the answers.
 5466:  Returns:
 5467:    Hash containing the result of parsing the scanline
 5468: 
 5469:    Keys are all proceeded by the string 'scantron.'
 5470: 
 5471:        CODE    - the CODE in use for this scanline
 5472:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5473:                  by the operator
 5474:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5475:                             CODEs were selected, but the usage has been
 5476:                             forced by the operator
 5477:        ID  - student/employee ID
 5478:        PaperID - if used, the ID number printed on the sheet when the 
 5479:                  paper was scanned
 5480:        FirstName - first name from the sheet
 5481:        LastName  - last name from the sheet
 5482: 
 5483:      if just_header was not true these key may also exist
 5484: 
 5485:        missingerror - a list of bubble ranges that are considered to be answers
 5486:                       to a single question that don't have any bubbles filled in.
 5487:                       Of the form questionnumber:firstbubblenumber:count.
 5488:        doubleerror  - a list of bubble ranges that are considered to be answers
 5489:                       to a single question that have more than one bubble filled in.
 5490:                       Of the form questionnumber::firstbubblenumber:count
 5491:    
 5492:                 In the above, count is the number of bubble responses in the
 5493:                 input line needed to represent the possible answers to the question.
 5494:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5495:                 per line would have count = 2.
 5496: 
 5497:        maxquest     - the number of the last bubble line that was parsed
 5498: 
 5499:        (<number> starts at 1)
 5500:        <number>.answer - zero or more letters representing the selected
 5501:                          letters from the scanline for the bubble line 
 5502:                          <number>.
 5503:                          if blank there was either no bubble or there where
 5504:                          multiple bubbles, (consult the keys missingerror and
 5505:                          doubleerror if this is an error condition)
 5506: 
 5507: =cut
 5508: 
 5509: sub scantron_parse_scanline {
 5510:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5511: 
 5512:     my %record;
 5513:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5514:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5515:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5516:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5517: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5518: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5519: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5520: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5521: 	    $record{'scantron.CODE'}=substr($data,
 5522: 					    $$scantron_config{'CODEstart'}-1,
 5523: 					    $$scantron_config{'CODElength'});
 5524: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5525: 		$record{'scantron.useCODE'}=1;
 5526: 	    }
 5527: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5528: 		$record{'scantron.CODE_ignore_dup'}=1;
 5529: 	    }
 5530: 	} else {
 5531: 	    #FIXME interpret first N questions
 5532: 	}
 5533:     }
 5534:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5535: 				  $$scantron_config{'IDlength'});
 5536:     $record{'scantron.PaperID'}=
 5537: 	substr($data,$$scantron_config{'PaperID'}-1,
 5538: 	       $$scantron_config{'PaperIDlength'});
 5539:     $record{'scantron.FirstName'}=
 5540: 	substr($data,$$scantron_config{'FirstName'}-1,
 5541: 	       $$scantron_config{'FirstNamelength'});
 5542:     $record{'scantron.LastName'}=
 5543: 	substr($data,$$scantron_config{'LastName'}-1,
 5544: 	       $$scantron_config{'LastNamelength'});
 5545:     if ($just_header) { return \%record; }
 5546: 
 5547:     my @alphabet=('A'..'Z');
 5548:     my $questnum=0;
 5549:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5550: 
 5551:     chomp($questions);		# Get rid of any trailing \n.
 5552:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5553:     while (length($questions)) {
 5554: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5555:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5556:                              || 1;
 5557:         $questnum++;
 5558:         my $quest_id = $questnum;
 5559:         my $currentquest = substr($questions,0,$answer_length);
 5560:         $questions       = substr($questions,$answer_length);
 5561:         if (length($currentquest) < $answer_length) { next; }
 5562: 
 5563:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5564:             my $subquestnum = 1;
 5565:             my $subquestions = $currentquest;
 5566:             my @subanswers_needed = 
 5567:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5568:             foreach my $subans (@subanswers_needed) {
 5569:                 my $subans_length =
 5570:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5571:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5572:                 $subquestions   = substr($subquestions,$subans_length);
 5573:                 $quest_id = "$questnum.$subquestnum";
 5574:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5575:                     ($$scantron_config{'Qon'} eq 'number')) {
 5576:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5577:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5578:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5579:                 } else {
 5580:                     $ansnum = &scantron_validator_positional($ansnum,
 5581:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5582:                 }
 5583:                 $subquestnum ++;
 5584:             }
 5585:         } else {
 5586:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5587:                 ($$scantron_config{'Qon'} eq 'number')) {
 5588:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5589:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5590:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5591:             } else {
 5592:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5593:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5594:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5595:             }
 5596:         }
 5597:     }
 5598:     $record{'scantron.maxquest'}=$questnum;
 5599:     return \%record;
 5600: }
 5601: 
 5602: sub scantron_validator_lettnum {
 5603:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5604:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5605: 
 5606:     # Qon 'letter' implies for each slot in currquest we have:
 5607:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5608:     #    about anything else (esp. a value of Qoff) for missing
 5609:     #    bubbles.
 5610:     #
 5611:     # Qon 'number' implies each slot gives a digit that indexes the
 5612:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5613:     #    and * or ? for double bubbles on a single line.
 5614:     #
 5615: 
 5616:     my $matchon;
 5617:     if ($$scantron_config{'Qon'} eq 'letter') {
 5618:         $matchon = '[A-Z]';
 5619:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5620:         $matchon = '\d';
 5621:     }
 5622:     my $occurrences = 0;
 5623:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5624:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5625:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5626:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5627:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5628:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5629:         my @singlelines = split('',$currquest);
 5630:         foreach my $entry (@singlelines) {
 5631:             $occurrences = &occurence_count($entry,$matchon);
 5632:             if ($occurrences > 1) {
 5633:                 last;
 5634:             }
 5635:         } 
 5636:     } else {
 5637:         $occurrences = &occurence_count($currquest,$matchon); 
 5638:     }
 5639:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5640:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5641:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5642:             my $bubble = substr($currquest,$ans,1);
 5643:             if ($bubble =~ /$matchon/ ) {
 5644:                 if ($$scantron_config{'Qon'} eq 'number') {
 5645:                     if ($bubble == 0) {
 5646:                         $bubble = 10; 
 5647:                     }
 5648:                     $record->{"scantron.$ansnum.answer"} = 
 5649:                         $alphabet->[$bubble-1];
 5650:                 } else {
 5651:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5652:                 }
 5653:             } else {
 5654:                 $record->{"scantron.$ansnum.answer"}='';
 5655:             }
 5656:             $ansnum++;
 5657:         }
 5658:     } elsif (!defined($currquest)
 5659:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5660:             || (&occurence_count($currquest,$matchon) == 0)) {
 5661:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5662:             $record->{"scantron.$ansnum.answer"}='';
 5663:             $ansnum++;
 5664:         }
 5665:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5666:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5667:         }
 5668:     } else {
 5669:         if ($$scantron_config{'Qon'} eq 'number') {
 5670:             $currquest = &digits_to_letters($currquest);            
 5671:         }
 5672:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5673:             my $bubble = substr($currquest,$ans,1);
 5674:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5675:             $ansnum++;
 5676:         }
 5677:     }
 5678:     return $ansnum;
 5679: }
 5680: 
 5681: sub scantron_validator_positional {
 5682:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5683:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5684: 
 5685:     # Otherwise there's a positional notation;
 5686:     # each bubble line requires Qlength items, and there are filled in
 5687:     # bubbles for each case where there 'Qon' characters.
 5688:     #
 5689: 
 5690:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5691: 
 5692:     # If the split only gives us one element.. the full length of the
 5693:     # answer string, no bubbles are filled in:
 5694: 
 5695:     if ($answers_needed eq '') {
 5696:         return;
 5697:     }
 5698: 
 5699:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5700:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5701:             $record->{"scantron.$ansnum.answer"}='';
 5702:             $ansnum++;
 5703:         }
 5704:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5705:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5706:         }
 5707:     } elsif (scalar(@array) == 2) {
 5708:         my $location = length($array[0]);
 5709:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5710:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5711:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5712:             if ($ans eq $line_num) {
 5713:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5714:             } else {
 5715:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5716:             }
 5717:             $ansnum++;
 5718:          }
 5719:     } else {
 5720:         #  If there's more than one instance of a bubble character
 5721:         #  That's a double bubble; with positional notation we can
 5722:         #  record all the bubbles filled in as well as the
 5723:         #  fact this response consists of multiple bubbles.
 5724:         #
 5725:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5726:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5727:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5728:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5729:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5730:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5731:             my $doubleerror = 0;
 5732:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5733:                    (!$doubleerror)) {
 5734:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5735:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5736:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5737:                if (length(@currarray) > 2) {
 5738:                    $doubleerror = 1;
 5739:                } 
 5740:             }
 5741:             if ($doubleerror) {
 5742:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5743:             }
 5744:         } else {
 5745:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5746:         }
 5747:         my $item = $ansnum;
 5748:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5749:             $record->{"scantron.$item.answer"} = '';
 5750:             $item ++;
 5751:         }
 5752: 
 5753:         my @ans=@array;
 5754:         my $i=0;
 5755:         my $increment = 0;
 5756:         while ($#ans) {
 5757:             $i+=length($ans[0]) + $increment;
 5758:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5759:             my $bubble = $i%$$scantron_config{'Qlength'};
 5760:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5761:             shift(@ans);
 5762:             $increment = 1;
 5763:         }
 5764:         $ansnum += $answers_needed;
 5765:     }
 5766:     return $ansnum;
 5767: }
 5768: 
 5769: =pod
 5770: 
 5771: =item scantron_add_delay
 5772: 
 5773:    Adds an error message that occurred during the grading phase to a
 5774:    queue of messages to be shown after grading pass is complete
 5775: 
 5776:  Arguments:
 5777:    $delayqueue  - arrary ref of hash ref of error messages
 5778:    $scanline    - the scanline that caused the error
 5779:    $errormesage - the error message
 5780:    $errorcode   - a numeric code for the error
 5781: 
 5782:  Side Effects:
 5783:    updates the $delayqueue to have a new hash ref of the error
 5784: 
 5785: =cut
 5786: 
 5787: sub scantron_add_delay {
 5788:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5789:     push(@$delayqueue,
 5790: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5791: 	  'ecode' => $errorcode }
 5792: 	 );
 5793: }
 5794: 
 5795: =pod
 5796: 
 5797: =item scantron_find_student
 5798: 
 5799:    Finds the username for the current scanline
 5800: 
 5801:   Arguments:
 5802:    $scantron_record - hash result from scantron_parse_scanline
 5803:    $scan_data       - hash of correction information 
 5804:                       (see &scantron_getfile() form more information)
 5805:    $idmap           - hash from &username_to_idmap()
 5806:    $line            - number of current scanline
 5807:  
 5808:   Returns:
 5809:    Either 'username:domain' or undef if unknown
 5810: 
 5811: =cut
 5812: 
 5813: sub scantron_find_student {
 5814:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5815:     my $scanID=$$scantron_record{'scantron.ID'};
 5816:     if ($scanID =~ /^\s*$/) {
 5817:  	return &scan_data($scan_data,"$line.user");
 5818:     }
 5819:     foreach my $id (keys(%$idmap)) {
 5820:  	if (lc($id) eq lc($scanID)) {
 5821:  	    return $$idmap{$id};
 5822:  	}
 5823:     }
 5824:     return undef;
 5825: }
 5826: 
 5827: =pod
 5828: 
 5829: =item scantron_filter
 5830: 
 5831:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5832:    hidden resources was selected
 5833: 
 5834: =cut
 5835: 
 5836: sub scantron_filter {
 5837:     my ($curres)=@_;
 5838: 
 5839:     if (ref($curres) && $curres->is_problem()) {
 5840: 	# if the user has asked to not have either hidden
 5841: 	# or 'randomout' controlled resources to be graded
 5842: 	# don't include them
 5843: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5844: 	    && $curres->randomout) {
 5845: 	    return 0;
 5846: 	}
 5847: 	return 1;
 5848:     }
 5849:     return 0;
 5850: }
 5851: 
 5852: =pod
 5853: 
 5854: =item scantron_process_corrections
 5855: 
 5856:    Gets correction information out of submitted form data and corrects
 5857:    the scanline
 5858: 
 5859: =cut
 5860: 
 5861: sub scantron_process_corrections {
 5862:     my ($r) = @_;
 5863:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5864:     my ($scanlines,$scan_data)=&scantron_getfile();
 5865:     my $classlist=&Apache::loncoursedata::get_classlist();
 5866:     my $which=$env{'form.scantron_line'};
 5867:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5868:     my ($skip,$err,$errmsg);
 5869:     if ($env{'form.scantron_skip_record'}) {
 5870: 	$skip=1;
 5871:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5872: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5873: 	    $env{'form.scantron_domain'};
 5874: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5875: 	($line,$err,$errmsg)=
 5876: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5877: 				     'ID',{'newid'=>$newid,
 5878: 				    'username'=>$env{'form.scantron_username'},
 5879: 				    'domain'=>$env{'form.scantron_domain'}});
 5880:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5881: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5882: 	my $newCODE;
 5883: 	my %args;
 5884: 	if      ($resolution eq 'use_unfound') {
 5885: 	    $newCODE='use_unfound';
 5886: 	} elsif ($resolution eq 'use_found') {
 5887: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5888: 	} elsif ($resolution eq 'use_typed') {
 5889: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5890: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5891: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5892: 	}
 5893: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5894: 	    $args{'CODE_ignore_dup'}=1;
 5895: 	}
 5896: 	$args{'CODE'}=$newCODE;
 5897: 	($line,$err,$errmsg)=
 5898: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5899: 				     'CODE',\%args);
 5900:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5901: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5902: 	    ($line,$err,$errmsg)=
 5903: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5904: 					 $which,'answer',
 5905: 					 { 'question'=>$question,
 5906: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5907:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5908: 	    if ($err) { last; }
 5909: 	}
 5910:     }
 5911:     if ($err) {
 5912: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5913:     } else {
 5914: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5915: 	&scantron_putfile($scanlines,$scan_data);
 5916:     }
 5917: }
 5918: 
 5919: =pod
 5920: 
 5921: =item reset_skipping_status
 5922: 
 5923:    Forgets the current set of remember skipped scanlines (and thus
 5924:    reverts back to considering all lines in the
 5925:    scantron_skipped_<filename> file)
 5926: 
 5927: =cut
 5928: 
 5929: sub reset_skipping_status {
 5930:     my ($scanlines,$scan_data)=&scantron_getfile();
 5931:     &scan_data($scan_data,'remember_skipping',undef,1);
 5932:     &scantron_putfile(undef,$scan_data);
 5933: }
 5934: 
 5935: =pod
 5936: 
 5937: =item start_skipping
 5938: 
 5939:    Marks a scanline to be skipped. 
 5940: 
 5941: =cut
 5942: 
 5943: sub start_skipping {
 5944:     my ($scan_data,$i)=@_;
 5945:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5946:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5947: 	$remembered{$i}=2;
 5948:     } else {
 5949: 	$remembered{$i}=1;
 5950:     }
 5951:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5952: }
 5953: 
 5954: =pod
 5955: 
 5956: =item should_be_skipped
 5957: 
 5958:    Checks whether a scanline should be skipped.
 5959: 
 5960: =cut
 5961: 
 5962: sub should_be_skipped {
 5963:     my ($scanlines,$scan_data,$i)=@_;
 5964:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5965: 	# not redoing old skips
 5966: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5967: 	return 0;
 5968:     }
 5969:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5970: 
 5971:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5972: 	return 0;
 5973:     }
 5974:     return 1;
 5975: }
 5976: 
 5977: =pod
 5978: 
 5979: =item remember_current_skipped
 5980: 
 5981:    Discovers what scanlines are in the scantron_skipped_<filename>
 5982:    file and remembers them into scan_data for later use.
 5983: 
 5984: =cut
 5985: 
 5986: sub remember_current_skipped {
 5987:     my ($scanlines,$scan_data)=&scantron_getfile();
 5988:     my %to_remember;
 5989:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5990: 	if ($scanlines->{'skipped'}[$i]) {
 5991: 	    $to_remember{$i}=1;
 5992: 	}
 5993:     }
 5994: 
 5995:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5996:     &scantron_putfile(undef,$scan_data);
 5997: }
 5998: 
 5999: =pod
 6000: 
 6001: =item check_for_error
 6002: 
 6003:     Checks if there was an error when attempting to remove a specific
 6004:     scantron_.. bubble sheet data file. Prints out an error if
 6005:     something went wrong.
 6006: 
 6007: =cut
 6008: 
 6009: sub check_for_error {
 6010:     my ($r,$result)=@_;
 6011:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6012: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6013:     }
 6014: }
 6015: 
 6016: =pod
 6017: 
 6018: =item scantron_warning_screen
 6019: 
 6020:    Interstitial screen to make sure the operator has selected the
 6021:    correct options before we start the validation phase.
 6022: 
 6023: =cut
 6024: 
 6025: sub scantron_warning_screen {
 6026:     my ($button_text)=@_;
 6027:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6028:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6029:     my $CODElist;
 6030:     if ($scantron_config{'CODElocation'} &&
 6031: 	$scantron_config{'CODEstart'} &&
 6032: 	$scantron_config{'CODElength'}) {
 6033: 	$CODElist=$env{'form.scantron_CODElist'};
 6034: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6035: 	$CODElist=
 6036: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6037: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6038:     }
 6039:     return ('
 6040: <p>
 6041: <span class="LC_warning">
 6042: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6043: </p>
 6044: <table>
 6045: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6046: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6047: '.$CODElist.'
 6048: </table>
 6049: <br />
 6050: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6051: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6052: 
 6053: <br />
 6054: ');
 6055: }
 6056: 
 6057: =pod
 6058: 
 6059: =item scantron_do_warning
 6060: 
 6061:    Check if the operator has picked something for all required
 6062:    fields. Error out if something is missing.
 6063: 
 6064: =cut
 6065: 
 6066: sub scantron_do_warning {
 6067:     my ($r)=@_;
 6068:     my ($symb)=&get_symb($r);
 6069:     if (!$symb) {return '';}
 6070:     my $default_form_data=&defaultFormData($symb);
 6071:     $r->print(&scantron_form_start().$default_form_data);
 6072:     if ( $env{'form.selectpage'} eq '' ||
 6073: 	 $env{'form.scantron_selectfile'} eq '' ||
 6074: 	 $env{'form.scantron_format'} eq '' ) {
 6075: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6076: 	if ( $env{'form.selectpage'} eq '') {
 6077: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6078: 	} 
 6079: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6080: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6081: 	} 
 6082: 	if ( $env{'form.scantron_format'} eq '') {
 6083: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6084: 	} 
 6085:     } else {
 6086: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6087: 	$r->print('
 6088: '.$warning.'
 6089: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6090: <input type="hidden" name="command" value="scantron_validate" />
 6091: ');
 6092:     }
 6093:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6094:     return '';
 6095: }
 6096: 
 6097: =pod
 6098: 
 6099: =item scantron_form_start
 6100: 
 6101:     html hidden input for remembering all selected grading options
 6102: 
 6103: =cut
 6104: 
 6105: sub scantron_form_start {
 6106:     my ($max_bubble)=@_;
 6107:     my $result= <<SCANTRONFORM;
 6108: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6109:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6110:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6111:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6112:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6113:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6114:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6115:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6116:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6117:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6118: SCANTRONFORM
 6119: 
 6120:   my $line = 0;
 6121:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6122:        my $chunk =
 6123: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6124:        $chunk .=
 6125: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6126:        $chunk .= 
 6127:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6128:        $chunk .=
 6129:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6130:        $result .= $chunk;
 6131:        $line++;
 6132:    }
 6133:     return $result;
 6134: }
 6135: 
 6136: =pod
 6137: 
 6138: =item scantron_validate_file
 6139: 
 6140:     Dispatch routine for doing validation of a bubble sheet data file.
 6141: 
 6142:     Also processes any necessary information resets that need to
 6143:     occur before validation begins (ignore previous corrections,
 6144:     restarting the skipped records processing)
 6145: 
 6146: =cut
 6147: 
 6148: sub scantron_validate_file {
 6149:     my ($r) = @_;
 6150:     my ($symb)=&get_symb($r);
 6151:     if (!$symb) {return '';}
 6152:     my $default_form_data=&defaultFormData($symb);
 6153:     
 6154:     # do the detection of only doing skipped records first befroe we delete
 6155:     # them when doing the corrections reset
 6156:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6157: 	&reset_skipping_status();
 6158:     }
 6159:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6160: 	&remember_current_skipped();
 6161: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6162:     }
 6163: 
 6164:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6165: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6166: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6167: 	&check_for_error($r,&scantron_remove_scan_data());
 6168: 	$env{'form.scantron_options_ignore'}='done';
 6169:     }
 6170: 
 6171:     if ($env{'form.scantron_corrections'}) {
 6172: 	&scantron_process_corrections($r);
 6173:     }
 6174:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6175:     #get the student pick code ready
 6176:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6177:     my $max_bubble=&scantron_get_maxbubble();
 6178:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6179:     $r->print($result);
 6180:     
 6181:     my @validate_phases=( 'sequence',
 6182: 			  'ID',
 6183: 			  'CODE',
 6184: 			  'doublebubble',
 6185: 			  'missingbubbles');
 6186:     if (!$env{'form.validatepass'}) {
 6187: 	$env{'form.validatepass'} = 0;
 6188:     }
 6189:     my $currentphase=$env{'form.validatepass'};
 6190: 
 6191: 
 6192:     my $stop=0;
 6193:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6194: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6195: 	$r->rflush();
 6196: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6197: 	{
 6198: 	    no strict 'refs';
 6199: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6200: 	}
 6201:     }
 6202:     if (!$stop) {
 6203: 	my $warning=&scantron_warning_screen('Start Grading');
 6204: 	$r->print(&mt('Validation process complete.').'<br />'.
 6205:                   $warning.
 6206:                   &mt('Perform verification for each student after storage of submissions?').
 6207:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6208:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6209:                   ('&nbsp;'x3).'<label>'.
 6210:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6211:                   '</label></span><br />'.
 6212:                   &mt('Grading will take longer if you use verification.').'<br />'.
 6213:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6214:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6215:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6216:     } else {
 6217: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6218: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6219:     }
 6220:     if ($stop) {
 6221: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6222: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
 6223: 	    $r->print(' '.&mt('this error').' <br />');
 6224: 
 6225: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6226: 	} else {
 6227:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6228: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6229:             } else {
 6230:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6231:             }
 6232: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6233: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6234: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6235: 	}
 6236:     }
 6237:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6238:     return '';
 6239: }
 6240: 
 6241: 
 6242: =pod
 6243: 
 6244: =item scantron_remove_file
 6245: 
 6246:    Removes the requested bubble sheet data file, makes sure that
 6247:    scantron_original_<filename> is never removed
 6248: 
 6249: 
 6250: =cut
 6251: 
 6252: sub scantron_remove_file {
 6253:     my ($which)=@_;
 6254:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6255:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6256:     my $file='scantron_';
 6257:     if ($which eq 'corrected' || $which eq 'skipped') {
 6258: 	$file.=$which.'_';
 6259:     } else {
 6260: 	return 'refused';
 6261:     }
 6262:     $file.=$env{'form.scantron_selectfile'};
 6263:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6264: }
 6265: 
 6266: 
 6267: =pod
 6268: 
 6269: =item scantron_remove_scan_data
 6270: 
 6271:    Removes all scan_data correction for the requested bubble sheet
 6272:    data file.  (In the case that both the are doing skipped records we need
 6273:    to remember the old skipped lines for the time being so that element
 6274:    persists for a while.)
 6275: 
 6276: =cut
 6277: 
 6278: sub scantron_remove_scan_data {
 6279:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6280:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6281:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6282:     my @todelete;
 6283:     my $filename=$env{'form.scantron_selectfile'};
 6284:     foreach my $key (@keys) {
 6285: 	if ($key=~/^\Q$filename\E_/) {
 6286: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6287: 		$key=~/remember_skipping/) {
 6288: 		next;
 6289: 	    }
 6290: 	    push(@todelete,$key);
 6291: 	}
 6292:     }
 6293:     my $result;
 6294:     if (@todelete) {
 6295: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6296: 				       \@todelete,$cdom,$cname);
 6297:     } else {
 6298: 	$result = 'ok';
 6299:     }
 6300:     return $result;
 6301: }
 6302: 
 6303: 
 6304: =pod
 6305: 
 6306: =item scantron_getfile
 6307: 
 6308:     Fetches the requested bubble sheet data file (all 3 versions), and
 6309:     the scan_data hash
 6310:   
 6311:   Arguments:
 6312:     None
 6313: 
 6314:   Returns:
 6315:     2 hash references
 6316: 
 6317:      - first one has 
 6318:          orig      -
 6319:          corrected -
 6320:          skipped   -  each of which points to an array ref of the specified
 6321:                       file broken up into individual lines
 6322:          count     - number of scanlines
 6323:  
 6324:      - second is the scan_data hash possible keys are
 6325:        ($number refers to scanline numbered $number and thus the key affects
 6326:         only that scanline
 6327:         $bubline refers to the specific bubble line element and the aspects
 6328:         refers to that specific bubble line element)
 6329: 
 6330:        $number.user - username:domain to use
 6331:        $number.CODE_ignore_dup 
 6332:                     - ignore the duplicate CODE error 
 6333:        $number.useCODE
 6334:                     - use the CODE in the scanline as is
 6335:        $number.no_bubble.$bubline
 6336:                     - it is valid that there is no bubbled in bubble
 6337:                       at $number $bubline
 6338:        remember_skipping
 6339:                     - a frozen hash containing keys of $number and values
 6340:                       of either 
 6341:                         1 - we are on a 'do skipped records pass' and plan
 6342:                             on processing this line
 6343:                         2 - we are on a 'do skipped records pass' and this
 6344:                             scanline has been marked to skip yet again
 6345: 
 6346: =cut
 6347: 
 6348: sub scantron_getfile {
 6349:     #FIXME really would prefer a scantron directory
 6350:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6351:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6352:     my $lines;
 6353:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6354: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6355:     my %scanlines;
 6356:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6357:     my $temp=$scanlines{'orig'};
 6358:     $scanlines{'count'}=$#$temp;
 6359: 
 6360:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6361: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6362:     if ($lines eq '-1') {
 6363: 	$scanlines{'corrected'}=[];
 6364:     } else {
 6365: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6366:     }
 6367:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6368: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6369:     if ($lines eq '-1') {
 6370: 	$scanlines{'skipped'}=[];
 6371:     } else {
 6372: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6373:     }
 6374:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6375:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6376:     my %scan_data = @tmp;
 6377:     return (\%scanlines,\%scan_data);
 6378: }
 6379: 
 6380: =pod
 6381: 
 6382: =item lonnet_putfile
 6383: 
 6384:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6385: 
 6386:  Arguments:
 6387:    $contents - data to store
 6388:    $filename - filename to store $contents into
 6389: 
 6390:  Returns:
 6391:    result value from &Apache::lonnet::finishuserfileupload
 6392: 
 6393: =cut
 6394: 
 6395: sub lonnet_putfile {
 6396:     my ($contents,$filename)=@_;
 6397:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6398:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6399:     $env{'form.sillywaytopassafilearound'}=$contents;
 6400:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6401: 
 6402: }
 6403: 
 6404: =pod
 6405: 
 6406: =item scantron_putfile
 6407: 
 6408:     Stores the current version of the bubble sheet data files, and the
 6409:     scan_data hash. (Does not modify the original version only the
 6410:     corrected and skipped versions.
 6411: 
 6412:  Arguments:
 6413:     $scanlines - hash ref that looks like the first return value from
 6414:                  &scantron_getfile()
 6415:     $scan_data - hash ref that looks like the second return value from
 6416:                  &scantron_getfile()
 6417: 
 6418: =cut
 6419: 
 6420: sub scantron_putfile {
 6421:     my ($scanlines,$scan_data) = @_;
 6422:     #FIXME really would prefer a scantron directory
 6423:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6424:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6425:     if ($scanlines) {
 6426: 	my $prefix='scantron_';
 6427: # no need to update orig, shouldn't change
 6428: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6429: #		    $env{'form.scantron_selectfile'});
 6430: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6431: 			$prefix.'corrected_'.
 6432: 			$env{'form.scantron_selectfile'});
 6433: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6434: 			$prefix.'skipped_'.
 6435: 			$env{'form.scantron_selectfile'});
 6436:     }
 6437:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6438: }
 6439: 
 6440: =pod
 6441: 
 6442: =item scantron_get_line
 6443: 
 6444:    Returns the correct version of the scanline
 6445: 
 6446:  Arguments:
 6447:     $scanlines - hash ref that looks like the first return value from
 6448:                  &scantron_getfile()
 6449:     $scan_data - hash ref that looks like the second return value from
 6450:                  &scantron_getfile()
 6451:     $i         - number of the requested line (starts at 0)
 6452: 
 6453:  Returns:
 6454:    A scanline, (either the original or the corrected one if it
 6455:    exists), or undef if the requested scanline should be
 6456:    skipped. (Either because it's an skipped scanline, or it's an
 6457:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6458:    pass.
 6459: 
 6460: =cut
 6461: 
 6462: sub scantron_get_line {
 6463:     my ($scanlines,$scan_data,$i)=@_;
 6464:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6465:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6466:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6467:     return $scanlines->{'orig'}[$i]; 
 6468: }
 6469: 
 6470: =pod
 6471: 
 6472: =item scantron_todo_count
 6473: 
 6474:     Counts the number of scanlines that need processing.
 6475: 
 6476:  Arguments:
 6477:     $scanlines - hash ref that looks like the first return value from
 6478:                  &scantron_getfile()
 6479:     $scan_data - hash ref that looks like the second return value from
 6480:                  &scantron_getfile()
 6481: 
 6482:  Returns:
 6483:     $count - number of scanlines to process
 6484: 
 6485: =cut
 6486: 
 6487: sub get_todo_count {
 6488:     my ($scanlines,$scan_data)=@_;
 6489:     my $count=0;
 6490:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6491: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6492: 	if ($line=~/^[\s\cz]*$/) { next; }
 6493: 	$count++;
 6494:     }
 6495:     return $count;
 6496: }
 6497: 
 6498: =pod
 6499: 
 6500: =item scantron_put_line
 6501: 
 6502:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6503:     data file.
 6504: 
 6505:  Arguments:
 6506:     $scanlines - hash ref that looks like the first return value from
 6507:                  &scantron_getfile()
 6508:     $scan_data - hash ref that looks like the second return value from
 6509:                  &scantron_getfile()
 6510:     $i         - line number to update
 6511:     $newline   - contents of the updated scanline
 6512:     $skip      - if true make the line for skipping and update the
 6513:                  'skipped' file
 6514: 
 6515: =cut
 6516: 
 6517: sub scantron_put_line {
 6518:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6519:     if ($skip) {
 6520: 	$scanlines->{'skipped'}[$i]=$newline;
 6521: 	&start_skipping($scan_data,$i);
 6522: 	return;
 6523:     }
 6524:     $scanlines->{'corrected'}[$i]=$newline;
 6525: }
 6526: 
 6527: =pod
 6528: 
 6529: =item scantron_clear_skip
 6530: 
 6531:    Remove a line from the 'skipped' file
 6532: 
 6533:  Arguments:
 6534:     $scanlines - hash ref that looks like the first return value from
 6535:                  &scantron_getfile()
 6536:     $scan_data - hash ref that looks like the second return value from
 6537:                  &scantron_getfile()
 6538:     $i         - line number to update
 6539: 
 6540: =cut
 6541: 
 6542: sub scantron_clear_skip {
 6543:     my ($scanlines,$scan_data,$i)=@_;
 6544:     if (exists($scanlines->{'skipped'}[$i])) {
 6545: 	undef($scanlines->{'skipped'}[$i]);
 6546: 	return 1;
 6547:     }
 6548:     return 0;
 6549: }
 6550: 
 6551: =pod
 6552: 
 6553: =item scantron_filter_not_exam
 6554: 
 6555:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6556:    filter out resources that are not marked as 'exam' mode
 6557: 
 6558: =cut
 6559: 
 6560: sub scantron_filter_not_exam {
 6561:     my ($curres)=@_;
 6562:     
 6563:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6564: 	# if the user has asked to not have either hidden
 6565: 	# or 'randomout' controlled resources to be graded
 6566: 	# don't include them
 6567: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6568: 	    && $curres->randomout) {
 6569: 	    return 0;
 6570: 	}
 6571: 	return 1;
 6572:     }
 6573:     return 0;
 6574: }
 6575: 
 6576: =pod
 6577: 
 6578: =item scantron_validate_sequence
 6579: 
 6580:     Validates the selected sequence, checking for resource that are
 6581:     not set to exam mode.
 6582: 
 6583: =cut
 6584: 
 6585: sub scantron_validate_sequence {
 6586:     my ($r,$currentphase) = @_;
 6587: 
 6588:     my $navmap=Apache::lonnavmaps::navmap->new();
 6589:     my (undef,undef,$sequence)=
 6590: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6591: 
 6592:     my $map=$navmap->getResourceByUrl($sequence);
 6593: 
 6594:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6595:                                     value="ignore" />');
 6596:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6597: 	my @resources=
 6598: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6599: 	if (@resources) {
 6600: 	    $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>");
 6601: 	    return (1,$currentphase);
 6602: 	}
 6603:     }
 6604: 
 6605:     return (0,$currentphase+1);
 6606: }
 6607: 
 6608: 
 6609: 
 6610: sub scantron_validate_ID {
 6611:     my ($r,$currentphase) = @_;
 6612:     
 6613:     #get student info
 6614:     my $classlist=&Apache::loncoursedata::get_classlist();
 6615:     my %idmap=&username_to_idmap($classlist);
 6616: 
 6617:     #get scantron line setup
 6618:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6619:     my ($scanlines,$scan_data)=&scantron_getfile();
 6620:     
 6621:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6622: 
 6623:     my %found=('ids'=>{},'usernames'=>{});
 6624:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6625: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6626: 	if ($line=~/^[\s\cz]*$/) { next; }
 6627: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6628: 						 $scan_data);
 6629: 	my $id=$$scan_record{'scantron.ID'};
 6630: 	my $found;
 6631: 	foreach my $checkid (keys(%idmap)) {
 6632: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6633: 	}
 6634: 	if ($found) {
 6635: 	    my $username=$idmap{$found};
 6636: 	    if ($found{'ids'}{$found}) {
 6637: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6638: 					 $line,'duplicateID',$found);
 6639: 		return(1,$currentphase);
 6640: 	    } elsif ($found{'usernames'}{$username}) {
 6641: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6642: 					 $line,'duplicateID',$username);
 6643: 		return(1,$currentphase);
 6644: 	    }
 6645: 	    #FIXME store away line we previously saw the ID on to use above
 6646: 	    $found{'ids'}{$found}++;
 6647: 	    $found{'usernames'}{$username}++;
 6648: 	} else {
 6649: 	    if ($id =~ /^\s*$/) {
 6650: 		my $username=&scan_data($scan_data,"$i.user");
 6651: 		if (defined($username) && $found{'usernames'}{$username}) {
 6652: 		    &scantron_get_correction($r,$i,$scan_record,
 6653: 					     \%scantron_config,
 6654: 					     $line,'duplicateID',$username);
 6655: 		    return(1,$currentphase);
 6656: 		} elsif (!defined($username)) {
 6657: 		    &scantron_get_correction($r,$i,$scan_record,
 6658: 					     \%scantron_config,
 6659: 					     $line,'incorrectID');
 6660: 		    return(1,$currentphase);
 6661: 		}
 6662: 		$found{'usernames'}{$username}++;
 6663: 	    } else {
 6664: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6665: 					 $line,'incorrectID');
 6666: 		return(1,$currentphase);
 6667: 	    }
 6668: 	}
 6669:     }
 6670: 
 6671:     return (0,$currentphase+1);
 6672: }
 6673: 
 6674: 
 6675: sub scantron_get_correction {
 6676:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6677: #FIXME in the case of a duplicated ID the previous line, probably need
 6678: #to show both the current line and the previous one and allow skipping
 6679: #the previous one or the current one
 6680: 
 6681:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6682: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6683: 			    " for PaperID <tt>[_1]</tt>",
 6684: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6685:     } else {
 6686: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6687: 			    " in scanline [_1] <pre>[_2]</pre>",
 6688: 			    $i,$line)."</p> \n");
 6689:     }
 6690:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6691: 			  "The name on the paper is [_2],[_3]",
 6692: 			  $$scan_record{'scantron.ID'},
 6693: 			  $$scan_record{'scantron.LastName'},
 6694: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6695: 
 6696:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6697:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6698:                            # Array populated for doublebubble or
 6699:     my @lines_to_correct;  # missingbubble errors to build javascript
 6700:                            # to validate radio button checking   
 6701: 
 6702:     if ($error =~ /ID$/) {
 6703: 	if ($error eq 'incorrectID') {
 6704: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6705: 		      "</p>\n");
 6706: 	} elsif ($error eq 'duplicateID') {
 6707: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6708: 	}
 6709: 	$r->print($message);
 6710: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6711: 	$r->print("\n<ul><li> ");
 6712: 	#FIXME it would be nice if this sent back the user ID and
 6713: 	#could do partial userID matches
 6714: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6715: 				       'scantron_username','scantron_domain'));
 6716: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6717: 	$r->print("\n@".
 6718: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6719: 
 6720: 	$r->print('</li>');
 6721:     } elsif ($error =~ /CODE$/) {
 6722: 	if ($error eq 'incorrectCODE') {
 6723: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6724: 	} elsif ($error eq 'duplicateCODE') {
 6725: 	    $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");
 6726: 	}
 6727: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6728: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6729: 	$r->print($message);
 6730: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6731: 	$r->print("\n<br /> ");
 6732: 	my $i=0;
 6733: 	if ($error eq 'incorrectCODE' 
 6734: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6735: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6736: 	    if ($closest > 0) {
 6737: 		foreach my $testcode (@{$closest}) {
 6738: 		    my $checked='';
 6739: 		    if (!$i) { $checked=' checked="checked" '; }
 6740: 		    $r->print("
 6741:    <label>
 6742:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6743:        ".&mt("Use the similar CODE [_1] instead.",
 6744: 	    "<b><tt>".$testcode."</tt></b>")."
 6745:     </label>
 6746:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6747: 		    $r->print("\n<br />");
 6748: 		    $i++;
 6749: 		}
 6750: 	    }
 6751: 	}
 6752: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6753: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6754: 	    $r->print("
 6755:     <label>
 6756:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6757:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6758: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6759:     </label>");
 6760: 	    $r->print("\n<br />");
 6761: 	}
 6762: 
 6763: 	$r->print(<<ENDSCRIPT);
 6764: <script type="text/javascript">
 6765: function change_radio(field) {
 6766:     var slct=document.scantronupload.scantron_CODE_resolution;
 6767:     var i;
 6768:     for (i=0;i<slct.length;i++) {
 6769:         if (slct[i].value==field) { slct[i].checked=true; }
 6770:     }
 6771: }
 6772: </script>
 6773: ENDSCRIPT
 6774: 	my $href="/adm/pickcode?".
 6775: 	   "form=".&escape("scantronupload").
 6776: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6777: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6778: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6779: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6780: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6781: 	    $r->print("
 6782:     <label>
 6783:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6784:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6785: 	     "<a target='_blank' href='$href'>","</a>")."
 6786:     </label> 
 6787:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
 6788: 	    $r->print("\n<br />");
 6789: 	}
 6790: 	$r->print("
 6791:     <label>
 6792:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6793:        ".&mt("Use [_1] as the CODE.",
 6794: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6795: 	$r->print("\n<br /><br />");
 6796:     } elsif ($error eq 'doublebubble') {
 6797: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6798: 
 6799: 	# The form field scantron_questions is acutally a list of line numbers.
 6800: 	# represented by this form so:
 6801: 
 6802: 	my $line_list = &questions_to_line_list($arg);
 6803: 
 6804: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6805: 		  $line_list.'" />');
 6806: 	$r->print($message);
 6807: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6808: 	foreach my $question (@{$arg}) {
 6809: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6810:                                                    $scan_record, $error);
 6811:             push(@lines_to_correct,@linenums);
 6812: 	}
 6813:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6814:     } elsif ($error eq 'missingbubble') {
 6815: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6816: 	$r->print($message);
 6817: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6818: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6819: 
 6820: 	# The form field scantron_questions is actually a list of line numbers not
 6821: 	# a list of question numbers. Therefore:
 6822: 	#
 6823: 	
 6824: 	my $line_list = &questions_to_line_list($arg);
 6825: 
 6826: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6827: 		  $line_list.'" />');
 6828: 	foreach my $question (@{$arg}) {
 6829: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6830:                                                    $scan_record, $error);
 6831:             push(@lines_to_correct,@linenums);
 6832: 	}
 6833:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6834:     } else {
 6835: 	$r->print("\n<ul>");
 6836:     }
 6837:     $r->print("\n</li></ul>");
 6838: }
 6839: 
 6840: sub verify_bubbles_checked {
 6841:     my (@ansnums) = @_;
 6842:     my $ansnumstr = join('","',@ansnums);
 6843:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6844:     my $output = (<<ENDSCRIPT);
 6845: <script type="text/javascript">
 6846: function verify_bubble_radio(form) {
 6847:     var ansnumArray = new Array ("$ansnumstr");
 6848:     var need_bubble_count = 0;
 6849:     for (var i=0; i<ansnumArray.length; i++) {
 6850:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6851:             var bubble_picked = 0; 
 6852:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6853:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6854:                     bubble_picked = 1;
 6855:                 }
 6856:             }
 6857:             if (bubble_picked == 0) {
 6858:                 need_bubble_count ++;
 6859:             }
 6860:         }
 6861:     }
 6862:     if (need_bubble_count) {
 6863:         alert("$warning");
 6864:         return;
 6865:     }
 6866:     form.submit(); 
 6867: }
 6868: </script>
 6869: ENDSCRIPT
 6870:     return $output;
 6871: }
 6872: 
 6873: =pod
 6874: 
 6875: =item  questions_to_line_list
 6876: 
 6877: Converts a list of questions into a string of comma separated
 6878: line numbers in the answer sheet used by the questions.  This is
 6879: used to fill in the scantron_questions form field.
 6880: 
 6881:   Arguments:
 6882:      questions    - Reference to an array of questions.
 6883: 
 6884: =cut
 6885: 
 6886: 
 6887: sub questions_to_line_list {
 6888:     my ($questions) = @_;
 6889:     my @lines;
 6890: 
 6891:     foreach my $item (@{$questions}) {
 6892:         my $question = $item;
 6893:         my ($first,$count,$last);
 6894:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6895:             $question = $1;
 6896:             my $subquestion = $2;
 6897:             $first = $first_bubble_line{$question-1} + 1;
 6898:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6899:             my $subcount = 1;
 6900:             while ($subcount<$subquestion) {
 6901:                 $first += $subans[$subcount-1];
 6902:                 $subcount ++;
 6903:             }
 6904:             $count = $subans[$subquestion-1];
 6905:         } else {
 6906: 	    $first   = $first_bubble_line{$question-1} + 1;
 6907: 	    $count   = $bubble_lines_per_response{$question-1};
 6908:         }
 6909:         $last = $first+$count-1;
 6910:         push(@lines, ($first..$last));
 6911:     }
 6912:     return join(',', @lines);
 6913: }
 6914: 
 6915: =pod 
 6916: 
 6917: =item prompt_for_corrections
 6918: 
 6919: Prompts for a potentially multiline correction to the
 6920: user's bubbling (factors out common code from scantron_get_correction
 6921: for multi and missing bubble cases).
 6922: 
 6923:  Arguments:
 6924:    $r           - Apache request object.
 6925:    $question    - The question number to prompt for.
 6926:    $scan_config - The scantron file configuration hash.
 6927:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6928:    $error       - Type of error
 6929: 
 6930:  Implicit inputs:
 6931:    %bubble_lines_per_response   - Starting line numbers for each question.
 6932:                                   Numbered from 0 (but question numbers are from
 6933:                                   1.
 6934:    %first_bubble_line           - Starting bubble line for each question.
 6935:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6936:                                   type problems render as separate sub-questions, 
 6937:                                   in exam mode. This hash contains a 
 6938:                                   comma-separated list of the lines per 
 6939:                                   sub-question.
 6940:    %responsetype_per_response   - essayresponse, formularesponse,
 6941:                                   stringresponse, imageresponse, reactionresponse,
 6942:                                   and organicresponse type problem parts can have
 6943:                                   multiple lines per response if the weight
 6944:                                   assigned exceeds 10.  In this case, only
 6945:                                   one bubble per line is permitted, but more 
 6946:                                   than one line might contain bubbles, e.g.
 6947:                                   bubbling of: line 1 - J, line 2 - J, 
 6948:                                   line 3 - B would assign 22 points.  
 6949: 
 6950: =cut
 6951: 
 6952: sub prompt_for_corrections {
 6953:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6954:     my ($current_line,$lines);
 6955:     my @linenums;
 6956:     my $questionnum = $question;
 6957:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6958:         $question = $1;
 6959:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6960:         my $subquestion = $2;
 6961:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6962:         my $subcount = 1;
 6963:         while ($subcount<$subquestion) {
 6964:             $current_line += $subans[$subcount-1];
 6965:             $subcount ++;
 6966:         }
 6967:         $lines = $subans[$subquestion-1];
 6968:     } else {
 6969:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6970:         $lines        = $bubble_lines_per_response{$question-1};
 6971:     }
 6972:     if ($lines > 1) {
 6973:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 6974:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 6975:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 6976:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 6977:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 6978:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 6979:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 6980:             $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 scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron 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 />');
 6981:         } else {
 6982:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 6983:         }
 6984:     }
 6985:     for (my $i =0; $i < $lines; $i++) {
 6986:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 6987: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 6988: 	        		  $questionnum,$error,split('', $selected));
 6989:         push(@linenums,$current_line);
 6990: 	$current_line++;
 6991:     }
 6992:     if ($lines > 1) {
 6993: 	$r->print("<hr /><br />");
 6994:     }
 6995:     return @linenums;
 6996: }
 6997: 
 6998: =pod
 6999: 
 7000: =item scantron_bubble_selector
 7001:   
 7002:    Generates the html radiobuttons to correct a single bubble line
 7003:    possibly showing the existing the selected bubbles if known
 7004: 
 7005:  Arguments:
 7006:     $r           - Apache request object
 7007:     $scan_config - hash from &get_scantron_config()
 7008:     $line        - Number of the line being displayed.
 7009:     $questionnum - Question number (may include subquestion)
 7010:     $error       - Type of error.
 7011:     @selected    - Array of bubbles picked on this line.
 7012: 
 7013: =cut
 7014: 
 7015: sub scantron_bubble_selector {
 7016:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7017:     my $max=$$scan_config{'Qlength'};
 7018: 
 7019:     my $scmode=$$scan_config{'Qon'};
 7020:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7021: 
 7022:     my @alphabet=('A'..'Z');
 7023:     $r->print(&Apache::loncommon::start_data_table().
 7024:               &Apache::loncommon::start_data_table_row());
 7025:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7026:     for (my $i=0;$i<$max+1;$i++) {
 7027: 	$r->print("\n".'<td align="center">');
 7028: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7029: 	else { $r->print('&nbsp;'); }
 7030: 	$r->print('</td>');
 7031:     }
 7032:     $r->print(&Apache::loncommon::end_data_table_row().
 7033:               &Apache::loncommon::start_data_table_row());
 7034:     for (my $i=0;$i<$max;$i++) {
 7035: 	$r->print("\n".
 7036: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7037: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7038:     }
 7039:     my $nobub_checked = ' ';
 7040:     if ($error eq 'missingbubble') {
 7041:         $nobub_checked = ' checked = "checked" ';
 7042:     }
 7043:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7044: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7045:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7046:               $line.'" value="'.$questionnum.'" /></td>');
 7047:     $r->print(&Apache::loncommon::end_data_table_row().
 7048:               &Apache::loncommon::end_data_table());
 7049: }
 7050: 
 7051: =pod
 7052: 
 7053: =item num_matches
 7054: 
 7055:    Counts the number of characters that are the same between the two arguments.
 7056: 
 7057:  Arguments:
 7058:    $orig - CODE from the scanline
 7059:    $code - CODE to match against
 7060: 
 7061:  Returns:
 7062:    $count - integer count of the number of same characters between the
 7063:             two arguments
 7064: 
 7065: =cut
 7066: 
 7067: sub num_matches {
 7068:     my ($orig,$code) = @_;
 7069:     my @code=split(//,$code);
 7070:     my @orig=split(//,$orig);
 7071:     my $same=0;
 7072:     for (my $i=0;$i<scalar(@code);$i++) {
 7073: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7074:     }
 7075:     return $same;
 7076: }
 7077: 
 7078: =pod
 7079: 
 7080: =item scantron_get_closely_matching_CODEs
 7081: 
 7082:    Cycles through all CODEs and finds the set that has the greatest
 7083:    number of same characters as the provided CODE
 7084: 
 7085:  Arguments:
 7086:    $allcodes - hash ref returned by &get_codes()
 7087:    $CODE     - CODE from the current scanline
 7088: 
 7089:  Returns:
 7090:    2 element list
 7091:     - first elements is number of how closely matching the best fit is 
 7092:       (5 means best set has 5 matching characters)
 7093:     - second element is an arrary ref containing the set of valid CODEs
 7094:       that best fit the passed in CODE
 7095: 
 7096: =cut
 7097: 
 7098: sub scantron_get_closely_matching_CODEs {
 7099:     my ($allcodes,$CODE)=@_;
 7100:     my @CODEs;
 7101:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7102: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7103:     }
 7104: 
 7105:     return ($#CODEs,$CODEs[-1]);
 7106: }
 7107: 
 7108: =pod
 7109: 
 7110: =item get_codes
 7111: 
 7112:    Builds a hash which has keys of all of the valid CODEs from the selected
 7113:    set of remembered CODEs.
 7114: 
 7115:  Arguments:
 7116:   $old_name - name of the set of remembered CODEs
 7117:   $cdom     - domain of the course
 7118:   $cnum     - internal course name
 7119: 
 7120:  Returns:
 7121:   %allcodes - keys are the valid CODEs, values are all 1
 7122: 
 7123: =cut
 7124: 
 7125: sub get_codes {
 7126:     my ($old_name, $cdom, $cnum) = @_;
 7127:     if (!$old_name) {
 7128: 	$old_name=$env{'form.scantron_CODElist'};
 7129:     }
 7130:     if (!$cdom) {
 7131: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7132:     }
 7133:     if (!$cnum) {
 7134: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7135:     }
 7136:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7137: 				    $cdom,$cnum);
 7138:     my %allcodes;
 7139:     if ($result{"type\0$old_name"} eq 'number') {
 7140: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7141:     } else {
 7142: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7143:     }
 7144:     return %allcodes;
 7145: }
 7146: 
 7147: =pod
 7148: 
 7149: =item scantron_validate_CODE
 7150: 
 7151:    Validates all scanlines in the selected file to not have any
 7152:    invalid or underspecified CODEs and that none of the codes are
 7153:    duplicated if this was requested.
 7154: 
 7155: =cut
 7156: 
 7157: sub scantron_validate_CODE {
 7158:     my ($r,$currentphase) = @_;
 7159:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7160:     if ($scantron_config{'CODElocation'} &&
 7161: 	$scantron_config{'CODEstart'} &&
 7162: 	$scantron_config{'CODElength'}) {
 7163: 	if (!defined($env{'form.scantron_CODElist'})) {
 7164: 	    &FIXME_blow_up()
 7165: 	}
 7166:     } else {
 7167: 	return (0,$currentphase+1);
 7168:     }
 7169:     
 7170:     my %usedCODEs;
 7171: 
 7172:     my %allcodes=&get_codes();
 7173: 
 7174:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7175: 
 7176:     my ($scanlines,$scan_data)=&scantron_getfile();
 7177:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7178: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7179: 	if ($line=~/^[\s\cz]*$/) { next; }
 7180: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7181: 						 $scan_data);
 7182: 	my $CODE=$$scan_record{'scantron.CODE'};
 7183: 	my $error=0;
 7184: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7185: 	    &scantron_get_correction($r,$i,$scan_record,
 7186: 				     \%scantron_config,
 7187: 				     $line,'incorrectCODE',\%allcodes);
 7188: 	    return(1,$currentphase);
 7189: 	}
 7190: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7191: 	    && !$$scan_record{'scantron.useCODE'}) {
 7192: 	    &scantron_get_correction($r,$i,$scan_record,
 7193: 				     \%scantron_config,
 7194: 				     $line,'incorrectCODE',\%allcodes);
 7195: 	    return(1,$currentphase);
 7196: 	}
 7197: 	if (exists($usedCODEs{$CODE}) 
 7198: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7199: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7200: 	    &scantron_get_correction($r,$i,$scan_record,
 7201: 				     \%scantron_config,
 7202: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7203: 	    return(1,$currentphase);
 7204: 	}
 7205: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7206:     }
 7207:     return (0,$currentphase+1);
 7208: }
 7209: 
 7210: =pod
 7211: 
 7212: =item scantron_validate_doublebubble
 7213: 
 7214:    Validates all scanlines in the selected file to not have any
 7215:    bubble lines with multiple bubbles marked.
 7216: 
 7217: =cut
 7218: 
 7219: sub scantron_validate_doublebubble {
 7220:     my ($r,$currentphase) = @_;
 7221:     #get student info
 7222:     my $classlist=&Apache::loncoursedata::get_classlist();
 7223:     my %idmap=&username_to_idmap($classlist);
 7224: 
 7225:     #get scantron line setup
 7226:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7227:     my ($scanlines,$scan_data)=&scantron_getfile();
 7228:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7229: 
 7230:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7231: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7232: 	if ($line=~/^[\s\cz]*$/) { next; }
 7233: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7234: 						 $scan_data);
 7235: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7236: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7237: 				 'doublebubble',
 7238: 				 $$scan_record{'scantron.doubleerror'});
 7239:     	return (1,$currentphase);
 7240:     }
 7241:     return (0,$currentphase+1);
 7242: }
 7243: 
 7244: 
 7245: sub scantron_get_maxbubble {
 7246:     if (defined($env{'form.scantron_maxbubble'}) &&
 7247: 	$env{'form.scantron_maxbubble'}) {
 7248: 	&restore_bubble_lines();
 7249: 	return $env{'form.scantron_maxbubble'};
 7250:     }
 7251: 
 7252:     my (undef, undef, $sequence) =
 7253: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7254: 
 7255:     my $navmap=Apache::lonnavmaps::navmap->new();
 7256:     my $map=$navmap->getResourceByUrl($sequence);
 7257:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7258: 
 7259:     &Apache::lonxml::clear_problem_counter();
 7260: 
 7261:     my $uname       = $env{'form.student'};
 7262:     my $udom        = $env{'form.userdom'};
 7263:     my $cid         = $env{'request.course.id'};
 7264:     my $total_lines = 0;
 7265:     %bubble_lines_per_response = ();
 7266:     %first_bubble_line         = ();
 7267:     %subdivided_bubble_lines   = ();
 7268:     %responsetype_per_response = ();
 7269: 
 7270:     my $response_number = 0;
 7271:     my $bubble_line     = 0;
 7272:     foreach my $resource (@resources) {
 7273:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7274:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7275: 	    foreach my $part_id (@{$parts}) {
 7276:                 my $lines;
 7277: 
 7278: 	        # TODO - make this a persistent hash not an array.
 7279: 
 7280:                 # optionresponse, matchresponse and rankresponse type items 
 7281:                 # render as separate sub-questions in exam mode.
 7282:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7283:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7284:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7285:                     my ($numbub,$numshown);
 7286:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7287:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7288:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7289:                         }
 7290:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7291:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7292:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7293:                         }
 7294:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7295:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7296:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7297:                         }
 7298:                     }
 7299:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7300:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7301:                     }
 7302:                     my $bubbles_per_line = 10;
 7303:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7304:                     if (($numbub % $bubbles_per_line) != 0) {
 7305:                         $inner_bubble_lines++;
 7306:                     }
 7307:                     for (my $i=0; $i<$numshown; $i++) {
 7308:                         $subdivided_bubble_lines{$response_number} .= 
 7309:                             $inner_bubble_lines.',';
 7310:                     }
 7311:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7312:                     $lines = $numshown * $inner_bubble_lines;
 7313:                 } else {
 7314:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7315:                 } 
 7316: 
 7317:                 $first_bubble_line{$response_number} = $bubble_line;
 7318: 	        $bubble_lines_per_response{$response_number} = $lines;
 7319:                 $responsetype_per_response{$response_number} = 
 7320:                     $analysis->{$part_id.'.type'};
 7321: 	        $response_number++;
 7322: 
 7323: 	        $bubble_line +=  $lines;
 7324: 	        $total_lines +=  $lines;
 7325: 	    }
 7326:         }
 7327:     }
 7328:     &Apache::lonnet::delenv('scantron.');
 7329: 
 7330:     &save_bubble_lines();
 7331:     $env{'form.scantron_maxbubble'} =
 7332: 	$total_lines;
 7333:     return $env{'form.scantron_maxbubble'};
 7334: }
 7335: 
 7336: sub scantron_validate_missingbubbles {
 7337:     my ($r,$currentphase) = @_;
 7338:     #get student info
 7339:     my $classlist=&Apache::loncoursedata::get_classlist();
 7340:     my %idmap=&username_to_idmap($classlist);
 7341: 
 7342:     #get scantron line setup
 7343:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7344:     my ($scanlines,$scan_data)=&scantron_getfile();
 7345:     my $max_bubble=&scantron_get_maxbubble();
 7346:     if (!$max_bubble) { $max_bubble=2**31; }
 7347:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7348: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7349: 	if ($line=~/^[\s\cz]*$/) { next; }
 7350: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7351: 						 $scan_data);
 7352: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7353: 	my @to_correct;
 7354: 	
 7355: 	# Probably here's where the error is...
 7356: 
 7357: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7358:             my $lastbubble;
 7359:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7360:                my $question = $1;
 7361:                my $subquestion = $2;
 7362:                if (!defined($first_bubble_line{$question -1})) { next; }
 7363:                my $first = $first_bubble_line{$question-1};
 7364:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7365:                my $subcount = 1;
 7366:                while ($subcount<$subquestion) {
 7367:                    $first += $subans[$subcount-1];
 7368:                    $subcount ++;
 7369:                }
 7370:                my $count = $subans[$subquestion-1];
 7371:                $lastbubble = $first + $count;
 7372:             } else {
 7373:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7374:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7375:             }
 7376:             if ($lastbubble > $max_bubble) { next; }
 7377: 	    push(@to_correct,$missing);
 7378: 	}
 7379: 	if (@to_correct) {
 7380: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7381: 				     $line,'missingbubble',\@to_correct);
 7382: 	    return (1,$currentphase);
 7383: 	}
 7384: 
 7385:     }
 7386:     return (0,$currentphase+1);
 7387: }
 7388: 
 7389: 
 7390: sub scantron_process_students {
 7391:     my ($r) = @_;
 7392: 
 7393:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7394:     my ($symb)=&get_symb($r);
 7395:     if (!$symb) {
 7396: 	return '';
 7397:     }
 7398:     my $default_form_data=&defaultFormData($symb);
 7399: 
 7400:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7401:     my ($scanlines,$scan_data)=&scantron_getfile();
 7402:     my $classlist=&Apache::loncoursedata::get_classlist();
 7403:     my %idmap=&username_to_idmap($classlist);
 7404:     my $navmap=Apache::lonnavmaps::navmap->new();
 7405:     my $map=$navmap->getResourceByUrl($sequence);
 7406:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7407: #    $r->print("geto ".scalar(@resources)."<br />");
 7408:     my ($uname,$udom);
 7409:     my $result= <<SCANTRONFORM;
 7410: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7411:   <input type="hidden" name="command" value="scantron_configphase" />
 7412:   $default_form_data
 7413: SCANTRONFORM
 7414:     $r->print($result);
 7415: 
 7416:     my @delayqueue;
 7417:     my (%completedstudents,%scandata);
 7418:     
 7419:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7420:     my $count=&get_todo_count($scanlines,$scan_data);
 7421:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7422:  				    'Scantron Progress',$count,
 7423: 				    'inline',undef,'scantronupload');
 7424:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7425: 					  'Processing first student');
 7426:     $r->print('<br />');
 7427:     my $start=&Time::HiRes::time();
 7428:     my $i=-1;
 7429:     my $started;
 7430: 
 7431:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7432: 
 7433:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7434:     # the user and return.
 7435: 
 7436:     if ($ssi_error) {
 7437: 	$r->print("</form>");
 7438: 	&ssi_print_error($r);
 7439: 	$r->print(&show_grading_menu_form($symb));
 7440:         &Apache::lonnet::remove_lock($lock);
 7441: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7442:     }
 7443: 
 7444:     my %lettdig = &letter_to_digits();
 7445:     my $numletts = scalar(keys(%lettdig));
 7446: 
 7447:     while ($i<$scanlines->{'count'}) {
 7448:  	($uname,$udom)=('','');
 7449:  	$i++;
 7450:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7451:  	if ($line=~/^[\s\cz]*$/) { next; }
 7452: 	if ($started) {
 7453: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7454: 						     'last student');
 7455: 	}
 7456: 	$started=1;
 7457:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7458:  						 $scan_data);
 7459:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7460:  					      \%idmap,$i)) {
 7461:   	    &scantron_add_delay(\@delayqueue,$line,
 7462:  				'Unable to find a student that matches',1);
 7463:  	    next;
 7464:   	}
 7465:  	if (exists $completedstudents{$uname}) {
 7466:  	    &scantron_add_delay(\@delayqueue,$line,
 7467:  				'Student '.$uname.' has multiple sheets',2);
 7468:  	    next;
 7469:  	}
 7470:   	($uname,$udom)=split(/:/,$uname);
 7471: 
 7472:         my %partids_by_symb;
 7473:         foreach my $resource (@resources) {
 7474:             my $ressymb = $resource->symb();
 7475:             my ($analysis,$parts) =
 7476:                 &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);            $partids_by_symb{$ressymb} = $parts;
 7477:         }
 7478: 
 7479: 	&Apache::lonxml::clear_problem_counter();
 7480:   	&Apache::lonnet::appenv($scan_record);
 7481: 
 7482: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7483: 	    &scantron_putfile($scanlines,$scan_data);
 7484: 	}
 7485: 	
 7486:         my $scancode;
 7487:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7488:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7489:             $scancode = $scan_record->{'scantron.CODE'};
 7490:         } else {
 7491:             $scancode = '';
 7492:         }
 7493: 
 7494:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7495:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
 7496:             $ssi_error = 0; # So end of handler error message does not trigger.
 7497:             $r->print("</form>");
 7498:             &ssi_print_error($r);
 7499:             $r->print(&show_grading_menu_form($symb));
 7500:             &Apache::lonnet::remove_lock($lock);
 7501:             return '';      # Why return ''?  Beats me.
 7502:         }
 7503: 
 7504: 	$completedstudents{$uname}={'line'=>$line};
 7505:         if ($env{'form.verifyrecord'}) {
 7506:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7507:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7508:             chomp($studentdata);
 7509:             $studentdata =~ s/\r$//;
 7510:             my $studentrecord = '';
 7511:             my $counter = -1;
 7512:             foreach my $resource (@resources) {
 7513:                 my $ressymb = $resource->symb();
 7514:                 ($counter,my $recording) =
 7515:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7516:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
 7517:                                              \%scantron_config,\%lettdig,$numletts);
 7518:                 $studentrecord .= $recording;
 7519:             }
 7520:             if ($studentrecord ne $studentdata) {
 7521:                 &Apache::lonxml::clear_problem_counter();
 7522:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7523:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
 7524:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7525:                     $r->print("</form>");
 7526:                     &ssi_print_error($r);
 7527:                     $r->print(&show_grading_menu_form($symb));
 7528:                     &Apache::lonnet::remove_lock($lock);
 7529:                     delete($completedstudents{$uname});
 7530:                     return '';
 7531:                 }
 7532:                 $counter = -1;
 7533:                 $studentrecord = '';
 7534:                 foreach my $resource (@resources) {
 7535:                     my $ressymb = $resource->symb();
 7536:                     ($counter,my $recording) =
 7537:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7538:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
 7539:                                                  \%scantron_config,\%lettdig,$numletts);
 7540:                     $studentrecord .= $recording;
 7541:                 }
 7542:                 if ($studentrecord ne $studentdata) {
 7543:                     $r->print('<p><span class="LC_error">');
 7544:                     if ($scancode eq '') {
 7545:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7546:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7547:                     } else {
 7548:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7549:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7550:                     }
 7551:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7552:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7553:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7554:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7555:                               &Apache::loncommon::start_data_table_row().
 7556:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7557:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7558:                               &Apache::loncommon::end_data_table_row().
 7559:                               &Apache::loncommon::start_data_table_row().
 7560:                               '<td>Stored submissions</td>'.
 7561:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7562:                               &Apache::loncommon::end_data_table_row().
 7563:                               &Apache::loncommon::end_data_table().'</p>');
 7564:                 } else {
 7565:                     $r->print('<br /><span class="LC_warning">'.
 7566:                              &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 />'.
 7567:                              &mt("As a consequence, this user's submission history records two tries.").
 7568:                                  '</span><br />');
 7569:                 }
 7570:             }
 7571:         }
 7572:         if (&Apache::loncommon::connection_aborted($r)) { last; }
 7573:     } continue {
 7574: 	&Apache::lonxml::clear_problem_counter();
 7575: 	&Apache::lonnet::delenv('scantron.');
 7576:     }
 7577:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7578:     &Apache::lonnet::remove_lock($lock);
 7579: #    my $lasttime = &Time::HiRes::time()-$start;
 7580: #    $r->print("<p>took $lasttime</p>");
 7581: 
 7582:     $r->print("</form>");
 7583:     $r->print(&show_grading_menu_form($symb));
 7584:     return '';
 7585: }
 7586: 
 7587: sub grade_student_bubbles {
 7588:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
 7589:     if (ref($resources) eq 'ARRAY') {
 7590:         my $count = 0;
 7591:         foreach my $resource (@{$resources}) {
 7592:             my $ressymb = $resource->symb();
 7593:             my %form = ('submitted'      => 'scantron',
 7594:                         'grade_target'   => 'grade',
 7595:                         'grade_username' => $uname,
 7596:                         'grade_domain'   => $udom,
 7597:                         'grade_courseid' => $env{'request.course.id'},
 7598:                         'grade_symb'     => $ressymb,
 7599:                         'CODE'           => $scancode
 7600:                        );
 7601:             if (ref($parts) eq 'HASH') {
 7602:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
 7603:                     foreach my $part (@{$parts->{$ressymb}}) {
 7604:                         $form{'scantron_questnum_start.'.$part} =
 7605:                             1+$env{'form.scantron.first_bubble_line.'.$count};
 7606:                         $count++;
 7607:                     }
 7608:                 }
 7609:             }
 7610:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7611:             return 'ssi_error' if ($ssi_error);
 7612:             last if (&Apache::loncommon::connection_aborted($r));
 7613:         }
 7614:     }
 7615:     return;
 7616: }
 7617: 
 7618: sub scantron_upload_scantron_data {
 7619:     my ($r)=@_;
 7620:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7621:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7622: 							  'domainid',
 7623: 							  'coursename');
 7624:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7625: 						   'domainid');
 7626:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7627:     $r->print('
 7628: <script type="text/javascript" language="javascript">
 7629:     function checkUpload(formname) {
 7630: 	if (formname.upfile.value == "") {
 7631: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7632: 	    return false;
 7633: 	}
 7634: 	formname.submit();
 7635:     }
 7636: </script>
 7637: 
 7638: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7639: '.$default_form_data.'
 7640: <table>
 7641: <tr><td>'.$select_link.'                             </td></tr>
 7642: <tr><td>'.&mt('Course ID:').'     </td>
 7643:     <td><input name="courseid"   type="text" />      </td></tr>
 7644: <tr><td>'.&mt('Course Name:').'   </td>
 7645:     <td><input name="coursename" type="text" />      </td></tr>
 7646: <tr><td>'.&mt('Domain:').'        </td>
 7647:     <td>'.$domsel.'                                  </td></tr>
 7648: <tr><td>'.&mt('File to upload:').'</td>
 7649:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7650: </table>
 7651: <input name="command" value="scantronupload_save" type="hidden" />
 7652: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7653: </form>
 7654: ');
 7655:     return '';
 7656: }
 7657: 
 7658: 
 7659: sub scantron_upload_scantron_data_save {
 7660:     my($r)=@_;
 7661:     my ($symb)=&get_symb($r,1);
 7662:     my $doanotherupload=
 7663: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7664: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7665: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7666: 	'</form>'."\n";
 7667:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7668: 	!&Apache::lonnet::allowed('usc',
 7669: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7670: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7671: 	if ($symb) {
 7672: 	    $r->print(&show_grading_menu_form($symb));
 7673: 	} else {
 7674: 	    $r->print($doanotherupload);
 7675: 	}
 7676: 	return '';
 7677:     }
 7678:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7679:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7680:     my $fname=$env{'form.upfile.filename'};
 7681:     #FIXME
 7682:     #copied from lonnet::userfileupload()
 7683:     #make that function able to target a specified course
 7684:     # Replace Windows backslashes by forward slashes
 7685:     $fname=~s/\\/\//g;
 7686:     # Get rid of everything but the actual filename
 7687:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7688:     # Replace spaces by underscores
 7689:     $fname=~s/\s+/\_/g;
 7690:     # Replace all other weird characters by nothing
 7691:     $fname=~s/[^\w\.\-]//g;
 7692:     # See if there is anything left
 7693:     unless ($fname) { return 'error: no uploaded file'; }
 7694:     my $uploadedfile=$fname;
 7695:     $fname='scantron_orig_'.$fname;
 7696:     if (length($env{'form.upfile'}) < 2) {
 7697: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7698:     } else {
 7699: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7700: 	if ($result =~ m|^/uploaded/|) {
 7701: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7702: 			  (length($env{'form.upfile'})-1),
 7703: 			  '<span class="LC_filename">'.$result."</span>"));
 7704: 	} else {
 7705: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7706: 			  $result,
 7707: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7708: 
 7709: 	}
 7710:     }
 7711:     if ($symb) {
 7712: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7713:     } else {
 7714: 	$r->print($doanotherupload);
 7715:     }
 7716:     return '';
 7717: }
 7718: 
 7719: sub valid_file {
 7720:     my ($requested_file)=@_;
 7721:     foreach my $filename (sort(&scantron_filenames())) {
 7722: 	if ($requested_file eq $filename) { return 1; }
 7723:     }
 7724:     return 0;
 7725: }
 7726: 
 7727: sub scantron_download_scantron_data {
 7728:     my ($r)=@_;
 7729:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7730:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7731:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7732:     my $file=$env{'form.scantron_selectfile'};
 7733:     if (! &valid_file($file)) {
 7734: 	$r->print('
 7735: 	<p>
 7736: 	    '.&mt('The requested file name was invalid.').'
 7737:         </p>
 7738: ');
 7739: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7740: 	return;
 7741:     }
 7742:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7743:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7744:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7745:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7746:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7747:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7748:     $r->print('
 7749:     <p>
 7750: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7751: 	      '<a href="'.$orig.'">','</a>').'
 7752:     </p>
 7753:     <p>
 7754: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7755: 	      '<a href="'.$corrected.'">','</a>').'
 7756:     </p>
 7757:     <p>
 7758: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7759: 	      '<a href="'.$skipped.'">','</a>').'
 7760:     </p>
 7761: ');
 7762:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7763:     return '';
 7764: }
 7765: 
 7766: sub checkscantron_results {
 7767:     my ($r) = @_;
 7768:     my ($symb)=&get_symb($r);
 7769:     if (!$symb) {return '';}
 7770:     my $grading_menu_button=&show_grading_menu_form($symb);
 7771:     my $cid = $env{'request.course.id'};
 7772:     my %lettdig = &letter_to_digits();
 7773:     my $numletts = scalar(keys(%lettdig));
 7774:     my $cnum = $env{'course.'.$cid.'.num'};
 7775:     my $cdom = $env{'course.'.$cid.'.domain'};
 7776:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7777:     my %record;
 7778:     my %scantron_config =
 7779:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7780:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7781:     my $classlist=&Apache::loncoursedata::get_classlist();
 7782:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7783:     my $navmap=Apache::lonnavmaps::navmap->new();
 7784:     my $map=$navmap->getResourceByUrl($sequence);
 7785:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7786:     my ($uname,$udom);
 7787:     my (%scandata,%lastname,%bylast);
 7788:     $r->print('
 7789: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7790: 
 7791:     my @delayqueue;
 7792:     my %completedstudents;
 7793: 
 7794:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7795:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7796:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7797:                                     'inline',undef,'checkscantron');
 7798:     my ($username,$domain,$started);
 7799: 
 7800:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7801: 
 7802:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7803:                                           'Processing first student');
 7804:     my $start=&Time::HiRes::time();
 7805:     my $i=-1;
 7806: 
 7807:     while ($i<$scanlines->{'count'}) {
 7808:         ($username,$domain,$uname)=('','','');
 7809:         $i++;
 7810:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7811:         if ($line=~/^[\s\cz]*$/) { next; }
 7812:         if ($started) {
 7813:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7814:                                                      'last student');
 7815:         }
 7816:         $started=1;
 7817:         my $scan_record=
 7818:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7819:                                                      $scan_data);
 7820:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7821:                                                               \%idmap,$i)) {
 7822:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7823:                                 'Unable to find a student that matches',1);
 7824:             next;
 7825:         }
 7826:         if (exists $completedstudents{$uname}) {
 7827:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7828:                                 'Student '.$uname.' has multiple sheets',2);
 7829:             next;
 7830:         }
 7831:         my $pid = $scan_record->{'scantron.ID'};
 7832:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7833:         push(@{$bylast{$lastname{$pid}}},$pid);
 7834:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7835:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7836:         chomp($scandata{$pid});
 7837:         $scandata{$pid} =~ s/\r$//;
 7838:         ($username,$domain)=split(/:/,$uname);
 7839:         my $counter = -1;
 7840:         foreach my $resource (@resources) {
 7841:             my $ressymb = $resource->symb();
 7842:             my ($analysis,$parts) =
 7843:                 &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
 7844:             ($counter,my $recording) =
 7845:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7846:                                          $scandata{$pid},$parts,
 7847:                                          \%scantron_config,\%lettdig,$numletts);
 7848:             $record{$pid} .= $recording;
 7849:         }
 7850:     }
 7851:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7852:     $r->print('<br />');
 7853:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7854:     $passed = 0;
 7855:     $failed = 0;
 7856:     $numstudents = 0;
 7857:     foreach my $last (sort(keys(%bylast))) {
 7858:         if (ref($bylast{$last}) eq 'ARRAY') {
 7859:             foreach my $pid (sort(@{$bylast{$last}})) {
 7860:                 my $showscandata = $scandata{$pid};
 7861:                 my $showrecord = $record{$pid};
 7862:                 $showscandata =~ s/\s/&nbsp;/g;
 7863:                 $showrecord =~ s/\s/&nbsp;/g;
 7864:                 if ($scandata{$pid} eq $record{$pid}) {
 7865:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 7866:                     $okstudents .= '<tr class="'.$css_class.'">'.
 7867: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7868: '</tr>'."\n".
 7869: '<tr class="'.$css_class.'">'."\n".
 7870: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 7871:                     $passed ++;
 7872:                 } else {
 7873:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 7874:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 7875: '</tr>'."\n".
 7876: '<tr class="'.$css_class.'">'."\n".
 7877: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 7878: '</tr>'."\n";
 7879:                     $failed ++;
 7880:                 }
 7881:                 $numstudents ++;
 7882:             }
 7883:         }
 7884:     }
 7885:     $r->print('<p>'.&mt('Comparison of scantron 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>');
 7886:     $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>');
 7887:     if ($passed) {
 7888:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 7889:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7890:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7891:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7892:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7893:                  $okstudents."\n".
 7894:                  &Apache::loncommon::end_data_table().'<br />');
 7895:     }
 7896:     if ($failed) {
 7897:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 7898:         $r->print(&Apache::loncommon::start_data_table()."\n".
 7899:                  &Apache::loncommon::start_data_table_header_row()."\n".
 7900:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 7901:                  &Apache::loncommon::end_data_table_header_row()."\n".
 7902:                  $badstudents."\n".
 7903:                  &Apache::loncommon::end_data_table()).'<br />'.
 7904:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 7905:     }
 7906:     $r->print('</form><br />'.$grading_menu_button);
 7907:     return;
 7908: }
 7909: 
 7910: sub verify_scantron_grading {
 7911:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
 7912:         $scantron_config,$lettdig,$numletts) = @_;
 7913:     my ($record,%expected,%startpos);
 7914:     return ($counter,$record) if (!ref($resource));
 7915:     return ($counter,$record) if (!$resource->is_problem());
 7916:     my $symb = $resource->symb();
 7917:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
 7918:     foreach my $part_id (@{$partids}) {
 7919:         $counter ++;
 7920:         $expected{$part_id} = 0;
 7921:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7922:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7923:             foreach my $item (@sub_lines) {
 7924:                 $expected{$part_id} += $item;
 7925:             }
 7926:         } else {
 7927:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7928:         }
 7929:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7930:     }
 7931:     if ($symb) {
 7932:         my %recorded;
 7933:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7934:         if ($returnhash{'version'}) {
 7935:             my %lasthash=();
 7936:             my $version;
 7937:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 7938:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7939:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 7940:                 }
 7941:             }
 7942:             foreach my $key (keys(%lasthash)) {
 7943:                 if ($key =~ /\.scantron$/) {
 7944:                     my $value = &unescape($lasthash{$key});
 7945:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7946:                     if ($value eq '') {
 7947:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 7948:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 7949:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 7950:                             }
 7951:                         }
 7952:                     } else {
 7953:                         my @tocheck;
 7954:                         my @items = split(//,$value);
 7955:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 7956:                             ($scantron_config->{'Qon'} eq 'number')) {
 7957:                             if (@items < $expected{$part_id}) {
 7958:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 7959:                                 my @singles = split(//,$fragment);
 7960:                                 foreach my $pos (@singles) {
 7961:                                     if ($pos eq ' ') {
 7962:                                         push(@tocheck,$pos);
 7963:                                     } else {
 7964:                                         my $next = shift(@items);
 7965:                                         push(@tocheck,$next);
 7966:                                     }
 7967:                                 }
 7968:                             } else {
 7969:                                 @tocheck = @items;
 7970:                             }
 7971:                             foreach my $letter (@tocheck) {
 7972:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 7973:                                     if ($letter !~ /^[A-J]$/) {
 7974:                                         $letter = $scantron_config->{'Qoff'};
 7975:                                     }
 7976:                                     $recorded{$part_id} .= $letter;
 7977:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 7978:                                     my $digit;
 7979:                                     if ($letter !~ /^[A-J]$/) {
 7980:                                         $digit = $scantron_config->{'Qoff'};
 7981:                                     } else {
 7982:                                         $digit = $lettdig->{$letter};
 7983:                                     }
 7984:                                     $recorded{$part_id} .= $digit;
 7985:                                 }
 7986:                             }
 7987:                         } else {
 7988:                             @tocheck = @items;
 7989:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 7990:                                 my $curr_sub = shift(@tocheck);
 7991:                                 my $digit;
 7992:                                 if ($curr_sub =~ /^[A-J]$/) {
 7993:                                     $digit = $lettdig->{$curr_sub}-1;
 7994:                                 }
 7995:                                 if ($curr_sub eq 'J') {
 7996:                                     $digit += scalar($numletts);
 7997:                                 }
 7998:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 7999:                                     if ($j == $digit) {
 8000:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8001:                                     } else {
 8002:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8003:                                     }
 8004:                                 }
 8005:                             }
 8006:                         }
 8007:                     }
 8008:                 }
 8009:             }
 8010:         }
 8011:         foreach my $part_id (@{$partids}) {
 8012:             if ($recorded{$part_id} eq '') {
 8013:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8014:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8015:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8016:                     }
 8017:                 }
 8018:             }
 8019:             $record .= $recorded{$part_id};
 8020:         }
 8021:     }
 8022:     return ($counter,$record);
 8023: }
 8024: 
 8025: sub letter_to_digits { 
 8026:     my %lettdig = (
 8027:                     A => 1,
 8028:                     B => 2,
 8029:                     C => 3,
 8030:                     D => 4,
 8031:                     E => 5,
 8032:                     F => 6,
 8033:                     G => 7,
 8034:                     H => 8,
 8035:                     I => 9,
 8036:                     J => 0,
 8037:                   );
 8038:     return %lettdig;
 8039: }
 8040: 
 8041: 
 8042: #-------- end of section for handling grading scantron forms -------
 8043: #
 8044: #-------------------------------------------------------------------
 8045: 
 8046: #-------------------------- Menu interface -------------------------
 8047: #
 8048: #--- Show a Grading Menu button - Calls the next routine ---
 8049: sub show_grading_menu_form {
 8050:     my ($symb)=@_;
 8051:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8052: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8053: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8054: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8055: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8056: 	'</form>'."\n";
 8057:     return $result;
 8058: }
 8059: 
 8060: # -- Retrieve choices for grading form
 8061: sub savedState {
 8062:     my %savedState = ();
 8063:     if ($env{'form.saveState'}) {
 8064: 	foreach (split(/:/,$env{'form.saveState'})) {
 8065: 	    my ($key,$value) = split(/=/,$_,2);
 8066: 	    $savedState{$key} = $value;
 8067: 	}
 8068:     }
 8069:     return \%savedState;
 8070: }
 8071: 
 8072: sub grading_menu {
 8073:     my ($request) = @_;
 8074:     my ($symb)=&get_symb($request);
 8075:     if (!$symb) {return '';}
 8076:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8077:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8078: 
 8079:     $request->print($table);
 8080:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8081:                   'handgrade'=>$hdgrade,
 8082:                   'probTitle'=>$probTitle,
 8083:                   'command'=>'submit_options',
 8084:                   'saveState'=>"",
 8085:                   'gradingMenu'=>1,
 8086:                   'showgrading'=>"yes");
 8087:     
 8088:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8089:     
 8090:     $fields{'command'} = 'csvform';
 8091:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8092:     
 8093:     $fields{'command'} = 'processclicker';
 8094:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8095:     
 8096:     $fields{'command'} = 'scantron_selectphase';
 8097:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8098:     
 8099:     my @menu = ({	categorytitle=>'Course Grading',
 8100:             items =>[
 8101:                         {	linktext => 'Manual Grading/View Submissions',
 8102:                     		url => $url1,
 8103:                     		permission => 'F',
 8104:                     		icon => 'edit-find-replace.png',
 8105:                     		linktitle => 'Start the process of hand grading submissions.'
 8106:                         },
 8107:                 	    {	linktext => 'Upload Scores',
 8108:                     		url => $url2,
 8109:                     		permission => 'F',
 8110:                     		icon => 'uploadscores.png',
 8111:                     		linktitle => 'Specify a file containing the class scores for current resource.'
 8112:                 	    },
 8113:                 	    {	linktext => 'Process Clicker',
 8114:                     		url => $url3,
 8115:                     		permission => 'F',
 8116:                     		icon => 'addClickerInfoFile.png',
 8117:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
 8118:                 	    },
 8119:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
 8120:                     		url => $url4,
 8121:                     		permission => 'F',
 8122:                     		icon => 'stat.png',
 8123:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
 8124:                 	    }
 8125:                     ]
 8126:             });
 8127: 
 8128:     #$fields{'command'} = 'verify';
 8129:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8130:     #
 8131:     # Create the menu
 8132:     my $Str;
 8133:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8134:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8135:     $Str .= '<input type="hidden" name="command" value="" />'.
 8136:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8137: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8138: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8139: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8140: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8141: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8142: 
 8143:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
 8144:     #$menudata->{'jscript'}
 8145:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8146:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8147:         ' /> '.
 8148:         &Apache::lonnet::recprefix($env{'request.course.id'}).
 8149:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8150: 
 8151:     $Str .="</form>\n";
 8152:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8153:     $request->print(<<GRADINGMENUJS);
 8154: <script type="text/javascript" language="javascript">
 8155:     function checkChoice(formname,val,cmdx) {
 8156: 	if (val <= 2) {
 8157: 	    var cmd = radioSelection(formname.radioChoice);
 8158: 	    var cmdsave = cmd;
 8159: 	} else {
 8160: 	    cmd = cmdx;
 8161: 	    cmdsave = 'submission';
 8162: 	}
 8163: 	formname.command.value = cmd;
 8164: 	if (val < 5) formname.submit();
 8165: 	if (val == 5) {
 8166: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8167: 	        return false;
 8168: 	    } else {
 8169: 	        formname.submit();
 8170: 	    }
 8171: 	}
 8172:     }
 8173: 
 8174:     function checkReceiptNo(formname,nospace) {
 8175: 	var receiptNo = formname.receipt.value;
 8176: 	var checkOpt = false;
 8177: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8178: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8179: 	if (checkOpt) {
 8180: 	    alert("$receiptalert");
 8181: 	    formname.receipt.value = "";
 8182: 	    formname.receipt.focus();
 8183: 	    return false;
 8184: 	}
 8185: 	return true;
 8186:     }
 8187: </script>
 8188: GRADINGMENUJS
 8189:     &commonJSfunctions($request);
 8190:     return $Str;    
 8191: }
 8192: 
 8193: 
 8194: #--- Displays the submissions first page -------
 8195: sub submit_options {
 8196:     my ($request) = @_;
 8197:     my ($symb)=&get_symb($request);
 8198:     if (!$symb) {return '';}
 8199:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8200: 
 8201:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8202:     $request->print(<<GRADINGMENUJS);
 8203: <script type="text/javascript" language="javascript">
 8204:     function checkChoice(formname,val,cmdx) {
 8205: 	if (val <= 2) {
 8206: 	    var cmd = radioSelection(formname.radioChoice);
 8207: 	    var cmdsave = cmd;
 8208: 	} else {
 8209: 	    cmd = cmdx;
 8210: 	    cmdsave = 'submission';
 8211: 	}
 8212: 	formname.command.value = cmd;
 8213: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8214: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8215: 	if (val < 5) formname.submit();
 8216: 	if (val == 5) {
 8217: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8218: 	    formname.submit();
 8219: 	}
 8220: 	if (val < 7) formname.submit();
 8221:     }
 8222: 
 8223:     function checkReceiptNo(formname,nospace) {
 8224: 	var receiptNo = formname.receipt.value;
 8225: 	var checkOpt = false;
 8226: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8227: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8228: 	if (checkOpt) {
 8229: 	    alert("$receiptalert");
 8230: 	    formname.receipt.value = "";
 8231: 	    formname.receipt.focus();
 8232: 	    return false;
 8233: 	}
 8234: 	return true;
 8235:     }
 8236: </script>
 8237: GRADINGMENUJS
 8238:     &commonJSfunctions($request);
 8239:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8240:     my $result;
 8241:     my (undef,$sections) = &getclasslist('all','0');
 8242:     my $savedState = &savedState();
 8243:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8244:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8245:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8246:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8247: 
 8248:     # Preselect sections
 8249:     my $selsec="";
 8250:     if (ref($sections)) {
 8251:         foreach my $section (sort(@$sections)) {
 8252:             $selsec.='<option value="'.$section.'" '.
 8253:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8254:         }
 8255:     }
 8256: 
 8257:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8258: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8259: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8260: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8261: 	'<input type="hidden" name="command"     value="" />'."\n".
 8262: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8263: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8264: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8265: 
 8266:     $result.='
 8267: <h2>
 8268:   '.&mt('Grade Current Resource').'
 8269: </h2>
 8270: <div>
 8271:   '.$table.'
 8272: </div>
 8273: 
 8274: <div class="LC_columnSection">
 8275:   
 8276:     <fieldset>
 8277:       <legend>
 8278:        '.&mt('Sections').'
 8279:       </legend>
 8280:       <select name="section" multiple="multiple" size="5">'."\n";
 8281:     $result.= $selsec;
 8282:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8283:     $result.='
 8284:     </fieldset>
 8285:   
 8286:     <fieldset>
 8287:       <legend>
 8288:         '.&mt('Groups').'
 8289:       </legend>
 8290:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8291:     </fieldset>
 8292:   
 8293:     <fieldset>
 8294:       <legend>
 8295:         '.&mt('Access Status').'
 8296:       </legend>
 8297:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8298:     </fieldset>
 8299:   
 8300:     <fieldset>
 8301:       <legend>
 8302:         '.&mt('Submission Status').'
 8303:       </legend>
 8304:       <select name="submitonly" size="5">
 8305: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8306: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8307: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8308: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8309:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8310:       </select>
 8311:     </fieldset>
 8312:   
 8313: </div>
 8314: 
 8315: <br />
 8316:           <div>
 8317:             <div>
 8318:               <label>
 8319:                 <input type="radio" name="radioChoice" value="submission" '.
 8320:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8321:              &mt('Select individual students to grade and view submissions.').'
 8322: 	      </label> 
 8323:             </div>
 8324:             <div>
 8325: 	      <label>
 8326:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8327:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8328:                     &mt('Grade all selected students in a grading table.').'
 8329:               </label>
 8330:             </div>
 8331:             <div>
 8332: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8333:             </div>
 8334:           </div>
 8335: 
 8336: 
 8337:         <h2>
 8338:          '.&mt('Grade Complete Folder for One Student').'
 8339:         </h2>
 8340:         <div>
 8341:             <div>
 8342:               <label>
 8343:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8344: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8345:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8346:               </label>
 8347:             </div>
 8348:             <div>
 8349: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8350:             </div>
 8351:         </div>
 8352:   </form>';
 8353:     $result .= &show_grading_menu_form($symb);
 8354:     return $result;
 8355: }
 8356: 
 8357: sub reset_perm {
 8358:     undef(%perm);
 8359: }
 8360: 
 8361: sub init_perm {
 8362:     &reset_perm();
 8363:     foreach my $test_perm ('vgr','mgr','opa') {
 8364: 
 8365: 	my $scope = $env{'request.course.id'};
 8366: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8367: 
 8368: 	    $scope .= '/'.$env{'request.course.sec'};
 8369: 	    if ( $perm{$test_perm}=
 8370: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8371: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8372: 	    } else {
 8373: 		delete($perm{$test_perm});
 8374: 	    }
 8375: 	}
 8376:     }
 8377: }
 8378: 
 8379: sub gather_clicker_ids {
 8380:     my %clicker_ids;
 8381: 
 8382:     my $classlist = &Apache::loncoursedata::get_classlist();
 8383: 
 8384:     # Set up a couple variables.
 8385:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8386:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8387:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8388: 
 8389:     foreach my $student (keys(%$classlist)) {
 8390:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8391:         my $username = $classlist->{$student}->[$username_idx];
 8392:         my $domain   = $classlist->{$student}->[$domain_idx];
 8393:         my $clickers =
 8394: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8395:         foreach my $id (split(/\,/,$clickers)) {
 8396:             $id=~s/^[\#0]+//;
 8397:             $id=~s/[\-\:]//g;
 8398:             if (exists($clicker_ids{$id})) {
 8399: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8400:             } else {
 8401: 		$clicker_ids{$id}=$username.':'.$domain;
 8402:             }
 8403:         }
 8404:     }
 8405:     return %clicker_ids;
 8406: }
 8407: 
 8408: sub gather_adv_clicker_ids {
 8409:     my %clicker_ids;
 8410:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8411:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8412:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8413:     foreach my $element (sort(keys(%coursepersonnel))) {
 8414:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8415:             my ($puname,$pudom)=split(/\:/,$person);
 8416:             my $clickers =
 8417: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8418:             foreach my $id (split(/\,/,$clickers)) {
 8419: 		$id=~s/^[\#0]+//;
 8420:                 $id=~s/[\-\:]//g;
 8421: 		if (exists($clicker_ids{$id})) {
 8422: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8423: 		} else {
 8424: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8425: 		}
 8426:             }
 8427:         }
 8428:     }
 8429:     return %clicker_ids;
 8430: }
 8431: 
 8432: sub clicker_grading_parameters {
 8433:     return ('gradingmechanism' => 'scalar',
 8434:             'upfiletype' => 'scalar',
 8435:             'specificid' => 'scalar',
 8436:             'pcorrect' => 'scalar',
 8437:             'pincorrect' => 'scalar');
 8438: }
 8439: 
 8440: sub process_clicker {
 8441:     my ($r)=@_;
 8442:     my ($symb)=&get_symb($r);
 8443:     if (!$symb) {return '';}
 8444:     my $result=&checkforfile_js();
 8445:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8446:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8447:     $result.=$table;
 8448:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8449:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8450:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8451:         '</b></td></tr>'."\n";
 8452:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8453: # Attempt to restore parameters from last session, set defaults if not present
 8454:     my %Saveable_Parameters=&clicker_grading_parameters();
 8455:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8456:                                                  \%Saveable_Parameters);
 8457:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8458:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8459:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8460:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8461: 
 8462:     my %checked;
 8463:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8464:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8465:           $checked{$gradingmechanism}="checked='checked'";
 8466:        }
 8467:     }
 8468: 
 8469:     my $upload=&mt("Upload File");
 8470:     my $type=&mt("Type");
 8471:     my $attendance=&mt("Award points just for participation");
 8472:     my $personnel=&mt("Correctness determined from response by course personnel");
 8473:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8474:     my $given=&mt("Correctness determined from given list of answers").' '.
 8475:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8476:     my $pcorrect=&mt("Percentage points for correct solution");
 8477:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8478:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8479: 						   ('iclicker' => 'i>clicker',
 8480:                                                     'interwrite' => 'interwrite PRS'));
 8481:     $symb = &Apache::lonenc::check_encrypt($symb);
 8482:     $result.=<<ENDUPFORM;
 8483: <script type="text/javascript">
 8484: function sanitycheck() {
 8485: // Accept only integer percentages
 8486:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8487:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8488: // Find out grading choice
 8489:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8490:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8491:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8492:       }
 8493:    }
 8494: // By default, new choice equals user selection
 8495:    newgradingchoice=gradingchoice;
 8496: // Not good to give more points for false answers than correct ones
 8497:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8498:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8499:    }
 8500: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8501:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8502:       document.forms.gradesupload.pcorrect.value=100;
 8503:       document.forms.gradesupload.pincorrect.value=100;
 8504:    }
 8505: // If the values are different, cannot be attendance only
 8506:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8507:        (gradingchoice=='attendance')) {
 8508:        newgradingchoice='personnel';
 8509:    }
 8510: // Change grading choice to new one
 8511:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8512:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8513:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8514:       } else {
 8515:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8516:       }
 8517:    }
 8518: // Remember the old state
 8519:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8520: }
 8521: </script>
 8522: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8523: <input type="hidden" name="symb" value="$symb" />
 8524: <input type="hidden" name="command" value="processclickerfile" />
 8525: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8526: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8527: <input type="file" name="upfile" size="50" />
 8528: <br /><label>$type: $selectform</label>
 8529: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8530: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8531: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8532: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8533: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8534: <br />&nbsp;&nbsp;&nbsp;
 8535: <input type="text" name="givenanswer" size="50" />
 8536: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8537: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8538: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8539: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8540: </form>
 8541: ENDUPFORM
 8542:     $result.='</td></tr></table>'."\n".
 8543:              '</td></tr></table><br /><br />'."\n";
 8544:     $result.=&show_grading_menu_form($symb);
 8545:     return $result;
 8546: }
 8547: 
 8548: sub process_clicker_file {
 8549:     my ($r)=@_;
 8550:     my ($symb)=&get_symb($r);
 8551:     if (!$symb) {return '';}
 8552: 
 8553:     my %Saveable_Parameters=&clicker_grading_parameters();
 8554:     &Apache::loncommon::store_course_settings('grades_clicker',
 8555:                                               \%Saveable_Parameters);
 8556: 
 8557:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8558:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8559: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8560: 	return $result.&show_grading_menu_form($symb);
 8561:     }
 8562:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8563:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8564:         return $result.&show_grading_menu_form($symb);
 8565:     }
 8566:     my $foundgiven=0;
 8567:     if ($env{'form.gradingmechanism'} eq 'given') {
 8568:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8569:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8570:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8571:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8572:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8573:         $foundgiven=$#answers+1;
 8574:     }
 8575:     my %clicker_ids=&gather_clicker_ids();
 8576:     my %correct_ids;
 8577:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8578: 	%correct_ids=&gather_adv_clicker_ids();
 8579:     }
 8580:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8581: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8582: 	   $correct_id=~tr/a-z/A-Z/;
 8583: 	   $correct_id=~s/\s//gs;
 8584: 	   $correct_id=~s/^[\#0]+//;
 8585:            $correct_id=~s/[\-\:]//g;
 8586:            if ($correct_id) {
 8587: 	      $correct_ids{$correct_id}='specified';
 8588:            }
 8589:         }
 8590:     }
 8591:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8592: 	$result.=&mt('Score based on attendance only');
 8593:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8594:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8595:     } else {
 8596: 	my $number=0;
 8597: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8598: 	foreach my $id (sort(keys(%correct_ids))) {
 8599: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8600: 	    if ($correct_ids{$id} eq 'specified') {
 8601: 		$result.=&mt('specified');
 8602: 	    } else {
 8603: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8604: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8605: 	    }
 8606: 	    $number++;
 8607: 	}
 8608:         $result.="</p>\n";
 8609: 	if ($number==0) {
 8610: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8611: 	    return $result.&show_grading_menu_form($symb);
 8612: 	}
 8613:     }
 8614:     if (length($env{'form.upfile'}) < 2) {
 8615:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8616: 		     '<span class="LC_error">',
 8617: 		     '</span>',
 8618: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8619:         return $result.&show_grading_menu_form($symb);
 8620:     }
 8621: 
 8622: # Were able to get all the info needed, now analyze the file
 8623: 
 8624:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8625:     $symb = &Apache::lonenc::check_encrypt($symb);
 8626:     my $heading=&mt('Scanning clicker file');
 8627:     $result.=(<<ENDHEADER);
 8628: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8629: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8630: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8631: <form method="post" action="/adm/grades" name="clickeranalysis">
 8632: <input type="hidden" name="symb" value="$symb" />
 8633: <input type="hidden" name="command" value="assignclickergrades" />
 8634: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8635: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8636: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8637: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8638: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8639: ENDHEADER
 8640:     if ($env{'form.gradingmechanism'} eq 'given') {
 8641:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8642:     } 
 8643:     my %responses;
 8644:     my @questiontitles;
 8645:     my $errormsg='';
 8646:     my $number=0;
 8647:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8648: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8649:     }
 8650:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8651:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8652:     }
 8653:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8654:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8655:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8656:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8657:              '<br />';
 8658:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8659:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8660:        return $result.&show_grading_menu_form($symb);
 8661:     } 
 8662: # Remember Question Titles
 8663: # FIXME: Possibly need delimiter other than ":"
 8664:     for (my $i=0;$i<$number;$i++) {
 8665:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8666:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8667:     }
 8668:     my $correct_count=0;
 8669:     my $student_count=0;
 8670:     my $unknown_count=0;
 8671: # Match answers with usernames
 8672: # FIXME: Possibly need delimiter other than ":"
 8673:     foreach my $id (keys(%responses)) {
 8674:        if ($correct_ids{$id}) {
 8675:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8676:           $correct_count++;
 8677:        } elsif ($clicker_ids{$id}) {
 8678:           if ($clicker_ids{$id}=~/\,/) {
 8679: # More than one user with the same clicker!
 8680:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8681:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8682:                            "<select name='multi".$id."'>";
 8683:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8684:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8685:              }
 8686:              $result.='</select>';
 8687:              $unknown_count++;
 8688:           } else {
 8689: # Good: found one and only one user with the right clicker
 8690:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8691:              $student_count++;
 8692:           }
 8693:        } else {
 8694:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8695:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8696:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8697:                    "\n".&mt("Domain").": ".
 8698:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8699:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8700:           $unknown_count++;
 8701:        }
 8702:     }
 8703:     $result.='<hr />'.
 8704:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8705:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8706:        if ($correct_count==0) {
 8707:           $errormsg.="Found no correct answers answers for grading!";
 8708:        } elsif ($correct_count>1) {
 8709:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8710:        }
 8711:     }
 8712:     if ($number<1) {
 8713:        $errormsg.="Found no questions.";
 8714:     }
 8715:     if ($errormsg) {
 8716:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8717:     } else {
 8718:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8719:     }
 8720:     $result.='</form></td></tr></table>'."\n".
 8721:              '</td></tr></table><br /><br />'."\n";
 8722:     return $result.&show_grading_menu_form($symb);
 8723: }
 8724: 
 8725: sub iclicker_eval {
 8726:     my ($questiontitles,$responses)=@_;
 8727:     my $number=0;
 8728:     my $errormsg='';
 8729:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8730:         my %components=&Apache::loncommon::record_sep($line);
 8731:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8732: 	if ($entries[0] eq 'Question') {
 8733: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8734: 		$$questiontitles[$number]=$entries[$i];
 8735: 		$number++;
 8736: 	    }
 8737: 	}
 8738: 	if ($entries[0]=~/^\#/) {
 8739: 	    my $id=$entries[0];
 8740: 	    my @idresponses;
 8741: 	    $id=~s/^[\#0]+//;
 8742: 	    for (my $i=0;$i<$number;$i++) {
 8743: 		my $idx=3+$i*6;
 8744: 		push(@idresponses,$entries[$idx]);
 8745: 	    }
 8746: 	    $$responses{$id}=join(',',@idresponses);
 8747: 	}
 8748:     }
 8749:     return ($errormsg,$number);
 8750: }
 8751: 
 8752: sub interwrite_eval {
 8753:     my ($questiontitles,$responses)=@_;
 8754:     my $number=0;
 8755:     my $errormsg='';
 8756:     my $skipline=1;
 8757:     my $questionnumber=0;
 8758:     my %idresponses=();
 8759:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8760:         my %components=&Apache::loncommon::record_sep($line);
 8761:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8762:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8763:         if ($entries[1] eq 'Response') { $skipline=1; }
 8764:         next if $skipline;
 8765:         if ($entries[0]!=$questionnumber) {
 8766:            $questionnumber=$entries[0];
 8767:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8768:            $number++;
 8769:         }
 8770:         my $id=$entries[4];
 8771:         $id=~s/^[\#0]+//;
 8772:         $id=~s/^v\d*\://i;
 8773:         $id=~s/[\-\:]//g;
 8774:         $idresponses{$id}[$number]=$entries[6];
 8775:     }
 8776:     foreach my $id (keys(%idresponses)) {
 8777:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8778:        $$responses{$id}=~s/^\s*\,//;
 8779:     }
 8780:     return ($errormsg,$number);
 8781: }
 8782: 
 8783: sub assign_clicker_grades {
 8784:     my ($r)=@_;
 8785:     my ($symb)=&get_symb($r);
 8786:     if (!$symb) {return '';}
 8787: # See which part we are saving to
 8788:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8789: # FIXME: This should probably look for the first handgradeable part
 8790:     my $part=$$partlist[0];
 8791: # Start screen output
 8792:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8793: 
 8794:     my $heading=&mt('Assigning grades based on clicker file');
 8795:     $result.=(<<ENDHEADER);
 8796: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8797: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8798: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8799: ENDHEADER
 8800: # Get correct result
 8801: # FIXME: Possibly need delimiter other than ":"
 8802:     my @correct=();
 8803:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8804:     my $number=$env{'form.number'};
 8805:     if ($gradingmechanism ne 'attendance') {
 8806:        foreach my $key (keys(%env)) {
 8807:           if ($key=~/^form\.correct\:/) {
 8808:              my @input=split(/\,/,$env{$key});
 8809:              for (my $i=0;$i<=$#input;$i++) {
 8810:                  if (($correct[$i]) && ($input[$i]) &&
 8811:                      ($correct[$i] ne $input[$i])) {
 8812:                     $result.='<br /><span class="LC_warning">'.
 8813:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8814:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8815:                  } elsif ($input[$i]) {
 8816:                     $correct[$i]=$input[$i];
 8817:                  }
 8818:              }
 8819:           }
 8820:        }
 8821:        for (my $i=0;$i<$number;$i++) {
 8822:           if (!$correct[$i]) {
 8823:              $result.='<br /><span class="LC_error">'.
 8824:                       &mt('No correct result given for question "[_1]"!',
 8825:                           $env{'form.question:'.$i}).'</span>';
 8826:           }
 8827:        }
 8828:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8829:     }
 8830: # Start grading
 8831:     my $pcorrect=$env{'form.pcorrect'};
 8832:     my $pincorrect=$env{'form.pincorrect'};
 8833:     my $storecount=0;
 8834:     foreach my $key (keys(%env)) {
 8835:        my $user='';
 8836:        if ($key=~/^form\.student\:(.*)$/) {
 8837:           $user=$1;
 8838:        }
 8839:        if ($key=~/^form\.unknown\:(.*)$/) {
 8840:           my $id=$1;
 8841:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8842:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8843:           } elsif ($env{'form.multi'.$id}) {
 8844:              $user=$env{'form.multi'.$id};
 8845:           }
 8846:        }
 8847:        if ($user) { 
 8848:           my @answer=split(/\,/,$env{$key});
 8849:           my $sum=0;
 8850:           my $realnumber=$number;
 8851:           for (my $i=0;$i<$number;$i++) {
 8852:              if ($answer[$i]) {
 8853:                 if ($gradingmechanism eq 'attendance') {
 8854:                    $sum+=$pcorrect;
 8855:                 } elsif ($answer[$i] eq '*') {
 8856:                    $sum+=$pcorrect;
 8857:                 } elsif ($answer[$i] eq '-') {
 8858:                    $realnumber--;
 8859:                 } else {
 8860:                    if ($answer[$i] eq $correct[$i]) {
 8861:                       $sum+=$pcorrect;
 8862:                    } else {
 8863:                       $sum+=$pincorrect;
 8864:                    }
 8865:                 }
 8866:              }
 8867:           }
 8868:           my $ave=$sum/(100*$realnumber);
 8869: # Store
 8870:           my ($username,$domain)=split(/\:/,$user);
 8871:           my %grades=();
 8872:           $grades{"resource.$part.solved"}='correct_by_override';
 8873:           $grades{"resource.$part.awarded"}=$ave;
 8874:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8875:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8876:                                                  $env{'request.course.id'},
 8877:                                                  $domain,$username);
 8878:           if ($returncode ne 'ok') {
 8879:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8880:           } else {
 8881:              $storecount++;
 8882:           }
 8883:        }
 8884:     }
 8885: # We are done
 8886:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 8887:              '</td></tr></table>'."\n".
 8888:              '</td></tr></table><br /><br />'."\n";
 8889:     return $result.&show_grading_menu_form($symb);
 8890: }
 8891: 
 8892: sub handler {
 8893:     my $request=$_[0];
 8894:     &reset_caches();
 8895:     if ($env{'browser.mathml'}) {
 8896: 	&Apache::loncommon::content_type($request,'text/xml');
 8897:     } else {
 8898: 	&Apache::loncommon::content_type($request,'text/html');
 8899:     }
 8900:     $request->send_http_header;
 8901:     return '' if $request->header_only;
 8902:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8903:     my $symb=&get_symb($request,1);
 8904:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8905:     my $command=$commands[0];
 8906: 
 8907:     if ($#commands > 0) {
 8908: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8909:     }
 8910: 
 8911:     $ssi_error = 0;
 8912:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
 8913:     $request->print(&Apache::loncommon::start_page('Grading',undef,
 8914:                                           {'bread_crumbs' => $brcrum}));
 8915:     if ($symb eq '' && $command eq '') {
 8916: 	if ($env{'user.adv'}) {
 8917: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8918: 		($env{'form.codethree'})) {
 8919: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8920: 		    $env{'form.codethree'};
 8921: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8922: 		    &Apache::lonnet::checkin($token);
 8923: 		if ($tsymb) {
 8924: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8925: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8926: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8927: 					  ('grade_username' => $tuname,
 8928: 					   'grade_domain' => $tudom,
 8929: 					   'grade_courseid' => $tcrsid,
 8930: 					   'grade_symb' => $tsymb)));
 8931: 		    } else {
 8932: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8933: 		    }
 8934: 		} else {
 8935: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8936: 		}
 8937: 	    } else {
 8938: 		$request->print(&Apache::lonxml::tokeninputfield());
 8939: 	    }
 8940: 	}
 8941:     } else {
 8942: 	&init_perm();
 8943: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8944: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8945: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8946: 	    &pickStudentPage($request);
 8947: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8948: 	    &displayPage($request);
 8949: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8950: 	    &updateGradeByPage($request);
 8951: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8952: 	    &processGroup($request);
 8953: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8954: 	    $request->print(&grading_menu($request));
 8955: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8956: 	    $request->print(&submit_options($request));
 8957: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8958: 	    $request->print(&viewgrades($request));
 8959: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8960: 	    $request->print(&processHandGrade($request));
 8961: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8962: 	    $request->print(&editgrades($request));
 8963: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8964: 	    $request->print(&verifyreceipt($request));
 8965:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8966:             $request->print(&process_clicker($request));
 8967:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8968:             $request->print(&process_clicker_file($request));
 8969:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8970:             $request->print(&assign_clicker_grades($request));
 8971: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8972: 	    $request->print(&upcsvScores_form($request));
 8973: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8974: 	    $request->print(&csvupload($request));
 8975: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8976: 	    $request->print(&csvuploadmap($request));
 8977: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8978: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8979: 		$request->print(&csvuploadoptions($request));
 8980: 	    } else {
 8981: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8982: 		    $env{'form.upfile_associate'} = 'reverse';
 8983: 		} else {
 8984: 		    $env{'form.upfile_associate'} = 'forward';
 8985: 		}
 8986: 		$request->print(&csvuploadmap($request));
 8987: 	    }
 8988: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8989: 	    $request->print(&csvuploadassign($request));
 8990: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8991: 	    $request->print(&scantron_selectphase($request));
 8992:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8993:  	    $request->print(&scantron_do_warning($request));
 8994: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8995: 	    $request->print(&scantron_validate_file($request));
 8996: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8997: 	    $request->print(&scantron_process_students($request));
 8998:  	} elsif ($command eq 'scantronupload' && 
 8999:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9000: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9001:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9002:  	} elsif ($command eq 'scantronupload_save' &&
 9003:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9004: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9005:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9006:  	} elsif ($command eq 'scantron_download' &&
 9007: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9008:  	    $request->print(&scantron_download_scantron_data($request));
 9009:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9010:             $request->print(&checkscantron_results($request));     
 9011: 	} elsif ($command) {
 9012: 	    $request->print("Access Denied ($command)");
 9013: 	}
 9014:     }
 9015:     if ($ssi_error) {
 9016: 	&ssi_print_error($request);
 9017:     }
 9018:     $request->print(&Apache::loncommon::end_page());
 9019:     &reset_caches();
 9020:     return '';
 9021: }
 9022: 
 9023: 1;
 9024: 
 9025: __END__;
 9026: 
 9027: 
 9028: =head1 NAME
 9029: 
 9030: Apache::grades
 9031: 
 9032: =head1 SYNOPSIS
 9033: 
 9034: Handles the viewing of grades.
 9035: 
 9036: This is part of the LearningOnline Network with CAPA project
 9037: described at http://www.lon-capa.org.
 9038: 
 9039: =head1 OVERVIEW
 9040: 
 9041: Do an ssi with retries:
 9042: While I'd love to factor out this with the vesrion in lonprintout,
 9043: 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
 9044: I'm not quite ready to invent (e.g. an ssi_with_retry object).
 9045: 
 9046: At least the logic that drives this has been pulled out into loncommon.
 9047: 
 9048: 
 9049: 
 9050: ssi_with_retries - Does the server side include of a resource.
 9051:                      if the ssi call returns an error we'll retry it up to
 9052:                      the number of times requested by the caller.
 9053:                      If we still have a proble, no text is appended to the
 9054:                      output and we set some global variables.
 9055:                      to indicate to the caller an SSI error occurred.  
 9056:                      All of this is supposed to deal with the issues described
 9057:                      in LonCAPA BZ 5631 see:
 9058:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 9059:                      by informing the user that this happened.
 9060: 
 9061: Parameters:
 9062:   resource   - The resource to include.  This is passed directly, without
 9063:                interpretation to lonnet::ssi.
 9064:   form       - The form hash parameters that guide the interpretation of the resource
 9065:                
 9066:   retries    - Number of retries allowed before giving up completely.
 9067: Returns:
 9068:   On success, returns the rendered resource identified by the resource parameter.
 9069: Side Effects:
 9070:   The following global variables can be set:
 9071:    ssi_error                - If an unrecoverable error occurred this becomes true.
 9072:                               It is up to the caller to initialize this to false
 9073:                               if desired.
 9074:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
 9075:                               of the resource that could not be rendered by the ssi
 9076:                               call.
 9077:    ssi_error_message   - The error string fetched from the ssi response
 9078:                               in the event of an error.
 9079: 
 9080: 
 9081: =head1 HANDLER SUBROUTINE
 9082: 
 9083: ssi_with_retries()
 9084: 
 9085: =head1 SUBROUTINES
 9086: 
 9087: =over
 9088: 
 9089: =item scantron_get_correction() : 
 9090: 
 9091:    Builds the interface screen to interact with the operator to fix a
 9092:    specific error condition in a specific scanline
 9093: 
 9094:  Arguments:
 9095:     $r           - Apache request object
 9096:     $i           - number of the current scanline
 9097:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 9098:     $scan_config - hash ref as returned from &get_scantron_config()
 9099:     $line        - full contents of the current scanline
 9100:     $error       - error condition, valid values are
 9101:                    'incorrectCODE', 'duplicateCODE',
 9102:                    'doublebubble', 'missingbubble',
 9103:                    'duplicateID', 'incorrectID'
 9104:     $arg         - extra information needed
 9105:        For errors:
 9106:          - duplicateID   - paper number that this studentID was seen before on
 9107:          - duplicateCODE - array ref of the paper numbers this CODE was
 9108:                            seen on before
 9109:          - incorrectCODE - current incorrect CODE 
 9110:          - doublebubble  - array ref of the bubble lines that have double
 9111:                            bubble errors
 9112:          - missingbubble - array ref of the bubble lines that have missing
 9113:                            bubble errors
 9114: 
 9115: =item  scantron_get_maxbubble() : 
 9116: 
 9117:    Returns the maximum number of bubble lines that are expected to
 9118:    occur. Does this by walking the selected sequence rendering the
 9119:    resource and then checking &Apache::lonxml::get_problem_counter()
 9120:    for what the current value of the problem counter is.
 9121: 
 9122:    Caches the results to $env{'form.scantron_maxbubble'},
 9123:    $env{'form.scantron.bubble_lines.n'}, 
 9124:    $env{'form.scantron.first_bubble_line.n'} and
 9125:    $env{"form.scantron.sub_bubblelines.n"}
 9126:    which are the total number of bubble, lines, the number of bubble
 9127:    lines for response n and number of the first bubble line for response n,
 9128:    and a comma separated list of numbers of bubble lines for sub-questions
 9129:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 9130: 
 9131: 
 9132: =item  scantron_validate_missingbubbles() : 
 9133: 
 9134:    Validates all scanlines in the selected file to not have any
 9135:     answers that don't have bubbles that have not been verified
 9136:     to be bubble free.
 9137: 
 9138: =item  scantron_process_students() : 
 9139: 
 9140:    Routine that does the actual grading of the bubble sheet information.
 9141: 
 9142:    The parsed scanline hash is added to %env 
 9143: 
 9144:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 9145:    foreach resource , with the form data of
 9146: 
 9147: 	'submitted'     =>'scantron' 
 9148: 	'grade_target'  =>'grade',
 9149: 	'grade_username'=> username of student
 9150: 	'grade_domain'  => domain of student
 9151: 	'grade_courseid'=> of course
 9152: 	'grade_symb'    => symb of resource to grade
 9153: 
 9154:     This triggers a grading pass. The problem grading code takes care
 9155:     of converting the bubbled letter information (now in %env) into a
 9156:     valid submission.
 9157: 
 9158: =item  scantron_upload_scantron_data() :
 9159: 
 9160:     Creates the screen for adding a new bubble sheet data file to a course.
 9161: 
 9162: =item  scantron_upload_scantron_data_save() : 
 9163: 
 9164:    Adds a provided bubble information data file to the course if user
 9165:    has the correct privileges to do so. 
 9166: 
 9167: =item  valid_file() :
 9168: 
 9169:    Validates that the requested bubble data file exists in the course.
 9170: 
 9171: =item  scantron_download_scantron_data() : 
 9172: 
 9173:    Shows a list of the three internal files (original, corrected,
 9174:    skipped) for a specific bubble sheet data file that exists in the
 9175:    course.
 9176: 
 9177: =item  scantron_validate_ID() : 
 9178: 
 9179:    Validates all scanlines in the selected file to not have any
 9180:    invalid or underspecified student/employee IDs
 9181: 
 9182: =back
 9183: 
 9184: =cut

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