File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.528.2.9: download - view: text, annotated - select for diffs
Wed Jan 7 21:33:25 2009 UTC (15 years, 3 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.528: preferred, unified
- Backport a part of 1.542 omitted in the original backport.
- Interface to enable the option to peform verification of scantron grading.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.528.2.9 2009/01/07 21:33:25 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::lonpickcode;
   39: use Apache::loncoursedata;
   40: use Apache::lonmsg();
   41: use Apache::Constants qw(:common);
   42: use Apache::lonlocal;
   43: use Apache::lonenc;
   44: use String::Similarity;
   45: use LONCAPA;
   46: 
   47: use POSIX qw(floor);
   48: 
   49: 
   50: 
   51: my %perm=();
   52: 
   53: #  These variables are used to recover from ssi errors
   54: 
   55: my $ssi_retries = 5;
   56: my $ssi_error;
   57: my $ssi_error_resource;
   58: my $ssi_error_message;
   59: 
   60: 
   61: #  Do an ssi with retries:
   62: #  While I'd love to factor out this with the vesrion in lonprintout,
   63: #  that would either require a data coupling between modules, which I refuse to perpetuate
   64: #  (there's quite enough of that already), or would require the invention of another infrastructure
   65: #  I'm not quite ready to invent (e.g. an ssi_with_retry object).
   66: #
   67: # At least the logic that drives this has been pulled out into loncommon.
   68: 
   69: 
   70: #
   71: #   ssi_with_retries - Does the server side include of a resource.
   72: #                      if the ssi call returns an error we'll retry it up to
   73: #                      the number of times requested by the caller.
   74: #                      If we still have a proble, no text is appended to the
   75: #                      output and we set some global variables.
   76: #                      to indicate to the caller an SSI error occurred.  
   77: #                      All of this is supposed to deal with the issues described
   78: #                      in LonCAPA BZ 5631 see:
   79: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
   80: #                      by informing the user that this happened.
   81: #
   82: # Parameters:
   83: #   resource   - The resource to include.  This is passed directly, without
   84: #                interpretation to lonnet::ssi.
   85: #   form       - The form hash parameters that guide the interpretation of the resource
   86: #                
   87: #   retries    - Number of retries allowed before giving up completely.
   88: # Returns:
   89: #   On success, returns the rendered resource identified by the resource parameter.
   90: # Side Effects:
   91: #   The following global variables can be set:
   92: #    ssi_error                - If an unrecoverable error occurred this becomes true.
   93: #                               It is up to the caller to initialize this to false
   94: #                               if desired.
   95: #    ssi_error_resource  - If an unrecoverable error occurred, this is the value
   96: #                               of the resource that could not be rendered by the ssi
   97: #                               call.
   98: #    ssi_error_message   - The error string fetched from the ssi response
   99: #                               in the event of an error.
  100: #
  101: sub ssi_with_retries {
  102:     my ($resource, $retries, %form) = @_;
  103:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  104:     if ($response->is_error) {
  105: 	$ssi_error          = 1;
  106: 	$ssi_error_resource = $resource;
  107: 	$ssi_error_message  = $response->code . " " . $response->message;
  108:     }
  109: 
  110:     return $content;
  111: 
  112: }
  113: #
  114: #  Prodcuces an ssi retry failure error message to the user:
  115: #
  116: 
  117: sub ssi_print_error {
  118:     my ($r) = @_;
  119:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
  120:     $r->print('
  121: <br />
  122: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
  123: <p>
  124: '.&mt('Unable to retrieve a resource from a server:').'<br />
  125: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
  126: '.&mt('Error:').' '.$ssi_error_message.'
  127: </p>
  128: <p>'.
  129: &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 />'.
  130: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  131: '</p>');
  132:     return;
  133: }
  134: 
  135: #
  136: # --- Retrieve the parts from the metadata file.---
  137: sub getpartlist {
  138:     my ($symb) = @_;
  139: 
  140:     my $navmap   = Apache::lonnavmaps::navmap->new();
  141:     my $res      = $navmap->getBySymb($symb);
  142:     my $partlist = $res->parts();
  143:     my $url      = $res->src();
  144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  145: 
  146:     my @stores;
  147:     foreach my $part (@{ $partlist }) {
  148: 	foreach my $key (@metakeys) {
  149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  150: 	}
  151:     }
  152:     return @stores;
  153: }
  154: 
  155: # --- Get the symbolic name of a problem and the url
  156: sub get_symb {
  157:     my ($request,$silent) = @_;
  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  160:     if ($symb eq '') { 
  161: 	if (!$silent) {
  162: 	    $request->print("Unable to handle ambiguous references:$url:.");
  163: 	    return ();
  164: 	}
  165:     }
  166:     &Apache::lonenc::check_decrypt(\$symb);
  167:     return ($symb);
  168: }
  169: 
  170: #--- Format fullname, username:domain if different for display
  171: #--- Use anywhere where the student names are listed
  172: sub nameUserString {
  173:     my ($type,$fullname,$uname,$udom) = @_;
  174:     if ($type eq 'header') {
  175: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  176:     } else {
  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  179:     }
  180: }
  181: 
  182: #--- Get the partlist and the response type for a given problem. ---
  183: #--- Indicate if a response type is coded handgraded or not. ---
  184: sub response_type {
  185:     my ($symb) = shift;
  186: 
  187:     my $navmap = Apache::lonnavmaps::navmap->new();
  188:     my $res = $navmap->getBySymb($symb);
  189:     my $partlist = $res->parts();
  190:     my %vPart = 
  191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  192:     my (%response_types,%handgrade);
  193:     foreach my $part (@{ $partlist }) {
  194: 	next if (%vPart && !exists($vPart{$part}));
  195: 
  196: 	my @types = $res->responseType($part);
  197: 	my @ids = $res->responseIds($part);
  198: 	for (my $i=0; $i < scalar(@ids); $i++) {
  199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  200: 	    $handgrade{$part.'_'.$ids[$i]} = 
  201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  202: 				     '.handgrade',$symb);
  203: 	}
  204:     }
  205:     return ($partlist,\%handgrade,\%response_types);
  206: }
  207: 
  208: sub flatten_responseType {
  209:     my ($responseType) = @_;
  210:     my @part_response_id =
  211: 	map { 
  212: 	    my $part = $_;
  213: 	    map {
  214: 		[$part,$_]
  215: 		} sort(keys(%{ $responseType->{$part} }));
  216: 	} sort(keys(%$responseType));
  217:     return @part_response_id;
  218: }
  219: 
  220: sub get_display_part {
  221:     my ($partID,$symb)=@_;
  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  223:     if (defined($display) and $display ne '') {
  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  225:     } else {
  226: 	$display=$partID;
  227:     }
  228:     return $display;
  229: }
  230: 
  231: #--- Show resource title
  232: #--- and parts and response type
  233: sub showResourceInfo {
  234:     my ($symb,$probTitle,$checkboxes) = @_;
  235:     my $col=3;
  236:     if ($checkboxes) { $col=4; }
  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  238:     $result .='<table border="0">';
  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  240:     my %resptype = ();
  241:     my $hdgrade='no';
  242:     my %partsseen;
  243:     foreach my $partID (sort(keys(%$responseType))) {
  244: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  246: 	    my $responsetype = $responseType->{$partID}->{$resID};
  247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  248: 	    $result.='<tr>';
  249: 	    if ($checkboxes) {
  250: 		if (exists($partsseen{$partID})) {
  251: 		    $result.="<td>&nbsp;</td>";
  252: 		} else {
  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  254: 		}
  255: 		$partsseen{$partID}=1;
  256: 	    }
  257: 	    my $display_part=&get_display_part($partID,$symb);
  258: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
  259: 		$resID.'</span></td>'.
  260: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
  261: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  262: 	}
  263:     }
  264:     $result.='</table>'."\n";
  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  266: }
  267: 
  268: sub reset_caches {
  269:     &reset_analyze_cache();
  270:     &reset_perm();
  271: }
  272: 
  273: {
  274:     my %analyze_cache;
  275: 
  276:     sub reset_analyze_cache {
  277: 	undef(%analyze_cache);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  284: 
  285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  286: 	$url=&Apache::lonnet::clutter($url);
  287: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  288: 					   ('grade_target' => 'analyze',
  289: 					    'grade_domain' => $udom,
  290: 					    'grade_symb' => $symb,
  291: 					    'grade_courseid' => 
  292: 					    $env{'request.course.id'},
  293: 					    'grade_username' => $uname,
  294:                                             'grade_noincrement' => $no_increment));
  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  297: 	return $analyze_cache{$key} = \%analyze;
  298:     }
  299: 
  300:     sub get_order {
  301: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  302: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  303: 	return $analyze->{"$partid.$respid.shown"};
  304:     }
  305: 
  306:     sub get_radiobutton_correct_foil {
  307: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  308: 	my $analyze = &get_analyze($symb,$uname,$udom);
  309: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  310: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  311: 		return $foil;
  312: 	    }
  313: 	}
  314:     }
  315: }
  316: 
  317: #--- Clean response type for display
  318: #--- Currently filters option/rank/radiobutton/match/essay/Task
  319: #        response types only.
  320: sub cleanRecord {
  321:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  322: 	$uname,$udom) = @_;
  323:     my $grayFont = '<span class="LC_internal_info">';
  324:     if ($response =~ /^(option|rank)$/) {
  325: 	my %answer=&Apache::lonnet::str2hash($answer);
  326: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  327: 	my ($toprow,$bottomrow);
  328: 	foreach my $foil (@$order) {
  329: 	    if ($grading{$foil} == 1) {
  330: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  331: 	    } else {
  332: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  333: 	    }
  334: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  335: 	}
  336: 	return '<blockquote><table border="1">'.
  337: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  338: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  339: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  340:     } elsif ($response eq 'match') {
  341: 	my %answer=&Apache::lonnet::str2hash($answer);
  342: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  343: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  344: 	my ($toprow,$middlerow,$bottomrow);
  345: 	foreach my $foil (@$order) {
  346: 	    my $item=shift(@items);
  347: 	    if ($grading{$foil} == 1) {
  348: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  349: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  350: 	    } else {
  351: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  352: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  353: 	    }
  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  355: 	}
  356: 	return '<blockquote><table border="1">'.
  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  359: 	    $middlerow.'</tr>'.
  360: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  361: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  362:     } elsif ($response eq 'radiobutton') {
  363: 	my %answer=&Apache::lonnet::str2hash($answer);
  364: 	my ($toprow,$bottomrow);
  365: 	my $correct = 
  366: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  367: 	foreach my $foil (@$order) {
  368: 	    if (exists($answer{$foil})) {
  369: 		if ($foil eq $correct) {
  370: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  371: 		} else {
  372: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  373: 		}
  374: 	    } else {
  375: 		$toprow.='<td>'.&mt('false').'</td>';
  376: 	    }
  377: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  378: 	}
  379: 	return '<blockquote><table border="1">'.
  380: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  381: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  382: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  383:     } elsif ($response eq 'essay') {
  384: 	if (! exists ($env{'form.'.$symb})) {
  385: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  386: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  387: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  388: 
  389: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  390: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  391: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  392: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  393: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  394: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  395: 	}
  396: 	$answer =~ s-\n-<br />-g;
  397: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  398:     } elsif ( $response eq 'organic') {
  399: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  400: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  401: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  402: 	return $result;
  403:     } elsif ( $response eq 'Task') {
  404: 	if ( $answer eq 'SUBMITTED') {
  405: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  406: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  407: 	    return $result;
  408: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  409: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  410: 			       keys(%{$record}));
  411: 	    return join('<br />',($version,@matches));
  412: 			       
  413: 			       
  414: 	} else {
  415: 	    my $result =
  416: 		'<p>'
  417: 		.&mt('Overall result: [_1]',
  418: 		     $record->{$version."resource.$respid.$partid.status"})
  419: 		.'</p>';
  420: 	    
  421: 	    $result .= '<ul>';
  422: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  423: 			     keys(%{$record}));
  424: 	    foreach my $grade (sort(@grade)) {
  425: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  426: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  427: 				     $dim, $record->{$grade}).
  428: 			  '</li>';
  429: 	    }
  430: 	    $result.='</ul>';
  431: 	    return $result;
  432: 	}
  433:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  434: 	$answer = 
  435: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  436: 							      $answer);
  437:     }
  438:     return $answer;
  439: }
  440: 
  441: #-- A couple of common js functions
  442: sub commonJSfunctions {
  443:     my $request = shift;
  444:     $request->print(<<COMMONJSFUNCTIONS);
  445: <script type="text/javascript" language="javascript">
  446:     function radioSelection(radioButton) {
  447: 	var selection=null;
  448: 	if (radioButton.length > 1) {
  449: 	    for (var i=0; i<radioButton.length; i++) {
  450: 		if (radioButton[i].checked) {
  451: 		    return radioButton[i].value;
  452: 		}
  453: 	    }
  454: 	} else {
  455: 	    if (radioButton.checked) return radioButton.value;
  456: 	}
  457: 	return selection;
  458:     }
  459: 
  460:     function pullDownSelection(selectOne) {
  461: 	var selection="";
  462: 	if (selectOne.length > 1) {
  463: 	    for (var i=0; i<selectOne.length; i++) {
  464: 		if (selectOne[i].selected) {
  465: 		    return selectOne[i].value;
  466: 		}
  467: 	    }
  468: 	} else {
  469:             // only one value it must be the selected one
  470: 	    return selectOne.value;
  471: 	}
  472:     }
  473: </script>
  474: COMMONJSFUNCTIONS
  475: }
  476: 
  477: #--- Dumps the class list with usernames,list of sections,
  478: #--- section, ids and fullnames for each user.
  479: sub getclasslist {
  480:     my ($getsec,$filterlist,$getgroup) = @_;
  481:     my @getsec;
  482:     my @getgroup;
  483:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  484:     if (!ref($getsec)) {
  485: 	if ($getsec ne '' && $getsec ne 'all') {
  486: 	    @getsec=($getsec);
  487: 	}
  488:     } else {
  489: 	@getsec=@{$getsec};
  490:     }
  491:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  492:     if (!ref($getgroup)) {
  493: 	if ($getgroup ne '' && $getgroup ne 'all') {
  494: 	    @getgroup=($getgroup);
  495: 	}
  496:     } else {
  497: 	@getgroup=@{$getgroup};
  498:     }
  499:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  500: 
  501:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  502:     # Bail out if we were unable to get the classlist
  503:     return if (! defined($classlist));
  504:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  505:     #
  506:     my %sections;
  507:     my %fullnames;
  508:     foreach my $student (keys(%$classlist)) {
  509:         my $end      = 
  510:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  511:         my $start    = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  513:         my $id       = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  515:         my $section  = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  517:         my $fullname = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  519:         my $status   = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  521:         my $group   = 
  522:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  523: 	# filter students according to status selected
  524: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  525: 	    if (!($stu_status =~ $status)) {
  526: 		delete($classlist->{$student});
  527: 		next;
  528: 	    }
  529: 	}
  530: 	# filter students according to groups selected
  531: 	my @stu_groups = split(/,/,$group);
  532: 	if (@getgroup) {
  533: 	    my $exclude = 1;
  534: 	    foreach my $grp (@getgroup) {
  535: 	        foreach my $stu_group (@stu_groups) {
  536: 	            if ($stu_group eq $grp) {
  537: 	                $exclude = 0;
  538:     	            } 
  539: 	        }
  540:     	        if (($grp eq 'none') && !$group) {
  541:         	        $exclude = 0;
  542:         	}
  543: 	    }
  544: 	    if ($exclude) {
  545: 	        delete($classlist->{$student});
  546: 	    }
  547: 	}
  548: 	$section = ($section ne '' ? $section : 'none');
  549: 	if (&canview($section)) {
  550: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  551: 		$sections{$section}++;
  552: 		if ($classlist->{$student}) {
  553: 		    $fullnames{$student}=$fullname;
  554: 		}
  555: 	    } else {
  556: 		delete($classlist->{$student});
  557: 	    }
  558: 	} else {
  559: 	    delete($classlist->{$student});
  560: 	}
  561:     }
  562:     my %seen = ();
  563:     my @sections = sort(keys(%sections));
  564:     return ($classlist,\@sections,\%fullnames);
  565: }
  566: 
  567: sub canmodify {
  568:     my ($sec)=@_;
  569:     if ($perm{'mgr'}) {
  570: 	if (!defined($perm{'mgr_section'})) {
  571: 	    # can modify whole class
  572: 	    return 1;
  573: 	} else {
  574: 	    if ($sec eq $perm{'mgr_section'}) {
  575: 		#can modify the requested section
  576: 		return 1;
  577: 	    } else {
  578: 		# can't modify the request section
  579: 		return 0;
  580: 	    }
  581: 	}
  582:     }
  583:     #can't modify
  584:     return 0;
  585: }
  586: 
  587: sub canview {
  588:     my ($sec)=@_;
  589:     if ($perm{'vgr'}) {
  590: 	if (!defined($perm{'vgr_section'})) {
  591: 	    # can modify whole class
  592: 	    return 1;
  593: 	} else {
  594: 	    if ($sec eq $perm{'vgr_section'}) {
  595: 		#can modify the requested section
  596: 		return 1;
  597: 	    } else {
  598: 		# can't modify the request section
  599: 		return 0;
  600: 	    }
  601: 	}
  602:     }
  603:     #can't modify
  604:     return 0;
  605: }
  606: 
  607: #--- Retrieve the grade status of a student for all the parts
  608: sub student_gradeStatus {
  609:     my ($symb,$udom,$uname,$partlist) = @_;
  610:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  611:     my %partstatus = ();
  612:     foreach (@$partlist) {
  613: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  614: 	$status              = 'nothing' if ($status eq '');
  615: 	$partstatus{$_}      = $status;
  616: 	my $subkey           = "resource.$_.submitted_by";
  617: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  618:     }
  619:     return %partstatus;
  620: }
  621: 
  622: # hidden form and javascript that calls the form
  623: # Use by verifyscript and viewgrades
  624: # Shows a student's view of problem and submission
  625: sub jscriptNform {
  626:     my ($symb) = @_;
  627:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  628:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  629: 	'    function viewOneStudent(user,domain) {'."\n".
  630: 	'	document.onestudent.student.value = user;'."\n".
  631: 	'	document.onestudent.userdom.value = domain;'."\n".
  632: 	'	document.onestudent.submit();'."\n".
  633: 	'    }'."\n".
  634: 	'</script>'."\n";
  635:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  636: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  637: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  638: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  639: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  640: 	'<input type="hidden" name="command" value="submission" />'."\n".
  641: 	'<input type="hidden" name="student" value="" />'."\n".
  642: 	'<input type="hidden" name="userdom" value="" />'."\n".
  643: 	'</form>'."\n";
  644:     return $jscript;
  645: }
  646: 
  647: 
  648: 
  649: # Given the score (as a number [0-1] and the weight) what is the final
  650: # point value? This function will round to the nearest tenth, third,
  651: # or quarter if one of those is within the tolerance of .00001.
  652: sub compute_points {
  653:     my ($score, $weight) = @_;
  654:     
  655:     my $tolerance = .00001;
  656:     my $points = $score * $weight;
  657: 
  658:     # Check for nearness to 1/x.
  659:     my $check_for_nearness = sub {
  660:         my ($factor) = @_;
  661:         my $num = ($points * $factor) + $tolerance;
  662:         my $floored_num = floor($num);
  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  664:             return $floored_num / $factor;
  665:         }
  666:         return $points;
  667:     };
  668: 
  669:     $points = $check_for_nearness->(10);
  670:     $points = $check_for_nearness->(3);
  671:     $points = $check_for_nearness->(4);
  672:     
  673:     return $points;
  674: }
  675: 
  676: #------------------ End of general use routines --------------------
  677: 
  678: #
  679: # Find most similar essay
  680: #
  681: 
  682: sub most_similar {
  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
  684: 
  685: # ignore spaces and punctuation
  686: 
  687:     $uessay=~s/\W+/ /gs;
  688: 
  689: # ignore empty submissions (occuring when only files are sent)
  690: 
  691:     unless ($uessay=~/\w+/) { return ''; }
  692: 
  693: # these will be returned. Do not care if not at least 50 percent similar
  694:     my $limit=0.6;
  695:     my $sname='';
  696:     my $sdom='';
  697:     my $scrsid='';
  698:     my $sessay='';
  699: # go through all essays ...
  700:     foreach my $tkey (keys(%$old_essays)) {
  701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  702: # ... except the same student
  703:         next if (($tname eq $uname) && ($tdom eq $udom));
  704: 	my $tessay=$old_essays->{$tkey};
  705: 	$tessay=~s/\W+/ /gs;
  706: # String similarity gives up if not even limit
  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  708: # Found one
  709: 	if ($tsimilar>$limit) {
  710: 	    $limit=$tsimilar;
  711: 	    $sname=$tname;
  712: 	    $sdom=$tdom;
  713: 	    $scrsid=$tcrsid;
  714: 	    $sessay=$old_essays->{$tkey};
  715: 	}
  716:     }
  717:     if ($limit>0.6) {
  718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  719:     } else {
  720:        return ('','','','',0);
  721:     }
  722: }
  723: 
  724: #-------------------------------------------------------------------
  725: 
  726: #------------------------------------ Receipt Verification Routines
  727: #
  728: #--- Check whether a receipt number is valid.---
  729: sub verifyreceipt {
  730:     my $request  = shift;
  731: 
  732:     my $courseid = $env{'request.course.id'};
  733:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  734: 	$env{'form.receipt'};
  735:     $receipt     =~ s/[^\-\d]//g;
  736:     my ($symb)   = &get_symb($request);
  737: 
  738:     my $title.=
  739: 	'<h3><span class="LC_info">'.
  740: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  741: 	'</span></h3>'."\n".
  742: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  743: 	'</h4>'."\n";
  744: 
  745:     my ($string,$contents,$matches) = ('','',0);
  746:     my (undef,undef,$fullname) = &getclasslist('all','0');
  747:     
  748:     my $receiptparts=0;
  749:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  750: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  751:     my $parts=['0'];
  752:     if ($receiptparts) { ($parts)=&response_type($symb); }
  753:     
  754:     my $header = 
  755: 	&Apache::loncommon::start_data_table().
  756: 	&Apache::loncommon::start_data_table_header_row().
  757: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  758: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  759: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  760:     if ($receiptparts) {
  761: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  762:     }
  763:     $header.=
  764: 	&Apache::loncommon::end_data_table_header_row();
  765: 
  766:     foreach (sort 
  767: 	     {
  768: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  769: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  770: 		 }
  771: 		 return $a cmp $b;
  772: 	     } (keys(%$fullname))) {
  773: 	my ($uname,$udom)=split(/\:/);
  774: 	foreach my $part (@$parts) {
  775: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  776: 		$contents.=
  777: 		    &Apache::loncommon::start_data_table_row().
  778: 		    '<td>&nbsp;'."\n".
  779: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  780: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  781: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  782: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  783: 		if ($receiptparts) {
  784: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  785: 		}
  786: 		$contents.= 
  787: 		    &Apache::loncommon::end_data_table_row()."\n";
  788: 		
  789: 		$matches++;
  790: 	    }
  791: 	}
  792:     }
  793:     if ($matches == 0) {
  794: 	$string = $title.&mt('No match found for the above receipt.');
  795:     } else {
  796: 	$string = &jscriptNform($symb).$title.
  797: 	    '<p>'.
  798: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  799: 	    '</p>'.
  800: 	    $header.
  801: 	    $contents.
  802: 	    &Apache::loncommon::end_data_table()."\n";
  803:     }
  804:     return $string.&show_grading_menu_form($symb);
  805: }
  806: 
  807: #--- This is called by a number of programs.
  808: #--- Called from the Grading Menu - View/Grade an individual student
  809: #--- Also called directly when one clicks on the subm button 
  810: #    on the problem page.
  811: sub listStudents {
  812:     my ($request) = shift;
  813: 
  814:     my ($symb) = &get_symb($request);
  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  819:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  820:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  821:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  822: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  823: 
  824:     my $result='<h3><span class="LC_info">&nbsp;'.
  825: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  826: 	.'</span></h3>';
  827: 
  828:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  829: 
  830:     my %lt = ( 'multiple' =>
  831: 	       "Please select a student or group of students before clicking on the Next button.",
  832: 	       'single'   =>
  833: 	       "Please select the student before clicking on the Next button.",
  834: 	       );
  835:     %lt = &Apache::lonlocal::texthash(%lt);
  836:     $request->print(<<LISTJAVASCRIPT);
  837: <script type="text/javascript" language="javascript">
  838:     function checkSelect(checkBox) {
  839: 	var ctr=0;
  840: 	var sense="";
  841: 	if (checkBox.length > 1) {
  842: 	    for (var i=0; i<checkBox.length; i++) {
  843: 		if (checkBox[i].checked) {
  844: 		    ctr++;
  845: 		}
  846: 	    }
  847: 	    sense = '$lt{'multiple'}';
  848: 	} else {
  849: 	    if (checkBox.checked) {
  850: 		ctr = 1;
  851: 	    }
  852: 	    sense = '$lt{'single'}';
  853: 	}
  854: 	if (ctr == 0) {
  855: 	    alert(sense);
  856: 	    return false;
  857: 	}
  858: 	document.gradesub.submit();
  859:     }
  860: 
  861:     function reLoadList(formname) {
  862: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  863: 	formname.command.value = 'submission';
  864: 	formname.submit();
  865:     }
  866: </script>
  867: LISTJAVASCRIPT
  868: 
  869:     &commonJSfunctions($request);
  870:     $request->print($result);
  871: 
  872:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  873:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  874:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  875: 	"\n".$table;
  876: 	
  877:     $gradeTable .= 
  878: 	'&nbsp;'.
  879: 	&mt('<b>View Problem Text: </b>[_1]',
  880: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  881: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  882: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
  883:     $gradeTable .= 
  884: 	'&nbsp;'.
  885: 	&mt('<b>View Answer: </b>[_1]',
  886: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  887: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  888: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
  889: 
  890:     my $submission_options;
  891:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  892: 	$submission_options.=
  893: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  894:     }
  895:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  896:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  897:     $env{'form.Status'} = $saveStatus;
  898:     $submission_options.=
  899: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  900: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  901: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  902: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  903:     $gradeTable .= 
  904: 	'&nbsp;'.
  905: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
  906: 
  907:     $gradeTable .= 
  908:         '&nbsp;'.
  909: 	&mt('<b>Grading Increments:</b> [_1]',
  910: 	    '<select name="increment">'.
  911: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  912: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  913: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  914: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  915: 	    '</select>');
  916:     
  917:     $gradeTable .= 
  918:         &build_section_inputs().
  919: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  920: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  921: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  922: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  923: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  926: 
  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  928: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  929:     } else {
  930: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  931: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  932:     }
  933: 
  934:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  935: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
  936: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  937: 
  938: # checkall buttons
  939:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  940:     $gradeTable.='<input type="button" '."\n".
  941: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  942: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
  943:     $gradeTable.=&check_buttons();
  944:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  945:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  946:     $gradeTable.= &Apache::loncommon::start_data_table().
  947: 	&Apache::loncommon::start_data_table_header_row();
  948:     my $loop = 0;
  949:     while ($loop < 2) {
  950: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  951: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  952: 	if ($env{'form.showgrading'} eq 'yes' 
  953: 	    && $submitonly ne 'queued'
  954: 	    && $submitonly ne 'all') {
  955: 	    foreach my $part (sort(@$partlist)) {
  956: 		my $display_part=
  957: 		    &get_display_part((split(/_/,$part))[0],$symb);
  958: 		$gradeTable.=
  959: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  960: 	    }
  961: 	} elsif ($submitonly eq 'queued') {
  962: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  963: 	}
  964: 	$loop++;
  965: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  966:     }
  967:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  968: 
  969:     my $ctr = 0;
  970:     foreach my $student (sort 
  971: 			 {
  972: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  973: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  974: 			     }
  975: 			     return $a cmp $b;
  976: 			 }
  977: 			 (keys(%$fullname))) {
  978: 	my ($uname,$udom) = split(/:/,$student);
  979: 
  980: 	my %status = ();
  981: 
  982: 	if ($submitonly eq 'queued') {
  983: 	    my %queue_status = 
  984: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  985: 							$udom,$uname);
  986: 	    next if (!defined($queue_status{'gradingqueue'}));
  987: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  988: 	}
  989: 
  990: 	if ($env{'form.showgrading'} eq 'yes' 
  991: 	    && $submitonly ne 'queued'
  992: 	    && $submitonly ne 'all') {
  993: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  994: 	    my $submitted = 0;
  995: 	    my $graded = 0;
  996: 	    my $incorrect = 0;
  997: 	    foreach (keys(%status)) {
  998: 		$submitted = 1 if ($status{$_} ne 'nothing');
  999: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1000: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1001: 		
 1002: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1003: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1004: 		    $submitted = 0;
 1005: 		    my ($part)=split(/\./,$partid);
 1006: 		    $gradeTable.='<input type="hidden" name="'.
 1007: 			$student.':'.$part.':submitted_by" value="'.
 1008: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1009: 		}
 1010: 	    }
 1011: 	    
 1012: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1013: 				     $submitonly eq 'incorrect' ||
 1014: 				     $submitonly eq 'graded'));
 1015: 	    next if (!$graded && ($submitonly eq 'graded'));
 1016: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1017: 	}
 1018: 
 1019: 	$ctr++;
 1020: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1021:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1022: 	if ( $perm{'vgr'} eq 'F' ) {
 1023: 	    if ($ctr%2 ==1) {
 1024: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1025: 	    }
 1026: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1027:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1028:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1029: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1030: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1031: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1032: 
 1033: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1034: 		foreach (sort(keys(%status))) {
 1035: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1036: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1037: 		}
 1038: 	    }
 1039: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1040: 	    if ($ctr%2 ==0) {
 1041: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1042: 	    }
 1043: 	}
 1044:     }
 1045:     if ($ctr%2 ==1) {
 1046: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1047: 	    if ($env{'form.showgrading'} eq 'yes' 
 1048: 		&& $submitonly ne 'queued'
 1049: 		&& $submitonly ne 'all') {
 1050: 		foreach (@$partlist) {
 1051: 		    $gradeTable.='<td>&nbsp;</td>';
 1052: 		}
 1053: 	    } elsif ($submitonly eq 'queued') {
 1054: 		$gradeTable.='<td>&nbsp;</td>';
 1055: 	    }
 1056: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1057:     }
 1058: 
 1059:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1060: 	'<input type="button" '.
 1061: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1062: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1063:     if ($ctr == 0) {
 1064: 	my $num_students=(scalar(keys(%$fullname)));
 1065: 	if ($num_students eq 0) {
 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1067: 	} else {
 1068: 	    my $submissions='submissions';
 1069: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1070: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1071: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1072: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1073: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1074: 		    $num_students).
 1075: 		'</span><br />';
 1076: 	}
 1077:     } elsif ($ctr == 1) {
 1078: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1079:     }
 1080:     $gradeTable.=&show_grading_menu_form($symb);
 1081:     $request->print($gradeTable);
 1082:     return '';
 1083: }
 1084: 
 1085: #---- Called from the listStudents routine
 1086: 
 1087: sub check_script {
 1088:     my ($form, $type)=@_;
 1089:     my $chkallscript='<script type="text/javascript">
 1090:     function checkall() {
 1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1092:             ele = document.forms.'.$form.'.elements[i];
 1093:             if (ele.name == "'.$type.'") {
 1094:             document.forms.'.$form.'.elements[i].checked=true;
 1095:                                        }
 1096:         }
 1097:     }
 1098: 
 1099:     function checksec() {
 1100:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1101:             ele = document.forms.'.$form.'.elements[i];
 1102:            string = document.forms.'.$form.'.chksec.value;
 1103:            if
 1104:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1105:               document.forms.'.$form.'.elements[i].checked=true;
 1106:             }
 1107:         }
 1108:     }
 1109: 
 1110: 
 1111:     function uncheckall() {
 1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1113:             ele = document.forms.'.$form.'.elements[i];
 1114:             if (ele.name == "'.$type.'") {
 1115:             document.forms.'.$form.'.elements[i].checked=false;
 1116:                                        }
 1117:         }
 1118:     }
 1119: 
 1120: </script>'."\n";
 1121:     return $chkallscript;
 1122: }
 1123: 
 1124: sub check_buttons {
 1125:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1126:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1127:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1128:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1129:     return $buttons;
 1130: }
 1131: 
 1132: #     Displays the submissions for one student or a group of students
 1133: sub processGroup {
 1134:     my ($request)  = shift;
 1135:     my $ctr        = 0;
 1136:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1137:     my $total      = scalar(@stuchecked)-1;
 1138: 
 1139:     foreach my $student (@stuchecked) {
 1140: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1141: 	$env{'form.student'}        = $uname;
 1142: 	$env{'form.userdom'}        = $udom;
 1143: 	$env{'form.fullname'}       = $fullname;
 1144: 	&submission($request,$ctr,$total);
 1145: 	$ctr++;
 1146:     }
 1147:     return '';
 1148: }
 1149: 
 1150: #------------------------------------------------------------------------------------
 1151: #
 1152: #-------------------------- Next few routines handles grading by student, essentially
 1153: #                           handles essay response type problem/part
 1154: #
 1155: #--- Javascript to handle the submission page functionality ---
 1156: sub sub_page_js {
 1157:     my $request = shift;
 1158:     $request->print(<<SUBJAVASCRIPT);
 1159: <script type="text/javascript" language="javascript">
 1160:     function updateRadio(formname,id,weight) {
 1161: 	var gradeBox = formname["GD_BOX"+id];
 1162: 	var radioButton = formname["RADVAL"+id];
 1163: 	var oldpts = formname["oldpts"+id].value;
 1164: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1165: 	gradeBox.value = pts;
 1166: 	var resetbox = false;
 1167: 	if (isNaN(pts) || pts < 0) {
 1168: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1169: 	    for (var i=0; i<radioButton.length; i++) {
 1170: 		if (radioButton[i].checked) {
 1171: 		    gradeBox.value = i;
 1172: 		    resetbox = true;
 1173: 		}
 1174: 	    }
 1175: 	    if (!resetbox) {
 1176: 		formtextbox.value = "";
 1177: 	    }
 1178: 	    return;
 1179: 	}
 1180: 
 1181: 	if (pts > weight) {
 1182: 	    var resp = confirm("You entered a value ("+pts+
 1183: 			       ") greater than the weight for the part. Accept?");
 1184: 	    if (resp == false) {
 1185: 		gradeBox.value = oldpts;
 1186: 		return;
 1187: 	    }
 1188: 	}
 1189: 
 1190: 	for (var i=0; i<radioButton.length; i++) {
 1191: 	    radioButton[i].checked=false;
 1192: 	    if (pts == i && pts != "") {
 1193: 		radioButton[i].checked=true;
 1194: 	    }
 1195: 	}
 1196: 	updateSelect(formname,id);
 1197: 	formname["stores"+id].value = "0";
 1198:     }
 1199: 
 1200:     function writeBox(formname,id,pts) {
 1201: 	var gradeBox = formname["GD_BOX"+id];
 1202: 	if (checkSolved(formname,id) == 'update') {
 1203: 	    gradeBox.value = pts;
 1204: 	} else {
 1205: 	    var oldpts = formname["oldpts"+id].value;
 1206: 	    gradeBox.value = oldpts;
 1207: 	    var radioButton = formname["RADVAL"+id];
 1208: 	    for (var i=0; i<radioButton.length; i++) {
 1209: 		radioButton[i].checked=false;
 1210: 		if (i == oldpts) {
 1211: 		    radioButton[i].checked=true;
 1212: 		}
 1213: 	    }
 1214: 	}
 1215: 	formname["stores"+id].value = "0";
 1216: 	updateSelect(formname,id);
 1217: 	return;
 1218:     }
 1219: 
 1220:     function clearRadBox(formname,id) {
 1221: 	if (checkSolved(formname,id) == 'noupdate') {
 1222: 	    updateSelect(formname,id);
 1223: 	    return;
 1224: 	}
 1225: 	gradeSelect = formname["GD_SEL"+id];
 1226: 	for (var i=0; i<gradeSelect.length; i++) {
 1227: 	    if (gradeSelect[i].selected) {
 1228: 		var selectx=i;
 1229: 	    }
 1230: 	}
 1231: 	var stores = formname["stores"+id];
 1232: 	if (selectx == stores.value) { return };
 1233: 	var gradeBox = formname["GD_BOX"+id];
 1234: 	gradeBox.value = "";
 1235: 	var radioButton = formname["RADVAL"+id];
 1236: 	for (var i=0; i<radioButton.length; i++) {
 1237: 	    radioButton[i].checked=false;
 1238: 	}
 1239: 	stores.value = selectx;
 1240:     }
 1241: 
 1242:     function checkSolved(formname,id) {
 1243: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1244: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1245: 	    if (!reply) {return "noupdate";}
 1246: 	    formname.overRideScore.value = 'yes';
 1247: 	}
 1248: 	return "update";
 1249:     }
 1250: 
 1251:     function updateSelect(formname,id) {
 1252: 	formname["GD_SEL"+id][0].selected = true;
 1253: 	return;
 1254:     }
 1255: 
 1256: //=========== Check that a point is assigned for all the parts  ============
 1257:     function checksubmit(formname,val,total,parttot) {
 1258: 	formname.gradeOpt.value = val;
 1259: 	if (val == "Save & Next") {
 1260: 	    for (i=0;i<=total;i++) {
 1261: 		for (j=0;j<parttot;j++) {
 1262: 		    var partid = formname["partid"+i+"_"+j].value;
 1263: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1264: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1265: 			if (points == "") {
 1266: 			    var name = formname["name"+i].value;
 1267: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1268: 			    var resp = confirm("You did not assign a score for "+studentID+
 1269: 					       ", part "+partid+". Continue?");
 1270: 			    if (resp == false) {
 1271: 				formname["GD_BOX"+i+"_"+partid].focus();
 1272: 				return false;
 1273: 			    }
 1274: 			}
 1275: 		    }
 1276: 		    
 1277: 		}
 1278: 	    }
 1279: 	    
 1280: 	}
 1281: 	if (val == "Grade Student") {
 1282: 	    formname.showgrading.value = "yes";
 1283: 	    if (formname.Status.value == "") {
 1284: 		formname.Status.value = "Active";
 1285: 	    }
 1286: 	    formname.studentNo.value = total;
 1287: 	}
 1288: 	formname.submit();
 1289:     }
 1290: 
 1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1292:     function checkSubmitPage(formname,total) {
 1293: 	noscore = new Array(100);
 1294: 	var ptr = 0;
 1295: 	for (i=1;i<total;i++) {
 1296: 	    var partid = formname["q_"+i].value;
 1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1299: 		var status = formname["solved"+i+"_"+partid].value;
 1300: 		if (points == "" && status != "correct_by_student") {
 1301: 		    noscore[ptr] = i;
 1302: 		    ptr++;
 1303: 		}
 1304: 	    }
 1305: 	}
 1306: 	if (ptr != 0) {
 1307: 	    var sense = ptr == 1 ? ": " : "s: ";
 1308: 	    var prolist = "";
 1309: 	    if (ptr == 1) {
 1310: 		prolist = noscore[0];
 1311: 	    } else {
 1312: 		var i = 0;
 1313: 		while (i < ptr-1) {
 1314: 		    prolist += noscore[i]+", ";
 1315: 		    i++;
 1316: 		}
 1317: 		prolist += "and "+noscore[i];
 1318: 	    }
 1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1320: 	    if (resp == false) {
 1321: 		return false;
 1322: 	    }
 1323: 	}
 1324: 
 1325: 	formname.submit();
 1326:     }
 1327: </script>
 1328: SUBJAVASCRIPT
 1329: }
 1330: 
 1331: #--- javascript for essay type problem --
 1332: sub sub_page_kw_js {
 1333:     my $request = shift;
 1334:     my $iconpath = $request->dir_config('lonIconsURL');
 1335:     &commonJSfunctions($request);
 1336: 
 1337:     my $inner_js_msg_central=<<INNERJS;
 1338:     <script text="text/javascript">
 1339:     function checkInput() {
 1340:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1341:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1342:       var usrctr = document.msgcenter.usrctr.value;
 1343:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1344:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1345: 
 1346:       var msgchk = "";
 1347:       if (document.msgcenter.subchk.checked) {
 1348:          msgchk = "msgsub,";
 1349:       }
 1350:       var includemsg = 0;
 1351:       for (var i=1; i<=nmsg; i++) {
 1352:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1353:           var frmmsg = document.msgcenter["msg"+i];
 1354:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1355:           var showflg = opener.document.SCORE["shownOnce"+i];
 1356:           showflg.value = "1";
 1357:           var chkbox = document.msgcenter["msgn"+i];
 1358:           if (chkbox.checked) {
 1359:              msgchk += "savemsg"+i+",";
 1360:              includemsg = 1;
 1361:           }
 1362:       }
 1363:       if (document.msgcenter.newmsgchk.checked) {
 1364:          msgchk += "newmsg"+usrctr;
 1365:          includemsg = 1;
 1366:       }
 1367:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1368:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1369:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1370:       includemsg.value = msgchk;
 1371: 
 1372:       self.close()
 1373: 
 1374:     }
 1375:     </script>
 1376: INNERJS
 1377: 
 1378:     my $inner_js_highlight_central=<<INNERJS;
 1379:  <script type="text/javascript">
 1380:     function updateChoice(flag) {
 1381:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1382:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1383:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1384:       opener.document.SCORE.refresh.value = "on";
 1385:       if (opener.document.SCORE.keywords.value!=""){
 1386:          opener.document.SCORE.submit();
 1387:       }
 1388:       self.close()
 1389:     }
 1390: </script>
 1391: INNERJS
 1392: 
 1393:     my $start_page_msg_central = 
 1394:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1395: 				       {'js_ready'  => 1,
 1396: 					'only_body' => 1,
 1397: 					'bgcolor'   =>'#FFFFFF',});
 1398:     my $end_page_msg_central = 
 1399: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1400: 
 1401: 
 1402:     my $start_page_highlight_central = 
 1403:         &Apache::loncommon::start_page('Highlight Central',
 1404: 				       $inner_js_highlight_central,
 1405: 				       {'js_ready'  => 1,
 1406: 					'only_body' => 1,
 1407: 					'bgcolor'   =>'#FFFFFF',});
 1408:     my $end_page_highlight_central = 
 1409: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1410: 
 1411:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1412:     $docopen=~s/^document\.//;
 1413:     $request->print(<<SUBJAVASCRIPT);
 1414: <script type="text/javascript" language="javascript">
 1415: 
 1416: //===================== Show list of keywords ====================
 1417:   function keywords(formname) {
 1418:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1419:     if (nret==null) return;
 1420:     formname.keywords.value = nret;
 1421: 
 1422:     if (formname.keywords.value != "") {
 1423: 	formname.refresh.value = "on";
 1424: 	formname.submit();
 1425:     }
 1426:     return;
 1427:   }
 1428: 
 1429: //===================== Script to view submitted by ==================
 1430:   function viewSubmitter(submitter) {
 1431:     document.SCORE.refresh.value = "on";
 1432:     document.SCORE.NCT.value = "1";
 1433:     document.SCORE.unamedom0.value = submitter;
 1434:     document.SCORE.submit();
 1435:     return;
 1436:   }
 1437: 
 1438: //===================== Script to add keyword(s) ==================
 1439:   function getSel() {
 1440:     if (document.getSelection) txt = document.getSelection();
 1441:     else if (document.selection) txt = document.selection.createRange().text;
 1442:     else return;
 1443:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1444:     if (cleantxt=="") {
 1445: 	alert("Please select a word or group of words from document and then click this link.");
 1446: 	return;
 1447:     }
 1448:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1449:     if (nret==null) return;
 1450:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1451:     if (document.SCORE.keywords.value != "") {
 1452: 	document.SCORE.refresh.value = "on";
 1453: 	document.SCORE.submit();
 1454:     }
 1455:     return;
 1456:   }
 1457: 
 1458: //====================== Script for composing message ==============
 1459:    // preload images
 1460:    img1 = new Image();
 1461:    img1.src = "$iconpath/mailbkgrd.gif";
 1462:    img2 = new Image();
 1463:    img2.src = "$iconpath/mailto.gif";
 1464: 
 1465:   function msgCenter(msgform,usrctr,fullname) {
 1466:     var Nmsg  = msgform.savemsgN.value;
 1467:     savedMsgHeader(Nmsg,usrctr,fullname);
 1468:     var subject = msgform.msgsub.value;
 1469:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1470:     re = /msgsub/;
 1471:     var shwsel = "";
 1472:     if (re.test(msgchk)) { shwsel = "checked" }
 1473:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1474:     displaySubject(checkEntities(subject),shwsel);
 1475:     for (var i=1; i<=Nmsg; i++) {
 1476: 	var testmsg = "savemsg"+i+",";
 1477: 	re = new RegExp(testmsg,"g");
 1478: 	shwsel = "";
 1479: 	if (re.test(msgchk)) { shwsel = "checked" }
 1480: 	var message = document.SCORE["savemsg"+i].value;
 1481: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1482: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1483: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1484:     }
 1485:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1486:     shwsel = "";
 1487:     re = /newmsg/;
 1488:     if (re.test(msgchk)) { shwsel = "checked" }
 1489:     newMsg(newmsg,shwsel);
 1490:     msgTail(); 
 1491:     return;
 1492:   }
 1493: 
 1494:   function checkEntities(strx) {
 1495:     if (strx.length == 0) return strx;
 1496:     var orgStr = ["&", "<", ">", '"']; 
 1497:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1498:     var counter = 0;
 1499:     while (counter < 4) {
 1500: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1501: 	counter++;
 1502:     }
 1503:     return strx;
 1504:   }
 1505: 
 1506:   function strReplace(strx, orgStr, newStr) {
 1507:     return strx.split(orgStr).join(newStr);
 1508:   }
 1509: 
 1510:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1511:     var height = 70*Nmsg+250;
 1512:     var scrollbar = "no";
 1513:     if (height > 600) {
 1514: 	height = 600;
 1515: 	scrollbar = "yes";
 1516:     }
 1517:     var xpos = (screen.width-600)/2;
 1518:     xpos = (xpos < 0) ? '0' : xpos;
 1519:     var ypos = (screen.height-height)/2-30;
 1520:     ypos = (ypos < 0) ? '0' : ypos;
 1521: 
 1522:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1523:     pWin.focus();
 1524:     pDoc = pWin.document;
 1525:     pDoc.$docopen;
 1526:     pDoc.write('$start_page_msg_central');
 1527: 
 1528:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1529:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1530:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1531: 
 1532:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1533:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1534:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1535: }
 1536:     function displaySubject(msg,shwsel) {
 1537:     pDoc = pWin.document;
 1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1539:     pDoc.write("<td>Subject<\\/td>");
 1540:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1541:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1542: }
 1543: 
 1544:   function displaySavedMsg(ctr,msg,shwsel) {
 1545:     pDoc = pWin.document;
 1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1547:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1548:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1549:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1550: }
 1551: 
 1552:   function newMsg(newmsg,shwsel) {
 1553:     pDoc = pWin.document;
 1554:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1555:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1556:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1557:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1558: }
 1559: 
 1560:   function msgTail() {
 1561:     pDoc = pWin.document;
 1562:     pDoc.write("<\\/table>");
 1563:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1564:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1565:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1566:     pDoc.write("<\\/form>");
 1567:     pDoc.write('$end_page_msg_central');
 1568:     pDoc.close();
 1569: }
 1570: 
 1571: //====================== Script for keyword highlight options ==============
 1572:   function kwhighlight() {
 1573:     var kwclr    = document.SCORE.kwclr.value;
 1574:     var kwsize   = document.SCORE.kwsize.value;
 1575:     var kwstyle  = document.SCORE.kwstyle.value;
 1576:     var redsel = "";
 1577:     var grnsel = "";
 1578:     var blusel = "";
 1579:     if (kwclr=="red")   {var redsel="checked"};
 1580:     if (kwclr=="green") {var grnsel="checked"};
 1581:     if (kwclr=="blue")  {var blusel="checked"};
 1582:     var sznsel = "";
 1583:     var sz1sel = "";
 1584:     var sz2sel = "";
 1585:     if (kwsize=="0")  {var sznsel="checked"};
 1586:     if (kwsize=="+1") {var sz1sel="checked"};
 1587:     if (kwsize=="+2") {var sz2sel="checked"};
 1588:     var synsel = "";
 1589:     var syisel = "";
 1590:     var sybsel = "";
 1591:     if (kwstyle=="")    {var synsel="checked"};
 1592:     if (kwstyle=="<i>") {var syisel="checked"};
 1593:     if (kwstyle=="<b>") {var sybsel="checked"};
 1594:     highlightCentral();
 1595:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1596:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1597:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1598:     highlightend();
 1599:     return;
 1600:   }
 1601: 
 1602:   function highlightCentral() {
 1603: //    if (window.hwdWin) window.hwdWin.close();
 1604:     var xpos = (screen.width-400)/2;
 1605:     xpos = (xpos < 0) ? '0' : xpos;
 1606:     var ypos = (screen.height-330)/2-30;
 1607:     ypos = (ypos < 0) ? '0' : ypos;
 1608: 
 1609:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1610:     hwdWin.focus();
 1611:     var hDoc = hwdWin.document;
 1612:     hDoc.$docopen;
 1613:     hDoc.write('$start_page_highlight_central');
 1614:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1615:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1616: 
 1617:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1618:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1619:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1620:   }
 1621: 
 1622:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1623:     var hDoc = hwdWin.document;
 1624:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1625:     hDoc.write("<td align=\\"left\\">");
 1626:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1627:     hDoc.write("<td align=\\"left\\">");
 1628:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1629:     hDoc.write("<td align=\\"left\\">");
 1630:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1631:     hDoc.write("<\\/tr>");
 1632:   }
 1633: 
 1634:   function highlightend() { 
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.write("<\\/table>");
 1637:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1638:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1639:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1640:     hDoc.write("<\\/form>");
 1641:     hDoc.write('$end_page_highlight_central');
 1642:     hDoc.close();
 1643:   }
 1644: 
 1645: </script>
 1646: SUBJAVASCRIPT
 1647: }
 1648: 
 1649: sub get_increment {
 1650:     my $increment = $env{'form.increment'};
 1651:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1652:         $increment != .1) {
 1653:         $increment = 1;
 1654:     }
 1655:     return $increment;
 1656: }
 1657: 
 1658: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1659: sub gradeBox {
 1660:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1661:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1662: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1663:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1664:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1665:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1666:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1667:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1668: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1669:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1670:     my $display_part= &get_display_part($partid,$symb);
 1671:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1672: 				       [$partid]);
 1673:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1674:     if ($last_resets{$partid}) {
 1675:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1676:     }
 1677:     $result.='<table border="0"><tr>';
 1678:     my $ctr = 0;
 1679:     my $thisweight = 0;
 1680:     my $increment = &get_increment();
 1681: 
 1682:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1683:     while ($thisweight<=$wgt) {
 1684: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1685: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1686: 	    $thisweight.')" value="'.$thisweight.'" '.
 1687: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1688: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1689:         $thisweight += $increment;
 1690: 	$ctr++;
 1691:     }
 1692:     $radio.='</tr></table>';
 1693: 
 1694:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1695: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1696: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1697: 	$wgt.')" /></td>'."\n";
 1698:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1699: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1700: 	' </td><td>'."\n";
 1701:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1702: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1703:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1704: 	$line.='<option></option>'.
 1705: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1706:     } else {
 1707: 	$line.='<option selected="selected"></option>'.
 1708: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1709:     }
 1710:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1711: 
 1712: 
 1713:     $result .= 
 1714: 	&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);
 1715: 
 1716:     
 1717:     $result.='</tr></table>'."\n";
 1718:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1719: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1720: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1721: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1722:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1723:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1724:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1725:         $aggtries.'" />'."\n";
 1726:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1727:     return $result;
 1728: }
 1729: 
 1730: sub handback_box {
 1731:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1732:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1733:     my (@respids);
 1734:      my @part_response_id = &flatten_responseType($responseType);
 1735:     foreach my $part_response_id (@part_response_id) {
 1736:     	my ($part,$resp) = @{ $part_response_id };
 1737:         if ($part eq $partid) {
 1738:             push(@respids,$resp);
 1739:         }
 1740:     }
 1741:     my $result;
 1742:     foreach my $respid (@respids) {
 1743: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1744: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1745: 	next if (!@$files);
 1746: 	my $file_counter = 1;
 1747: 	foreach my $file (@$files) {
 1748: 	    if ($file =~ /\/portfolio\//) {
 1749:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1750:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1751:     	        $file_disp = "$name.$ext";
 1752:     	        $file = $file_path.$file_disp;
 1753:     	        $result.=&mt('Return commented version of [_1] to student.',
 1754:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1755:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1756:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1757:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1758:     	        $file_counter++;
 1759: 	    }
 1760: 	}
 1761:     }
 1762:     return $result;    
 1763: }
 1764: 
 1765: sub show_problem {
 1766:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1767:     my $rendered;
 1768:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1769:     &Apache::lonxml::remember_problem_counter();
 1770:     if ($mode eq 'both' or $mode eq 'text') {
 1771: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1772: 						       $env{'request.course.id'},
 1773: 						       undef,\%form);
 1774:     }
 1775:     if ($removeform) {
 1776: 	$rendered=~s|<form(.*?)>||g;
 1777: 	$rendered=~s|</form>||g;
 1778: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1779:     }
 1780:     my $companswer;
 1781:     if ($mode eq 'both' or $mode eq 'answer') {
 1782: 	&Apache::lonxml::restore_problem_counter();
 1783: 	$companswer=
 1784: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1785: 						    $env{'request.course.id'},
 1786: 						    %form);
 1787:     }
 1788:     if ($removeform) {
 1789: 	$companswer=~s|<form(.*?)>||g;
 1790: 	$companswer=~s|</form>||g;
 1791: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1792:     }
 1793:     $rendered=
 1794: 	'<div class="LC_grade_show_problem_header">'.
 1795: 	&mt('View of the problem').
 1796: 	'</div><div class="LC_grade_show_problem_problem">'.
 1797: 	$rendered.
 1798: 	'</div>';
 1799:     $companswer=
 1800: 	'<div class="LC_grade_show_problem_header">'.
 1801: 	&mt('Correct answer').
 1802: 	'</div><div class="LC_grade_show_problem_problem">'.
 1803: 	$companswer.
 1804: 	'</div>';
 1805:     my $result;
 1806:     if ($mode eq 'both') {
 1807: 	$result=$rendered.$companswer;
 1808:     } elsif ($mode eq 'text') {
 1809: 	$result=$rendered;
 1810:     } elsif ($mode eq 'answer') {
 1811: 	$result=$companswer;
 1812:     }
 1813:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1814:     return $result;
 1815: }
 1816: 
 1817: sub files_exist {
 1818:     my ($r, $symb) = @_;
 1819:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1820: 
 1821:     foreach my $student (@students) {
 1822:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1823:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1824: 					      $udom,$uname);
 1825:         my ($string,$timestamp)= &get_last_submission(\%record);
 1826:         foreach my $submission (@$string) {
 1827:             my ($partid,$respid) =
 1828: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1829:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1830: 					   \%record);
 1831:             return 1 if (@$files);
 1832:         }
 1833:     }
 1834:     return 0;
 1835: }
 1836: 
 1837: sub download_all_link {
 1838:     my ($r,$symb) = @_;
 1839:     my $all_students = 
 1840: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1841: 
 1842:     my $parts =
 1843: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1844: 
 1845:     my $identifier = &Apache::loncommon::get_cgi_id();
 1846:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1847:                              'cgi.'.$identifier.'.symb' => $symb,
 1848:                              'cgi.'.$identifier.'.parts' => $parts,});
 1849:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1850: 	      &mt('Download All Submitted Documents').'</a>');
 1851:     return
 1852: }
 1853: 
 1854: sub build_section_inputs {
 1855:     my $section_inputs;
 1856:     if ($env{'form.section'} eq '') {
 1857:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1858:     } else {
 1859:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1860:         foreach my $section (@sections) {
 1861:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1862:         }
 1863:     }
 1864:     return $section_inputs;
 1865: }
 1866: 
 1867: # --------------------------- show submissions of a student, option to grade 
 1868: sub submission {
 1869:     my ($request,$counter,$total) = @_;
 1870:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1871:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1872:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1873:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1874:     my $symb = &get_symb($request); 
 1875:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1876: 
 1877:     if (!&canview($usec)) {
 1878: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1879: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1880: 			$env{'request.course.id'}.')</span>');
 1881: 	$request->print(&show_grading_menu_form($symb));
 1882: 	return;
 1883:     }
 1884: 
 1885:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1886:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1887:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1888:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1889:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1890: 	'" src="'.$request->dir_config('lonIconsURL').
 1891: 	'/check.gif" height="16" border="0" />';
 1892: 
 1893:     my %old_essays;
 1894:     # header info
 1895:     if ($counter == 0) {
 1896: 	&sub_page_js($request);
 1897: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1898: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1899: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1900: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1901: 	    &download_all_link($request, $symb);
 1902: 	}
 1903: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1904: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1905: 
 1906: 	# option to display problem, only once else it cause problems 
 1907:         # with the form later since the problem has a form.
 1908: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1909: 	    my $mode;
 1910: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1911: 		$mode='both';
 1912: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1913: 		$mode='text';
 1914: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1915: 		$mode='answer';
 1916: 	    }
 1917: 	    &Apache::lonxml::clear_problem_counter();
 1918: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1919: 	}
 1920: 
 1921: 	# kwclr is the only variable that is guaranteed to be non blank 
 1922:         # if this subroutine has been called once.
 1923: 	my %keyhash = ();
 1924: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1925: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1926: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1927: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1928: 
 1929: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1930: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1931: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1932: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1933: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1934: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1935: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1936: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1937: 	}
 1938: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1939: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1940: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1941: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1942: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1943: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1944: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1945: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1946: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1947: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1948: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1949: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1950: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1951: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1952: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1953: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1954: 			&build_section_inputs().
 1955: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1956: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1957: 			'<input type="hidden" name="NCT"'.
 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1959: 	if ($env{'form.handgrade'} eq 'yes') {
 1960: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1961: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1963: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1965: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1966: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1967: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1968: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1969: 	    }
 1970: 	}
 1971: 	
 1972: 	my ($cts,$prnmsg) = (1,'');
 1973: 	while ($cts <= $env{'form.savemsgN'}) {
 1974: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1975: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1976: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1977: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1978: 		'" />'."\n".
 1979: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1980: 	    $cts++;
 1981: 	}
 1982: 	$request->print($prnmsg);
 1983: 
 1984: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1985: #
 1986: # Print out the keyword options line
 1987: #
 1988: 	    $request->print(<<KEYWORDS);
 1989: &nbsp;<b>Keyword Options:</b>&nbsp;
 1990: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1991: <a href="#" onMouseDown="javascript:getSel(); return false"
 1992:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1993: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1994: KEYWORDS
 1995: #
 1996: # Load the other essays for similarity check
 1997: #
 1998:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1999: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2000: 	    $apath=&escape($apath);
 2001: 	    $apath=~s/\W/\_/gs;
 2002: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2003:         }
 2004:     }
 2005: 
 2006: # This is where output for one specific student would start
 2007:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2008:     $request->print("\n\n".
 2009:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2010: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2011: 		    '<div class="LC_grade_show_user_body">'."\n");
 2012: 
 2013:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2014: 	my $mode;
 2015: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2016: 	    $mode='both';
 2017: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2018: 	    $mode='text';
 2019: 	} elsif ($env{'form.vAns'} eq 'all') {
 2020: 	    $mode='answer';
 2021: 	}
 2022: 	&Apache::lonxml::clear_problem_counter();
 2023: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2024:     }
 2025: 
 2026:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2027:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2028: 
 2029:     # Display student info
 2030:     $request->print(($counter == 0 ? '' : '<br />'));
 2031:     my $result='<div class="LC_grade_submissions">';
 2032:     
 2033:     $result.='<div class="LC_grade_submissions_header">';
 2034:     $result.= &mt('Submissions');
 2035:     $result.='<input type="hidden" name="name'.$counter.
 2036: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2037:     if ($env{'form.handgrade'} eq 'no') {
 2038: 	$result.='<span class="LC_grade_check_note">'.
 2039: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2040: 
 2041:     }
 2042: 
 2043: 
 2044: 
 2045:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2046:     my $fullname;
 2047:     my $col_fullnames = [];
 2048:     if ($env{'form.handgrade'} eq 'yes') {
 2049: 	(my $sub_result,$fullname,$col_fullnames)=
 2050: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2051: 				 $counter);
 2052: 	$result.=$sub_result;
 2053:     }
 2054:     $request->print($result."\n");
 2055:     $request->print('</div>'."\n");
 2056:     # print student answer/submission
 2057:     # Options are (1) Handgaded submission only
 2058:     #             (2) Last submission, includes submission that is not handgraded 
 2059:     #                  (for multi-response type part)
 2060:     #             (3) Last submission plus the parts info
 2061:     #             (4) The whole record for this student
 2062:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2063: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2064: 	
 2065: 	my $lastsubonly;
 2066: 
 2067: 	if ($$timestamp eq '') {
 2068: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2069: 	} else {
 2070: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2071: 
 2072: 	    my %seenparts;
 2073: 	    my @part_response_id = &flatten_responseType($responseType);
 2074: 	    foreach my $part (@part_response_id) {
 2075: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2076: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2077: 
 2078: 		my ($partid,$respid) = @{ $part };
 2079: 		my $display_part=&get_display_part($partid,$symb);
 2080: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2081: 		    if (exists($seenparts{$partid})) { next; }
 2082: 		    $seenparts{$partid}=1;
 2083: 		    my $submitby='<b>Part:</b> '.$display_part.
 2084: 			' <b>Collaborative submission by:</b> '.
 2085: 			'<a href="javascript:viewSubmitter(\''.
 2086: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2087: 			'\');" target="_self">'.
 2088: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2089: 		    $request->print($submitby);
 2090: 		    next;
 2091: 		}
 2092: 		my $responsetype = $responseType->{$partid}->{$respid};
 2093: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2094: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2095: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2096: 			' )</span>&nbsp; &nbsp;'.
 2097: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2098: 		    next;
 2099: 		}
 2100: 		foreach my $submission (@$string) {
 2101: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2102: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2103: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2104: 		    # Similarity check
 2105: 		    my $similar='';
 2106: 		    if($env{'form.checkPlag'}){
 2107: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2108: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2109: 			if ($osim) {
 2110: 			    $osim=int($osim*100.0);
 2111: 			    my %old_course_desc = 
 2112: 				&Apache::lonnet::coursedescription($ocrsid,
 2113: 								   {'one_time' => 1});
 2114: 
 2115: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2116: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2117: 				    $osim,
 2118: 				    &Apache::loncommon::plainname($oname,$odom),
 2119: 				    $oname,$odom,
 2120: 				    $old_course_desc{'description'},
 2121: 				    $old_course_desc{'num'},
 2122: 				    $old_course_desc{'domain'}).
 2123: 				'</span></h3><blockquote><i>'.
 2124: 				&keywords_highlight($oessay).
 2125: 				'</i></blockquote><hr />';
 2126: 			}
 2127: 		    }
 2128: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2129: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2130: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2131: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2132: 			my $display_part=&get_display_part($partid,$symb);
 2133: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2134: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2135: 			    ' )</span>&nbsp; &nbsp;';
 2136: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2137: 			if (@$files) {
 2138: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2139: 			    my $file_counter = 0;
 2140: 			    foreach my $file (@$files) {
 2141: 			        $file_counter++;
 2142: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2143: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2144: 			    }
 2145: 			    $lastsubonly.='<br />';
 2146: 			}
 2147: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2148: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2149: 					 $respid,\%record,$order);
 2150: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2151: 			$lastsubonly.='</div>';
 2152: 		    }
 2153: 		}
 2154: 	    }
 2155: 	    $lastsubonly.='</div>'."\n";
 2156: 	}
 2157: 	$request->print($lastsubonly);
 2158:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2159: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2160: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2161:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2162: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2163: 								 $env{'request.course.id'},
 2164: 								 $last,'.submission',
 2165: 								 'Apache::grades::keywords_highlight'));
 2166:     }
 2167: 
 2168:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2169: 	.$udom.'" />'."\n");
 2170:     # return if view submission with no grading option
 2171:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2172: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2173: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2174: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2175: 	$toGrade.='</div>'."\n";
 2176: 	if (($env{'form.command'} eq 'submission') || 
 2177: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2178: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2179: 	}
 2180: 	$request->print($toGrade);
 2181: 	return;
 2182:     } else {
 2183: 	$request->print('</div>'."\n");
 2184:     }
 2185: 
 2186:     # essay grading message center
 2187:     if ($env{'form.handgrade'} eq 'yes') {
 2188: 	my $result='<div class="LC_grade_message_center">';
 2189:     
 2190: 	$result.='<div class="LC_grade_message_center_header">'.
 2191: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2192: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2193: 	my $msgfor = $givenn.' '.$lastname;
 2194: 	if (scalar(@$col_fullnames) > 0) {
 2195: 	    my $lastone = pop(@$col_fullnames);
 2196: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2197: 	}
 2198: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2199: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2200: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2201: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2202: 	    ',\''.$msgfor.'\');" target="_self">'.
 2203: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2204: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2205: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2206: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2207: 	    '<br />&nbsp;('.
 2208: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2209: 	$result.='</div></div>';
 2210: 	$request->print($result);
 2211:     }
 2212: 
 2213:     my %seen = ();
 2214:     my @partlist;
 2215:     my @gradePartRespid;
 2216:     my @part_response_id = &flatten_responseType($responseType);
 2217:     $request->print('<div class="LC_grade_assign">'.
 2218: 		    
 2219: 		    '<div class="LC_grade_assign_header">'.
 2220: 		    &mt('Assign Grades').'</div>'.
 2221: 		    '<div class="LC_grade_assign_body">');
 2222:     foreach my $part_response_id (@part_response_id) {
 2223:     	my ($partid,$respid) = @{ $part_response_id };
 2224: 	my $part_resp = join('_',@{ $part_response_id });
 2225: 	next if ($seen{$partid} > 0);
 2226: 	$seen{$partid}++;
 2227: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2228: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2229: 	push(@partlist,$partid);
 2230: 	push(@gradePartRespid,$partid.'.'.$respid);
 2231: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2232:     }
 2233:     $request->print('</div></div>');
 2234: 
 2235:     $request->print('<div class="LC_grade_info_links">');
 2236:     if ($perm{'vgr'}) {
 2237: 	$request->print(
 2238: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2239: 						   $uname,$udom,'check'));
 2240:     }
 2241:     if ($perm{'opa'}) {
 2242: 	$request->print(
 2243: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2244: 					 $uname,$udom,$symb,'check'));
 2245:     }
 2246:     $request->print('</div>');
 2247: 
 2248:     $result='<input type="hidden" name="partlist'.$counter.
 2249: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2250:     $result.='<input type="hidden" name="gradePartRespid'.
 2251: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2252:     my $ctr = 0;
 2253:     while ($ctr < scalar(@partlist)) {
 2254: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2255: 	    $partlist[$ctr].'" />'."\n";
 2256: 	$ctr++;
 2257:     }
 2258:     $request->print($result.''."\n");
 2259: 
 2260: # Done with printing info for one student
 2261: 
 2262:     $request->print('</div>');#LC_grade_show_user_body
 2263:     $request->print('</div>');#LC_grade_show_user
 2264: 
 2265: 
 2266:     # print end of form
 2267:     if ($counter == $total) {
 2268: 	my $endform='<table border="0"><tr><td>'."\n";
 2269: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2270: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2271: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2272: 	my $ntstu ='<select name="NTSTU">'.
 2273: 	    '<option>1</option><option>2</option>'.
 2274: 	    '<option>3</option><option>5</option>'.
 2275: 	    '<option>7</option><option>10</option></select>'."\n";
 2276: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2277: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2278: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2279: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2280: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2281: 	    '<input type="button" value="'.&mt('Next').'" '.
 2282: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2283: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2284:         $endform.="<input type='hidden' value='".&get_increment().
 2285:             "' name='increment' />";
 2286: 	$endform.='</td></tr></table></form>';
 2287: 	$endform.=&show_grading_menu_form($symb);
 2288: 	$request->print($endform);
 2289:     }
 2290:     return '';
 2291: }
 2292: 
 2293: sub check_collaborators {
 2294:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2295:     my ($result,@col_fullnames);
 2296:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2297:     foreach my $part (keys(%$handgrade)) {
 2298: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2299: 					'.maxcollaborators',
 2300: 					$symb,$udom,$uname);
 2301: 	next if ($ncol <= 0);
 2302: 	$part =~ s/\_/\./g;
 2303: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2304: 	my (@good_collaborators, @bad_collaborators);
 2305: 	foreach my $possible_collaborator
 2306: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2307: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2308: 	    next if ($possible_collaborator eq '');
 2309: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2310: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2311: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2312: 	    # Doing this grep allows 'fuzzy' specification
 2313: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2314: 			       keys(%$classlist));
 2315: 	    if (! scalar(@matches)) {
 2316: 		push(@bad_collaborators, $possible_collaborator);
 2317: 	    } else {
 2318: 		push(@good_collaborators, @matches);
 2319: 	    }
 2320: 	}
 2321: 	if (scalar(@good_collaborators) != 0) {
 2322: 	    $result.='<br />'.&mt('Collaborators: ');
 2323: 	    foreach my $name (@good_collaborators) {
 2324: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2325: 		push(@col_fullnames, $givenn.' '.$lastname);
 2326: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2327: 	    }
 2328: 	    $result.='<br />'."\n";
 2329: 	    my ($part)=split(/\./,$part);
 2330: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2331: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2332: 		"\n";
 2333: 	}
 2334: 	if (scalar(@bad_collaborators) > 0) {
 2335: 	    $result.='<div class="LC_warning">';
 2336: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2337: 	    $result .= '</div>';
 2338: 	}         
 2339: 	if (scalar(@bad_collaborators > $ncol)) {
 2340: 	    $result .= '<div class="LC_warning">';
 2341: 	    $result .= &mt('This student has submitted too many '.
 2342: 		'collaborators.  Maximum is [_1].',$ncol);
 2343: 	    $result .= '</div>';
 2344: 	}
 2345:     }
 2346:     return ($result,$fullname,\@col_fullnames);
 2347: }
 2348: 
 2349: #--- Retrieve the last submission for all the parts
 2350: sub get_last_submission {
 2351:     my ($returnhash)=@_;
 2352:     my (@string,$timestamp);
 2353:     if ($$returnhash{'version'}) {
 2354: 	my %lasthash=();
 2355: 	my ($version);
 2356: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2357: 	    foreach my $key (sort(split(/\:/,
 2358: 					$$returnhash{$version.':keys'}))) {
 2359: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2360: 		$timestamp = 
 2361: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2362: 	    }
 2363: 	}
 2364: 	foreach my $key (keys(%lasthash)) {
 2365: 	    next if ($key !~ /\.submission$/);
 2366: 
 2367: 	    my ($partid,$foo) = split(/submission$/,$key);
 2368: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2369: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2370: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2371: 	}
 2372:     }
 2373:     if (!@string) {
 2374: 	$string[0] =
 2375: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2376:     }
 2377:     return (\@string,\$timestamp);
 2378: }
 2379: 
 2380: #--- High light keywords, with style choosen by user.
 2381: sub keywords_highlight {
 2382:     my $string    = shift;
 2383:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2384:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2385:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2386:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2387:     foreach my $keyword (@keylist) {
 2388: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2389:     }
 2390:     return $string;
 2391: }
 2392: 
 2393: #--- Called from submission routine
 2394: sub processHandGrade {
 2395:     my ($request) = shift;
 2396:     my $symb   = &get_symb($request);
 2397:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2398:     my $button = $env{'form.gradeOpt'};
 2399:     my $ngrade = $env{'form.NCT'};
 2400:     my $ntstu  = $env{'form.NTSTU'};
 2401:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2402:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2403: 
 2404:     if ($button eq 'Save & Next') {
 2405: 	my $ctr = 0;
 2406: 	while ($ctr < $ngrade) {
 2407: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2408: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2409: 	    if ($errorflag eq 'no_score') {
 2410: 		$ctr++;
 2411: 		next;
 2412: 	    }
 2413: 	    if ($errorflag eq 'not_allowed') {
 2414: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2415: 		$ctr++;
 2416: 		next;
 2417: 	    }
 2418: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2419: 	    my ($subject,$message,$msgstatus) = ('','','');
 2420: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2421:             my ($feedurl,$showsymb) =
 2422: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2423: 	    my $messagetail;
 2424: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2425: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2426: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2427: 		$subject.=' ['.$restitle.']';
 2428: 		my (@msgnum) = split(/,/,$includemsg);
 2429: 		foreach (@msgnum) {
 2430: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2431: 		}
 2432: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2433: 		if ($env{'form.withgrades'.$ctr}) {
 2434: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2435: 		    $messagetail = " for <a href=\"".
 2436: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2437: 		}
 2438: 		$msgstatus = 
 2439:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2440: 						     $message.$messagetail,
 2441:                                                      undef,$feedurl,undef,
 2442:                                                      undef,undef,$showsymb,
 2443:                                                      $restitle);
 2444: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2445: 				$msgstatus);
 2446: 	    }
 2447: 	    if ($env{'form.collaborator'.$ctr}) {
 2448: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2449: 		foreach my $collabstr (@collabstrs) {
 2450: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2451: 		    foreach my $collaborator (@collaborators) {
 2452: 			my ($errorflag,$pts,$wgt) = 
 2453: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2454: 					   $env{'form.unamedom'.$ctr},$part);
 2455: 			if ($errorflag eq 'not_allowed') {
 2456: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2457: 			    next;
 2458: 			} elsif ($message ne '') {
 2459: 			    my ($baseurl,$showsymb) = 
 2460: 				&get_feedurl_and_symb($symb,$collaborator,
 2461: 						      $udom);
 2462: 			    if ($env{'form.withgrades'.$ctr}) {
 2463: 				$messagetail = " for <a href=\"".
 2464:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2465: 			    }
 2466: 			    $msgstatus = 
 2467: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2468: 			}
 2469: 		    }
 2470: 		}
 2471: 	    }
 2472: 	    $ctr++;
 2473: 	}
 2474:     }
 2475: 
 2476:     if ($env{'form.handgrade'} eq 'yes') {
 2477: 	# Keywords sorted in alphabatical order
 2478: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2479: 	my %keyhash = ();
 2480: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2481: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2482: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2483: 	$env{'form.keywords'} = join(' ',@keywords);
 2484: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2485: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2486: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2487: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2488: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2489: 
 2490: 	# message center - Order of message gets changed. Blank line is eliminated.
 2491: 	# New messages are saved in env for the next student.
 2492: 	# All messages are saved in nohist_handgrade.db
 2493: 	my ($ctr,$idx) = (1,1);
 2494: 	while ($ctr <= $env{'form.savemsgN'}) {
 2495: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2496: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2497: 		$idx++;
 2498: 	    }
 2499: 	    $ctr++;
 2500: 	}
 2501: 	$ctr = 0;
 2502: 	while ($ctr < $ngrade) {
 2503: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2504: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2505: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2506: 		$idx++;
 2507: 	    }
 2508: 	    $ctr++;
 2509: 	}
 2510: 	$env{'form.savemsgN'} = --$idx;
 2511: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2512: 	my $putresult = &Apache::lonnet::put
 2513: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2514:     }
 2515:     # Called by Save & Refresh from Highlight Attribute Window
 2516:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2517:     if ($env{'form.refresh'} eq 'on') {
 2518: 	my ($ctr,$total) = (0,0);
 2519: 	while ($ctr < $ngrade) {
 2520: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2521: 	    $ctr++;
 2522: 	}
 2523: 	$env{'form.NTSTU'}=$ngrade;
 2524: 	$ctr = 0;
 2525: 	while ($ctr < $total) {
 2526: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2527: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2528: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2529: 	    &submission($request,$ctr,$total-1);
 2530: 	    $ctr++;
 2531: 	}
 2532: 	return '';
 2533:     }
 2534: 
 2535: # Go directly to grade student - from submission or link from chart page
 2536:     if ($button eq 'Grade Student') {
 2537: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2538: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2539: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2540: 	$env{'form.fullname'} = $$fullname{$processUser};
 2541: 	&submission($request,0,0);
 2542: 	return '';
 2543:     }
 2544: 
 2545:     # Get the next/previous one or group of students
 2546:     my $firststu = $env{'form.unamedom0'};
 2547:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2548:     my $ctr = 2;
 2549:     while ($laststu eq '') {
 2550: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2551: 	$ctr++;
 2552: 	$laststu = $firststu if ($ctr > $ngrade);
 2553:     }
 2554: 
 2555:     my (@parsedlist,@nextlist);
 2556:     my ($nextflg) = 0;
 2557:     foreach my $item (sort 
 2558: 	     {
 2559: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2560: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2561: 		 }
 2562: 		 return $a cmp $b;
 2563: 	     } (keys(%$fullname))) {
 2564: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2565: 	    push(@parsedlist,$item);
 2566: 	}
 2567: 	$nextflg = 1 if ($item eq $laststu);
 2568: 	if ($button eq 'Previous') {
 2569: 	    last if ($item eq $firststu);
 2570: 	    push(@parsedlist,$item);
 2571: 	}
 2572:     }
 2573:     $ctr = 0;
 2574:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2575:     my ($partlist) = &response_type($symb);
 2576:     foreach my $student (@parsedlist) {
 2577: 	my $submitonly=$env{'form.submitonly'};
 2578: 	my ($uname,$udom) = split(/:/,$student);
 2579: 	
 2580: 	if ($submitonly eq 'queued') {
 2581: 	    my %queue_status = 
 2582: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2583: 							$udom,$uname);
 2584: 	    next if (!defined($queue_status{'gradingqueue'}));
 2585: 	}
 2586: 
 2587: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2588: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2589: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2590: 	    my $submitted = 0;
 2591: 	    my $ungraded = 0;
 2592: 	    my $incorrect = 0;
 2593: 	    foreach my $item (keys(%status)) {
 2594: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2595: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2596: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2597: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2598: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2599: 		    $submitted = 0;
 2600: 		}
 2601: 	    }
 2602: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2603: 				     $submitonly eq 'incorrect' ||
 2604: 				     $submitonly eq 'graded'));
 2605: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2606: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2607: 	}
 2608: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2609: 	last if ($ctr == $ntstu);
 2610: 	$ctr++;
 2611:     }
 2612: 
 2613:     $ctr = 0;
 2614:     my $total = scalar(@nextlist)-1;
 2615: 
 2616:     foreach (sort(@nextlist)) {
 2617: 	my ($uname,$udom,$submitter) = split(/:/);
 2618: 	$env{'form.student'}  = $uname;
 2619: 	$env{'form.userdom'}  = $udom;
 2620: 	$env{'form.fullname'} = $$fullname{$_};
 2621: 	&submission($request,$ctr,$total);
 2622: 	$ctr++;
 2623:     }
 2624:     if ($total < 0) {
 2625: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2626: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2627: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2628: 	$the_end.=&show_grading_menu_form($symb);
 2629: 	$request->print($the_end);
 2630:     }
 2631:     return '';
 2632: }
 2633: 
 2634: #---- Save the score and award for each student, if changed
 2635: sub saveHandGrade {
 2636:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2637:     my @version_parts;
 2638:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2639: 					   $env{'request.course.id'});
 2640:     if (!&canmodify($usec)) { return('not_allowed'); }
 2641:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2642:     my @parts_graded;
 2643:     my %newrecord  = ();
 2644:     my ($pts,$wgt) = ('','');
 2645:     my %aggregate = ();
 2646:     my $aggregateflag = 0;
 2647:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2648:     foreach my $new_part (@parts) {
 2649: 	#collaborator ($submi may vary for different parts
 2650: 	if ($submitter && $new_part ne $part) { next; }
 2651: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2652: 	if ($dropMenu eq 'excused') {
 2653: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2654: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2655: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2656: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2657: 		}
 2658: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2659: 	    }
 2660: 	} elsif ($dropMenu eq 'reset status'
 2661: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2662: 	    foreach my $key (keys(%record)) {
 2663: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2664: 	    }
 2665: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2666: 		"$env{'user.name'}:$env{'user.domain'}";
 2667:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2668: 
 2669:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2670: 					       [$new_part]);
 2671:             my $aggtries =$totaltries;
 2672:             if ($last_resets{$new_part}) {
 2673:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2674: 					   $new_part);
 2675:             }
 2676: 
 2677:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2678:             if ($aggtries > 0) {
 2679:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2680:                 $aggregateflag = 1;
 2681:             }
 2682: 	} elsif ($dropMenu eq '') {
 2683: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2684: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2685: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2686: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2687: 		next;
 2688: 	    }
 2689: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2690: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2691: 	    my $partial= $pts/$wgt;
 2692: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2693: 		#do not update score for part if not changed.
 2694:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2695: 		next;
 2696: 	    } else {
 2697: 	        push(@parts_graded,$new_part);
 2698: 	    }
 2699: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2700: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2701: 	    }
 2702: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2703: 	    if ($partial == 0) {
 2704: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2705: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2706: 		}
 2707: 	    } else {
 2708: 		if ($record{$reckey} ne 'correct_by_override') {
 2709: 		    $newrecord{$reckey} = 'correct_by_override';
 2710: 		}
 2711: 	    }	    
 2712: 	    if ($submitter && 
 2713: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2714: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2715: 	    }
 2716: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2717: 		"$env{'user.name'}:$env{'user.domain'}";
 2718: 	}
 2719: 	# unless problem has been graded, set flag to version the submitted files
 2720: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2721: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2722: 	        $dropMenu eq 'reset status')
 2723: 	   {
 2724: 	    push(@version_parts,$new_part);
 2725: 	}
 2726:     }
 2727:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2728:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2729: 
 2730:     if (%newrecord) {
 2731:         if (@version_parts) {
 2732:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2733:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2734: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2735: 	    foreach my $new_part (@version_parts) {
 2736: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2737: 				$new_part,\%newrecord);
 2738: 	    }
 2739:         }
 2740: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2741: 				$env{'request.course.id'},$domain,$stuname);
 2742: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2743: 				     $cdom,$cnum,$domain,$stuname);
 2744:     }
 2745:     if ($aggregateflag) {
 2746:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2747: 			      $cdom,$cnum);
 2748:     }
 2749:     return ('',$pts,$wgt);
 2750: }
 2751: 
 2752: sub check_and_remove_from_queue {
 2753:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2754:     my @ungraded_parts;
 2755:     foreach my $part (@{$parts}) {
 2756: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2757: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2758: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2759: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2760: 		) {
 2761: 	    push(@ungraded_parts, $part);
 2762: 	}
 2763:     }
 2764:     if ( !@ungraded_parts ) {
 2765: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2766: 					       $cnum,$domain,$stuname);
 2767:     }
 2768: }
 2769: 
 2770: sub handback_files {
 2771:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2772:     my $portfolio_root = '/userfiles/portfolio';
 2773:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2774: 
 2775:     my @part_response_id = &flatten_responseType($responseType);
 2776:     foreach my $part_response_id (@part_response_id) {
 2777:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2778: 	my $part_resp = join('_',@{ $part_response_id });
 2779:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2780:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2781:                 my $file_counter = 1;
 2782: 		my $file_msg;
 2783:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2784:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2785:                     my ($directory,$answer_file) = 
 2786:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2787:                     my ($answer_name,$answer_ver,$answer_ext) =
 2788: 		        &file_name_version_ext($answer_file);
 2789: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2790:                     my $getpropath = 1;
 2791: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2792: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2793:                     # fix file name
 2794:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2795:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2796:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2797:             	                                $save_file_name);
 2798:                     if ($result !~ m|^/uploaded/|) {
 2799:                         $request->print('<br /><span class="LC_error">'.
 2800:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2801:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2802:                                         '</span>');
 2803:                     } else {
 2804:                         # mark the file as read only
 2805:                         my @files = ($save_file_name);
 2806:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2807:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2808: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2809: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2810: 			}
 2811:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2812: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2813: 
 2814:                     }
 2815:                     $request->print("<br />".$fname." will be the uploaded file name");
 2816:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2817:                     $file_counter++;
 2818:                 }
 2819: 		my $subject = "File Handed Back by Instructor ";
 2820: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2821: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2822: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2823: 		$message .= " and can be found in your portfolio space.";
 2824: 		my ($feedurl,$showsymb) = 
 2825: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2826:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2827: 		my $msgstatus = 
 2828:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2829: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2830:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2831:             }
 2832:         }
 2833:     return;
 2834: }
 2835: 
 2836: sub get_feedurl_and_symb {
 2837:     my ($symb,$uname,$udom) = @_;
 2838:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2839:     $url = &Apache::lonnet::clutter($url);
 2840:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2841: 					$symb,$udom,$uname);
 2842:     if ($encrypturl =~ /^yes$/i) {
 2843: 	&Apache::lonenc::encrypted(\$url,1);
 2844: 	&Apache::lonenc::encrypted(\$symb,1);
 2845:     }
 2846:     return ($url,$symb);
 2847: }
 2848: 
 2849: sub get_submitted_files {
 2850:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2851:     my @files;
 2852:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2853:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2854:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2855:     	    push(@files,$file_url.$file);
 2856:         }
 2857:     }
 2858:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2859:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2860:     }
 2861:     return (\@files);
 2862: }
 2863: 
 2864: # ----------- Provides number of tries since last reset.
 2865: sub get_num_tries {
 2866:     my ($record,$last_reset,$part) = @_;
 2867:     my $timestamp = '';
 2868:     my $num_tries = 0;
 2869:     if ($$record{'version'}) {
 2870:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2871:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2872:                 $timestamp = $$record{$version.':timestamp'};
 2873:                 if ($timestamp > $last_reset) {
 2874:                     $num_tries ++;
 2875:                 } else {
 2876:                     last;
 2877:                 }
 2878:             }
 2879:         }
 2880:     }
 2881:     return $num_tries;
 2882: }
 2883: 
 2884: # ----------- Determine decrements required in aggregate totals 
 2885: sub decrement_aggs {
 2886:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2887:     my %decrement = (
 2888:                         attempts => 0,
 2889:                         users => 0,
 2890:                         correct => 0
 2891:                     );
 2892:     $decrement{'attempts'} = $aggtries;
 2893:     if ($solvedstatus =~ /^correct/) {
 2894:         $decrement{'correct'} = 1;
 2895:     }
 2896:     if ($aggtries == $totaltries) {
 2897:         $decrement{'users'} = 1;
 2898:     }
 2899:     foreach my $type (keys(%decrement)) {
 2900:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2901:     }
 2902:     return;
 2903: }
 2904: 
 2905: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2906: sub get_last_resets {
 2907:     my ($symb,$courseid,$partids) =@_;
 2908:     my %last_resets;
 2909:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2910:     my $cname = $env{'course.'.$courseid.'.num'};
 2911:     my @keys;
 2912:     foreach my $part (@{$partids}) {
 2913: 	push(@keys,"$symb\0$part\0resettime");
 2914:     }
 2915:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2916: 				     $cdom,$cname);
 2917:     foreach my $part (@{$partids}) {
 2918: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2919:     }
 2920:     return %last_resets;
 2921: }
 2922: 
 2923: # ----------- Handles creating versions for portfolio files as answers
 2924: sub version_portfiles {
 2925:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2926:     my $version_parts = join('|',@$v_flag);
 2927:     my @returned_keys;
 2928:     my $parts = join('|', @$parts_graded);
 2929:     my $portfolio_root = '/userfiles/portfolio';
 2930:     foreach my $key (keys(%$record)) {
 2931:         my $new_portfiles;
 2932:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2933:             my @versioned_portfiles;
 2934:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2935:             foreach my $file (@portfiles) {
 2936:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2937:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2938: 		my ($answer_name,$answer_ver,$answer_ext) =
 2939: 		    &file_name_version_ext($answer_file);
 2940:                 my $getpropath = 1;    
 2941:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2942:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2943:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2944:                 if ($new_answer ne 'problem getting file') {
 2945:                     push(@versioned_portfiles, $directory.$new_answer);
 2946:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2947:                         [$directory.$new_answer],
 2948:                         [$symb,$env{'request.course.id'},'graded']);
 2949:                 }
 2950:             }
 2951:             $$record{$key} = join(',',@versioned_portfiles);
 2952:             push(@returned_keys,$key);
 2953:         }
 2954:     } 
 2955:     return (@returned_keys);   
 2956: }
 2957: 
 2958: sub get_next_version {
 2959:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2960:     my $version;
 2961:     foreach my $row (@$dir_list) {
 2962:         my ($file) = split(/\&/,$row,2);
 2963:         my ($file_name,$file_version,$file_ext) =
 2964: 	    &file_name_version_ext($file);
 2965:         if (($file_name eq $answer_name) && 
 2966: 	    ($file_ext eq $answer_ext)) {
 2967:                 # gets here if filename and extension match, regardless of version
 2968:                 if ($file_version ne '') {
 2969:                 # a versioned file is found  so save it for later
 2970:                 if ($file_version > $version) {
 2971: 		    $version = $file_version;
 2972: 	        }
 2973:             }
 2974:         }
 2975:     } 
 2976:     $version ++;
 2977:     return($version);
 2978: }
 2979: 
 2980: sub version_selected_portfile {
 2981:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2982:     my ($answer_name,$answer_ver,$answer_ext) =
 2983:         &file_name_version_ext($file_name);
 2984:     my $new_answer;
 2985:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2986:     if($env{'form.copy'} eq '-1') {
 2987:         $new_answer = 'problem getting file';
 2988:     } else {
 2989:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2990:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2991:                             $stu_name,$domain,'copy',
 2992: 		        '/portfolio'.$directory.$new_answer);
 2993:     }    
 2994:     return ($new_answer);
 2995: }
 2996: 
 2997: sub file_name_version_ext {
 2998:     my ($file)=@_;
 2999:     my @file_parts = split(/\./, $file);
 3000:     my ($name,$version,$ext);
 3001:     if (@file_parts > 1) {
 3002: 	$ext=pop(@file_parts);
 3003: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3004: 	    $version=pop(@file_parts);
 3005: 	}
 3006: 	$name=join('.',@file_parts);
 3007:     } else {
 3008: 	$name=join('.',@file_parts);
 3009:     }
 3010:     return($name,$version,$ext);
 3011: }
 3012: 
 3013: #--------------------------------------------------------------------------------------
 3014: #
 3015: #-------------------------- Next few routines handles grading by section or whole class
 3016: #
 3017: #--- Javascript to handle grading by section or whole class
 3018: sub viewgrades_js {
 3019:     my ($request) = shift;
 3020: 
 3021:     $request->print(<<VIEWJAVASCRIPT);
 3022: <script type="text/javascript" language="javascript">
 3023:    function writePoint(partid,weight,point) {
 3024: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3025: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3026: 	if (point == "textval") {
 3027: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3028: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3029: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3030: 		var resetbox = false;
 3031: 		for (var i=0; i<radioButton.length; i++) {
 3032: 		    if (radioButton[i].checked) {
 3033: 			textbox.value = i;
 3034: 			resetbox = true;
 3035: 		    }
 3036: 		}
 3037: 		if (!resetbox) {
 3038: 		    textbox.value = "";
 3039: 		}
 3040: 		return;
 3041: 	    }
 3042: 	    if (parseFloat(point) > parseFloat(weight)) {
 3043: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3044: 				   ") greater than the weight for the part. Accept?");
 3045: 		if (resp == false) {
 3046: 		    textbox.value = "";
 3047: 		    return;
 3048: 		}
 3049: 	    }
 3050: 	    for (var i=0; i<radioButton.length; i++) {
 3051: 		radioButton[i].checked=false;
 3052: 		if (parseFloat(point) == i) {
 3053: 		    radioButton[i].checked=true;
 3054: 		}
 3055: 	    }
 3056: 
 3057: 	} else {
 3058: 	    textbox.value = parseFloat(point);
 3059: 	}
 3060: 	for (i=0;i<document.classgrade.total.value;i++) {
 3061: 	    var user = document.classgrade["ctr"+i].value;
 3062: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3063: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3064: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3065: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3066: 	    if (saveval != "correct") {
 3067: 		scorename.value = point;
 3068: 		if (selname[0].selected != true) {
 3069: 		    selname[0].selected = true;
 3070: 		}
 3071: 	    }
 3072: 	}
 3073: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3074:     }
 3075: 
 3076:     function writeRadText(partid,weight) {
 3077: 	var selval   = document.classgrade["SELVAL_"+partid];
 3078: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3079:         var override = document.classgrade["FORCE_"+partid].checked;
 3080: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3081: 	if (selval[1].selected || selval[2].selected) {
 3082: 	    for (var i=0; i<radioButton.length; i++) {
 3083: 		radioButton[i].checked=false;
 3084: 
 3085: 	    }
 3086: 	    textbox.value = "";
 3087: 
 3088: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3089: 		var user = document.classgrade["ctr"+i].value;
 3090: 		user = user.replace(new RegExp(':', 'g'),"_");
 3091: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3092: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3093: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3094: 		if ((saveval != "correct") || override) {
 3095: 		    scorename.value = "";
 3096: 		    if (selval[1].selected) {
 3097: 			selname[1].selected = true;
 3098: 		    } else {
 3099: 			selname[2].selected = true;
 3100: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3101: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3102: 		    }
 3103: 		}
 3104: 	    }
 3105: 	} else {
 3106: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3107: 		var user = document.classgrade["ctr"+i].value;
 3108: 		user = user.replace(new RegExp(':', 'g'),"_");
 3109: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3110: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3111: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3112: 		if ((saveval != "correct") || override) {
 3113: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3114: 		    selname[0].selected = true;
 3115: 		}
 3116: 	    }
 3117: 	}	    
 3118:     }
 3119: 
 3120:     function changeSelect(partid,user) {
 3121: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3122: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3123: 	var point  = textbox.value;
 3124: 	var weight = document.classgrade["weight_"+partid].value;
 3125: 
 3126: 	if (isNaN(point) || parseFloat(point) < 0) {
 3127: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3128: 	    textbox.value = "";
 3129: 	    return;
 3130: 	}
 3131: 	if (parseFloat(point) > parseFloat(weight)) {
 3132: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3133: 			       ") greater than the weight of the part. Accept?");
 3134: 	    if (resp == false) {
 3135: 		textbox.value = "";
 3136: 		return;
 3137: 	    }
 3138: 	}
 3139: 	selval[0].selected = true;
 3140:     }
 3141: 
 3142:     function changeOneScore(partid,user) {
 3143: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3144: 	if (selval[1].selected || selval[2].selected) {
 3145: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3146: 	    if (selval[2].selected) {
 3147: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3148: 	    }
 3149:         }
 3150:     }
 3151: 
 3152:     function resetEntry(numpart) {
 3153: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3154: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3155: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3156: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3157: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3158: 	    for (var i=0; i<radioButton.length; i++) {
 3159: 		radioButton[i].checked=false;
 3160: 
 3161: 	    }
 3162: 	    textbox.value = "";
 3163: 	    selval[0].selected = true;
 3164: 
 3165: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3166: 		var user = document.classgrade["ctr"+i].value;
 3167: 		user = user.replace(new RegExp(':', 'g'),"_");
 3168: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3169: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3170: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3171: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3172: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3173: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3174: 		if (saveselval == "excused") {
 3175: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3176: 		} else {
 3177: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3178: 		}
 3179: 	    }
 3180: 	}
 3181:     }
 3182: 
 3183: </script>
 3184: VIEWJAVASCRIPT
 3185: }
 3186: 
 3187: #--- show scores for a section or whole class w/ option to change/update a score
 3188: sub viewgrades {
 3189:     my ($request) = shift;
 3190:     &viewgrades_js($request);
 3191: 
 3192:     my ($symb) = &get_symb($request);
 3193:     #need to make sure we have the correct data for later EXT calls, 
 3194:     #thus invalidate the cache
 3195:     &Apache::lonnet::devalidatecourseresdata(
 3196:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3197:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3198:     &Apache::lonnet::clear_EXT_cache_status();
 3199: 
 3200:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3201:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3202: 
 3203:     #view individual student submission form - called using Javascript viewOneStudent
 3204:     $result.=&jscriptNform($symb);
 3205: 
 3206:     #beginning of class grading form
 3207:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3208:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3209: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3210: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3211: 	&build_section_inputs().
 3212: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3213: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3214: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3215: 
 3216:     my $sectionClass;
 3217:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3218:     if ($env{'form.section'} eq 'all') {
 3219: 	$sectionClass='Class';
 3220:     } elsif ($env{'form.section'} eq 'none') {
 3221: 	$sectionClass='Students in no Section';
 3222:     } else {
 3223: 	$sectionClass='Students in Section(s) [_1]';
 3224:     }
 3225:     $result.=
 3226: 	'<h3>'.
 3227: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3228:     $result.= &Apache::loncommon::start_data_table();
 3229:     #radio buttons/text box for assigning points for a section or class.
 3230:     #handles different parts of a problem
 3231:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3232:     my %weight = ();
 3233:     my $ctsparts = 0;
 3234:     my %seen = ();
 3235:     my @part_response_id = &flatten_responseType($responseType);
 3236:     foreach my $part_response_id (@part_response_id) {
 3237:     	my ($partid,$respid) = @{ $part_response_id };
 3238: 	my $part_resp = join('_',@{ $part_response_id });
 3239: 	next if $seen{$partid};
 3240: 	$seen{$partid}++;
 3241: 	my $handgrade=$$handgrade{$part_resp};
 3242: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3243: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3244: 
 3245: 	my $display_part=&get_display_part($partid,$symb);
 3246: 	my $radio.='<table border="0"><tr>';  
 3247: 	my $ctr = 0;
 3248: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3249: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3250: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3251: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3252: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3253: 	    $ctr++;
 3254: 	}
 3255: 	$radio.='</tr></table>';
 3256: 	my $line = '<input type="text" name="TEXTVAL_'.
 3257: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3258: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3259: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3260: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3261: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3262: 		$weight{$partid}.')"> '.
 3263: 	    '<option selected="selected"> </option>'.
 3264: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3265: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3266: 	    '</select></td>'.
 3267:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3268: 	$line.='<input type="hidden" name="partid_'.
 3269: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3270: 	$line.='<input type="hidden" name="weight_'.
 3271: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3272: 
 3273: 	$result.=
 3274: 	    &Apache::loncommon::start_data_table_row()."\n".
 3275: 	    &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).
 3276: 	    &Apache::loncommon::end_data_table_row()."\n";
 3277: 	$ctsparts++;
 3278:     }
 3279:     $result.=&Apache::loncommon::end_data_table()."\n".
 3280: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3281:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3282: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3283: 
 3284:     #table listing all the students in a section/class
 3285:     #header of table
 3286:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3287: 			 $section_display).'</h3>';
 3288:     $result.= &Apache::loncommon::start_data_table().
 3289: 	&Apache::loncommon::start_data_table_header_row().
 3290: 	'<th>'.&mt('No.').'</th>'.
 3291: 	'<th>'.&nameUserString('header')."</th>\n";
 3292:     my (@parts) = sort(&getpartlist($symb));
 3293:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3294:     my @partids = ();
 3295:     foreach my $part (@parts) {
 3296: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3297: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3298: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3299: 	my ($partid) = &split_part_type($part);
 3300:         push(@partids,$partid);
 3301: 	my $display_part=&get_display_part($partid,$symb);
 3302: 	if ($display =~ /^Partial Credit Factor/) {
 3303: 	    $result.='<th>'.
 3304: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3305: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3306: 	    next;
 3307: 	    
 3308: 	} else {
 3309: 	    if ($display =~ /Problem Status/) {
 3310: 		my $grade_status_mt = &mt('Grade Status');
 3311: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3312: 	    }
 3313: 	    my $part_mt = &mt('Part:');
 3314: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3315: 	}
 3316: 
 3317: 	$result.='<th>'.$display.'</th>'."\n";
 3318:     }
 3319:     $result.=&Apache::loncommon::end_data_table_header_row();
 3320: 
 3321:     my %last_resets = 
 3322: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3323: 
 3324:     #get info for each student
 3325:     #list all the students - with points and grade status
 3326:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3327:     my $ctr = 0;
 3328:     foreach (sort 
 3329: 	     {
 3330: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3331: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3332: 		 }
 3333: 		 return $a cmp $b;
 3334: 	     } (keys(%$fullname))) {
 3335: 	$ctr++;
 3336: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3337: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3338:     }
 3339:     $result.=&Apache::loncommon::end_data_table();
 3340:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3341:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3342: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3343:     if (scalar(%$fullname) eq 0) {
 3344: 	my $colspan=3+scalar(@parts);
 3345: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3346:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3347: 	$result='<span class="LC_warning">'.
 3348: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3349: 	        $section_display, $stu_status).
 3350: 	    '</span>';
 3351:     }
 3352:     $result.=&show_grading_menu_form($symb);
 3353:     return $result;
 3354: }
 3355: 
 3356: #--- call by previous routine to display each student
 3357: sub viewstudentgrade {
 3358:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3359:     my ($uname,$udom) = split(/:/,$student);
 3360:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3361:     my %aggregates = (); 
 3362:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3363: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3364: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3365: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3366: 	'\');" target="_self">'.$fullname.'</a> '.
 3367: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3368:     $student=~s/:/_/; # colon doen't work in javascript for names
 3369:     foreach my $apart (@$parts) {
 3370: 	my ($part,$type) = &split_part_type($apart);
 3371: 	my $score=$record{"resource.$part.$type"};
 3372:         $result.='<td align="center">';
 3373:         my ($aggtries,$totaltries);
 3374:         unless (exists($aggregates{$part})) {
 3375: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3376: 
 3377: 	    $aggtries = $totaltries;
 3378:             if ($$last_resets{$part}) {  
 3379:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3380: 					   $part);
 3381:             }
 3382:             $result.='<input type="hidden" name="'.
 3383:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3384:             $result.='<input type="hidden" name="'.
 3385:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3386:             $aggregates{$part} = 1;
 3387:         }
 3388: 	if ($type eq 'awarded') {
 3389: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3390: 	    $result.='<input type="hidden" name="'.
 3391: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3392: 	    $result.='<input type="text" name="'.
 3393: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3394: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3395: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3396: 	} elsif ($type eq 'solved') {
 3397: 	    my ($status,$foo)=split(/_/,$score,2);
 3398: 	    $status = 'nothing' if ($status eq '');
 3399: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3400: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3401: 	    $result.='&nbsp;<select name="'.
 3402: 		'GD_'.$student.'_'.$part.'_solved" '.
 3403: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3404: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3405: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3406: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3407: 	    $result.="</select>&nbsp;</td>\n";
 3408: 	} else {
 3409: 	    $result.='<input type="hidden" name="'.
 3410: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3411: 		    "\n";
 3412: 	    $result.='<input type="text" name="'.
 3413: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3414: 		'value="'.$score.'" size="4" /></td>'."\n";
 3415: 	}
 3416:     }
 3417:     $result.=&Apache::loncommon::end_data_table_row();
 3418:     return $result;
 3419: }
 3420: 
 3421: #--- change scores for all the students in a section/class
 3422: #    record does not get update if unchanged
 3423: sub editgrades {
 3424:     my ($request) = @_;
 3425: 
 3426:     my $symb=&get_symb($request);
 3427:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3428:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3429:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3430:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3431: 
 3432:     my $result= &Apache::loncommon::start_data_table().
 3433: 	&Apache::loncommon::start_data_table_header_row().
 3434: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3435: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3436:     my %scoreptr = (
 3437: 		    'correct'  =>'correct_by_override',
 3438: 		    'incorrect'=>'incorrect_by_override',
 3439: 		    'excused'  =>'excused',
 3440: 		    'ungraded' =>'ungraded_attempted',
 3441: 		    'nothing'  => '',
 3442: 		    );
 3443:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3444: 
 3445:     my (@partid);
 3446:     my %weight = ();
 3447:     my %columns = ();
 3448:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3449: 
 3450:     my (@parts) = sort(&getpartlist($symb));
 3451:     my $header;
 3452:     while ($ctr < $env{'form.totalparts'}) {
 3453: 	my $partid = $env{'form.partid_'.$ctr};
 3454: 	push(@partid,$partid);
 3455: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3456: 	$ctr++;
 3457:     }
 3458:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3459:     foreach my $partid (@partid) {
 3460: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3461: 	    '<th align="center">'.&mt('New Score').'</th>';
 3462: 	$columns{$partid}=2;
 3463: 	foreach my $stores (@parts) {
 3464: 	    my ($part,$type) = &split_part_type($stores);
 3465: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3466: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3467: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3468: 	    $display =~ s/\[Part: (\w)+\]//;
 3469: 	    $display =~ s/Number of Attempts/Tries/;
 3470: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3471: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3472: 	    $columns{$partid}+=2;
 3473: 	}
 3474:     }
 3475:     foreach my $partid (@partid) {
 3476: 	my $display_part=&get_display_part($partid,$symb);
 3477: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3478: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3479: 	    '</th>';
 3480: 
 3481:     }
 3482:     $result .= &Apache::loncommon::end_data_table_header_row().
 3483: 	&Apache::loncommon::start_data_table_header_row().
 3484: 	$header.
 3485: 	&Apache::loncommon::end_data_table_header_row();
 3486:     my @noupdate;
 3487:     my ($updateCtr,$noupdateCtr) = (1,1);
 3488:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3489: 	my $line;
 3490: 	my $user = $env{'form.ctr'.$i};
 3491: 	my ($uname,$udom)=split(/:/,$user);
 3492: 	my %newrecord;
 3493: 	my $updateflag = 0;
 3494: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3495: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3496: 	if (!&canmodify($usec)) {
 3497: 	    my $numcols=scalar(@partid)*4+2;
 3498: 	    push(@noupdate,
 3499: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3500: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3501: 	    next;
 3502: 	}
 3503:         my %aggregate = ();
 3504:         my $aggregateflag = 0;
 3505: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3506: 	foreach (@partid) {
 3507: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3508: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3509: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3510: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3511: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3512: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3513: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3514: 	    my $score;
 3515: 	    if ($partial eq '') {
 3516: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3517: 	    } elsif ($partial > 0) {
 3518: 		$score = 'correct_by_override';
 3519: 	    } elsif ($partial == 0) {
 3520: 		$score = 'incorrect_by_override';
 3521: 	    }
 3522: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3523: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3524: 
 3525: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3526: 		"$env{'user.name'}:$env{'user.domain'}";
 3527: 	    if ($dropMenu eq 'reset status' &&
 3528: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3529: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3530: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3531: 		$newrecord{'resource.'.$_.'.award'} = '';
 3532: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3533: 		$updateflag = 1;
 3534:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3535:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3536:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3537:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3538:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3539:                     $aggregateflag = 1;
 3540:                 }
 3541: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3542: 		$updateflag = 1;
 3543: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3544: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3545: 		$rec_update++;
 3546: 	    }
 3547: 
 3548: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3549: 		'<td align="center">'.$awarded.
 3550: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3551: 
 3552: 
 3553: 	    my $partid=$_;
 3554: 	    foreach my $stores (@parts) {
 3555: 		my ($part,$type) = &split_part_type($stores);
 3556: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3557: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3558: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3559: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3560: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3561: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3562: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3563: 		    $updateflag=1;
 3564: 		}
 3565: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3566: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3567: 	    }
 3568: 	}
 3569: 	$line.="\n";
 3570: 
 3571: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3572: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3573: 
 3574: 	if ($updateflag) {
 3575: 	    $count++;
 3576: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3577: 				    $udom,$uname);
 3578: 
 3579: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3580: 					      $cnum,$udom,$uname)) {
 3581: 		# need to figure out if should be in queue.
 3582: 		my %record =  
 3583: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3584: 					     $udom,$uname);
 3585: 		my $all_graded = 1;
 3586: 		my $none_graded = 1;
 3587: 		foreach my $part (@parts) {
 3588: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3589: 			$all_graded = 0;
 3590: 		    } else {
 3591: 			$none_graded = 0;
 3592: 		    }
 3593: 		}
 3594: 
 3595: 		if ($all_graded || $none_graded) {
 3596: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3597: 							   $symb,$cdom,$cnum,
 3598: 							   $udom,$uname);
 3599: 		}
 3600: 	    }
 3601: 
 3602: 	    $result.=&Apache::loncommon::start_data_table_row().
 3603: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3604: 		&Apache::loncommon::end_data_table_row();
 3605: 	    $updateCtr++;
 3606: 	} else {
 3607: 	    push(@noupdate,
 3608: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3609: 	    $noupdateCtr++;
 3610: 	}
 3611:         if ($aggregateflag) {
 3612:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3613: 				  $cdom,$cnum);
 3614:         }
 3615:     }
 3616:     if (@noupdate) {
 3617: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3618: 	my $numcols=scalar(@partid)*4+2;
 3619: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3620: 	    '<td align="center" colspan="'.$numcols.'">'.
 3621: 	    &mt('No Changes Occurred For the Students Below').
 3622: 	    '</td>'.
 3623: 	    &Apache::loncommon::end_data_table_row();
 3624: 	foreach my $line (@noupdate) {
 3625: 	    $result.=
 3626: 		&Apache::loncommon::start_data_table_row().
 3627: 		$line.
 3628: 		&Apache::loncommon::end_data_table_row();
 3629: 	}
 3630:     }
 3631:     $result .= &Apache::loncommon::end_data_table().
 3632: 	&show_grading_menu_form($symb);
 3633:     my $msg = '<p><b>'.
 3634: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3635: 	    $rec_update,$count).'</b><br />'.
 3636: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3637: 	'</b></p>';
 3638:     return $title.$msg.$result;
 3639: }
 3640: 
 3641: sub split_part_type {
 3642:     my ($partstr) = @_;
 3643:     my ($temp,@allparts)=split(/_/,$partstr);
 3644:     my $type=pop(@allparts);
 3645:     my $part=join('_',@allparts);
 3646:     return ($part,$type);
 3647: }
 3648: 
 3649: #------------- end of section for handling grading by section/class ---------
 3650: #
 3651: #----------------------------------------------------------------------------
 3652: 
 3653: 
 3654: #----------------------------------------------------------------------------
 3655: #
 3656: #-------------------------- Next few routines handles grading by csv upload
 3657: #
 3658: #--- Javascript to handle csv upload
 3659: sub csvupload_javascript_reverse_associate {
 3660:     my $error1=&mt('You need to specify the username or ID');
 3661:     my $error2=&mt('You need to specify at least one grading field');
 3662:   return(<<ENDPICK);
 3663:   function verify(vf) {
 3664:     var foundsomething=0;
 3665:     var founduname=0;
 3666:     var foundID=0;
 3667:     for (i=0;i<=vf.nfields.value;i++) {
 3668:       tw=eval('vf.f'+i+'.selectedIndex');
 3669:       if (i==0 && tw!=0) { foundID=1; }
 3670:       if (i==1 && tw!=0) { founduname=1; }
 3671:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3672:     }
 3673:     if (founduname==0 && foundID==0) {
 3674: 	alert('$error1');
 3675: 	return;
 3676:     }
 3677:     if (foundsomething==0) {
 3678: 	alert('$error2');
 3679: 	return;
 3680:     }
 3681:     vf.submit();
 3682:   }
 3683:   function flip(vf,tf) {
 3684:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3685:     var i;
 3686:     for (i=0;i<=vf.nfields.value;i++) {
 3687:       //can not pick the same destination field for both name and domain
 3688:       if (((i ==0)||(i ==1)) && 
 3689:           ((tf==0)||(tf==1)) && 
 3690:           (i!=tf) &&
 3691:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3692:         eval('vf.f'+i+'.selectedIndex=0;')
 3693:       }
 3694:     }
 3695:   }
 3696: ENDPICK
 3697: }
 3698: 
 3699: sub csvupload_javascript_forward_associate {
 3700:     my $error1=&mt('You need to specify the username or ID');
 3701:     my $error2=&mt('You need to specify at least one grading field');
 3702:   return(<<ENDPICK);
 3703:   function verify(vf) {
 3704:     var foundsomething=0;
 3705:     var founduname=0;
 3706:     var foundID=0;
 3707:     for (i=0;i<=vf.nfields.value;i++) {
 3708:       tw=eval('vf.f'+i+'.selectedIndex');
 3709:       if (tw==1) { foundID=1; }
 3710:       if (tw==2) { founduname=1; }
 3711:       if (tw>3) { foundsomething=1; }
 3712:     }
 3713:     if (founduname==0 && foundID==0) {
 3714: 	alert('$error1');
 3715: 	return;
 3716:     }
 3717:     if (foundsomething==0) {
 3718: 	alert('$error2');
 3719: 	return;
 3720:     }
 3721:     vf.submit();
 3722:   }
 3723:   function flip(vf,tf) {
 3724:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3725:     var i;
 3726:     //can not pick the same destination field twice
 3727:     for (i=0;i<=vf.nfields.value;i++) {
 3728:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3729:         eval('vf.f'+i+'.selectedIndex=0;')
 3730:       }
 3731:     }
 3732:   }
 3733: ENDPICK
 3734: }
 3735: 
 3736: sub csvuploadmap_header {
 3737:     my ($request,$symb,$datatoken,$distotal)= @_;
 3738:     my $javascript;
 3739:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3740: 	$javascript=&csvupload_javascript_reverse_associate();
 3741:     } else {
 3742: 	$javascript=&csvupload_javascript_forward_associate();
 3743:     }
 3744: 
 3745:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3746:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3747:     my $ignore=&mt('Ignore First Line');
 3748:     $symb = &Apache::lonenc::check_encrypt($symb);
 3749:     $request->print(<<ENDPICK);
 3750: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3751: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3752: $result
 3753: <hr />
 3754: <h3>Identify fields</h3>
 3755: Total number of records found in file: $distotal <hr />
 3756: Enter as many fields as you can. The system will inform you and bring you back
 3757: to this page if the data selected is insufficient to run your class.<hr />
 3758: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3759: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3760: <input type="hidden" name="associate"  value="" />
 3761: <input type="hidden" name="phase"      value="three" />
 3762: <input type="hidden" name="datatoken"  value="$datatoken" />
 3763: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3764: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3765: <input type="hidden" name="upfile_associate" 
 3766:                                        value="$env{'form.upfile_associate'}" />
 3767: <input type="hidden" name="symb"       value="$symb" />
 3768: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3769: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3770: <input type="hidden" name="command"    value="csvuploadoptions" />
 3771: <hr />
 3772: <script type="text/javascript" language="Javascript">
 3773: $javascript
 3774: </script>
 3775: ENDPICK
 3776:     return '';
 3777: 
 3778: }
 3779: 
 3780: sub csvupload_fields {
 3781:     my ($symb) = @_;
 3782:     my (@parts) = &getpartlist($symb);
 3783:     my @fields=(['ID','Student ID'],
 3784: 		['username','Student Username'],
 3785: 		['domain','Student Domain']);
 3786:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3787:     foreach my $part (sort(@parts)) {
 3788: 	my @datum;
 3789: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3790: 	my $name=$part;
 3791: 	if  (!$display) { $display = $name; }
 3792: 	@datum=($name,$display);
 3793: 	if ($name=~/^stores_(.*)_awarded/) {
 3794: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3795: 	}
 3796: 	push(@fields,\@datum);
 3797:     }
 3798:     return (@fields);
 3799: }
 3800: 
 3801: sub csvuploadmap_footer {
 3802:     my ($request,$i,$keyfields) =@_;
 3803:     $request->print(<<ENDPICK);
 3804: </table>
 3805: <input type="hidden" name="nfields" value="$i" />
 3806: <input type="hidden" name="keyfields" value="$keyfields" />
 3807: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3808: </form>
 3809: ENDPICK
 3810: }
 3811: 
 3812: sub checkforfile_js {
 3813:     my $result =<<CSVFORMJS;
 3814: <script type="text/javascript" language="javascript">
 3815:     function checkUpload(formname) {
 3816: 	if (formname.upfile.value == "") {
 3817: 	    alert("Please use the browse button to select a file from your local directory.");
 3818: 	    return false;
 3819: 	}
 3820: 	formname.submit();
 3821:     }
 3822:     </script>
 3823: CSVFORMJS
 3824:     return $result;
 3825: }
 3826: 
 3827: sub upcsvScores_form {
 3828:     my ($request) = shift;
 3829:     my ($symb)=&get_symb($request);
 3830:     if (!$symb) {return '';}
 3831:     my $result=&checkforfile_js();
 3832:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3833:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3834:     $result.=$table;
 3835:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3836:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3837:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3838: 	'.</b></td></tr>'."\n";
 3839:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3840:     my $upload=&mt("Upload Scores");
 3841:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3842:     my $ignore=&mt('Ignore First Line');
 3843:     $symb = &Apache::lonenc::check_encrypt($symb);
 3844:     $result.=<<ENDUPFORM;
 3845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3846: <input type="hidden" name="symb" value="$symb" />
 3847: <input type="hidden" name="command" value="csvuploadmap" />
 3848: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3849: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3850: $upfile_select
 3851: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3852: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3853: </form>
 3854: ENDUPFORM
 3855:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3856:                            &mt("How do I create a CSV file from a spreadsheet"))
 3857:     .'</td></tr></table>'."\n";
 3858:     $result.='</td></tr></table><br /><br />'."\n";
 3859:     $result.=&show_grading_menu_form($symb);
 3860:     return $result;
 3861: }
 3862: 
 3863: 
 3864: sub csvuploadmap {
 3865:     my ($request)= @_;
 3866:     my ($symb)=&get_symb($request);
 3867:     if (!$symb) {return '';}
 3868: 
 3869:     my $datatoken;
 3870:     if (!$env{'form.datatoken'}) {
 3871: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3872:     } else {
 3873: 	$datatoken=$env{'form.datatoken'};
 3874: 	&Apache::loncommon::load_tmp_file($request);
 3875:     }
 3876:     my @records=&Apache::loncommon::upfile_record_sep();
 3877:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3878:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3879:     my ($i,$keyfields);
 3880:     if (@records) {
 3881: 	my @fields=&csvupload_fields($symb);
 3882: 
 3883: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3884: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3885: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3886: 							  \@fields);
 3887: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3888: 	    chop($keyfields);
 3889: 	} else {
 3890: 	    unshift(@fields,['none','']);
 3891: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3892: 							    \@fields);
 3893:             foreach my $rec (@records) {
 3894:                 my %temp = &Apache::loncommon::record_sep($rec);
 3895:                 if (%temp) {
 3896:                     $keyfields=join(',',sort(keys(%temp)));
 3897:                     last;
 3898:                 }
 3899:             }
 3900: 	}
 3901:     }
 3902:     &csvuploadmap_footer($request,$i,$keyfields);
 3903:     $request->print(&show_grading_menu_form($symb));
 3904: 
 3905:     return '';
 3906: }
 3907: 
 3908: sub csvuploadoptions {
 3909:     my ($request)= @_;
 3910:     my ($symb)=&get_symb($request);
 3911:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3912:     my $ignore=&mt('Ignore First Line');
 3913:     $request->print(<<ENDPICK);
 3914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3915: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3916: <input type="hidden" name="command"    value="csvuploadassign" />
 3917: <!--
 3918: <p>
 3919: <label>
 3920:    <input type="checkbox" name="show_full_results" />
 3921:    Show a table of all changes
 3922: </label>
 3923: </p>
 3924: -->
 3925: <p>
 3926: <label>
 3927:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3928:    Overwrite any existing score
 3929: </label>
 3930: </p>
 3931: ENDPICK
 3932:     my %fields=&get_fields();
 3933:     if (!defined($fields{'domain'})) {
 3934: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3935: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3936:     }
 3937:     foreach my $key (sort(keys(%env))) {
 3938: 	if ($key !~ /^form\.(.*)$/) { next; }
 3939: 	my $cleankey=$1;
 3940: 	if ($cleankey eq 'command') { next; }
 3941: 	$request->print('<input type="hidden" name="'.$cleankey.
 3942: 			'"  value="'.$env{$key}.'" />'."\n");
 3943:     }
 3944:     # FIXME do a check for any duplicated user ids...
 3945:     # FIXME do a check for any invalid user ids?...
 3946:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3947: <hr /></form>'."\n");
 3948:     $request->print(&show_grading_menu_form($symb));
 3949:     return '';
 3950: }
 3951: 
 3952: sub get_fields {
 3953:     my %fields;
 3954:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3955:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3956: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3957: 	    if ($env{'form.f'.$i} ne 'none') {
 3958: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3959: 	    }
 3960: 	} else {
 3961: 	    if ($env{'form.f'.$i} ne 'none') {
 3962: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3963: 	    }
 3964: 	}
 3965:     }
 3966:     return %fields;
 3967: }
 3968: 
 3969: sub csvuploadassign {
 3970:     my ($request)= @_;
 3971:     my ($symb)=&get_symb($request);
 3972:     if (!$symb) {return '';}
 3973:     my $error_msg = '';
 3974:     &Apache::loncommon::load_tmp_file($request);
 3975:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3976:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3977:     my %fields=&get_fields();
 3978:     $request->print('<h3>Assigning Grades</h3>');
 3979:     my $courseid=$env{'request.course.id'};
 3980:     my ($classlist) = &getclasslist('all',0);
 3981:     my @notallowed;
 3982:     my @skipped;
 3983:     my $countdone=0;
 3984:     foreach my $grade (@gradedata) {
 3985: 	my %entries=&Apache::loncommon::record_sep($grade);
 3986: 	my $domain;
 3987: 	if ($entries{$fields{'domain'}}) {
 3988: 	    $domain=$entries{$fields{'domain'}};
 3989: 	} else {
 3990: 	    $domain=$env{'form.default_domain'};
 3991: 	}
 3992: 	$domain=~s/\s//g;
 3993: 	my $username=$entries{$fields{'username'}};
 3994: 	$username=~s/\s//g;
 3995: 	if (!$username) {
 3996: 	    my $id=$entries{$fields{'ID'}};
 3997: 	    $id=~s/\s//g;
 3998: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3999: 	    $username=$ids{$id};
 4000: 	}
 4001: 	if (!exists($$classlist{"$username:$domain"})) {
 4002: 	    my $id=$entries{$fields{'ID'}};
 4003: 	    $id=~s/\s//g;
 4004: 	    if ($id) {
 4005: 		push(@skipped,"$id:$domain");
 4006: 	    } else {
 4007: 		push(@skipped,"$username:$domain");
 4008: 	    }
 4009: 	    next;
 4010: 	}
 4011: 	my $usec=$classlist->{"$username:$domain"}[5];
 4012: 	if (!&canmodify($usec)) {
 4013: 	    push(@notallowed,"$username:$domain");
 4014: 	    next;
 4015: 	}
 4016: 	my %points;
 4017: 	my %grades;
 4018: 	foreach my $dest (keys(%fields)) {
 4019: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4020: 		$dest eq 'domain') { next; }
 4021: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4022: 	    if ($dest=~/stores_(.*)_points/) {
 4023: 		my $part=$1;
 4024: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4025: 					      $symb,$domain,$username);
 4026:                 if ($wgt) {
 4027:                     $entries{$fields{$dest}}=~s/\s//g;
 4028:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4029:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4030:                                           : 'correct_by_override';
 4031:                     $grades{"resource.$part.awarded"}=$pcr;
 4032:                     $grades{"resource.$part.solved"}=$award;
 4033:                     $points{$part}=1;
 4034:                 } else {
 4035:                     $error_msg = "<br />" .
 4036:                         &mt("Some point values were assigned"
 4037:                             ." for problems with a weight "
 4038:                             ."of zero. These values were "
 4039:                             ."ignored.");
 4040:                 }
 4041: 	    } else {
 4042: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4043: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4044: 		my $store_key=$dest;
 4045: 		$store_key=~s/^stores/resource/;
 4046: 		$store_key=~s/_/\./g;
 4047: 		$grades{$store_key}=$entries{$fields{$dest}};
 4048: 	    }
 4049: 	}
 4050: 	if (! %grades) { 
 4051:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4052:         } else {
 4053: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4054: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4055: 					   $env{'request.course.id'},
 4056: 					   $domain,$username);
 4057: 	   if ($result eq 'ok') {
 4058: 	      $request->print('.');
 4059: 	   } else {
 4060: 	      $request->print("<p><span class=\"LC_error\">".
 4061:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4062:                                   "$username:$domain",$result)."</span></p>");
 4063: 	   }
 4064: 	   $request->rflush();
 4065: 	   $countdone++;
 4066:         }
 4067:     }
 4068:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4069:     if (@skipped) {
 4070: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4071: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4072:     }
 4073:     if (@notallowed) {
 4074: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4075: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4076:     }
 4077:     $request->print("<br />\n");
 4078:     $request->print(&show_grading_menu_form($symb));
 4079:     return $error_msg;
 4080: }
 4081: #------------- end of section for handling csv file upload ---------
 4082: #
 4083: #-------------------------------------------------------------------
 4084: #
 4085: #-------------- Next few routines handle grading by page/sequence
 4086: #
 4087: #--- Select a page/sequence and a student to grade
 4088: sub pickStudentPage {
 4089:     my ($request) = shift;
 4090: 
 4091:     $request->print(<<LISTJAVASCRIPT);
 4092: <script type="text/javascript" language="javascript">
 4093: 
 4094: function checkPickOne(formname) {
 4095:     if (radioSelection(formname.student) == null) {
 4096: 	alert("Please select the student you wish to grade.");
 4097: 	return;
 4098:     }
 4099:     ptr = pullDownSelection(formname.selectpage);
 4100:     formname.page.value = formname["page"+ptr].value;
 4101:     formname.title.value = formname["title"+ptr].value;
 4102:     formname.submit();
 4103: }
 4104: 
 4105: </script>
 4106: LISTJAVASCRIPT
 4107:     &commonJSfunctions($request);
 4108:     my ($symb) = &get_symb($request);
 4109:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4110:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4111:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4112: 
 4113:     my $result='<h3><span class="LC_info">&nbsp;'.
 4114: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4115: 
 4116:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4117:     my ($titles,$symbx) = &getSymbMap();
 4118:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4119: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4120: #    my $type=($curpage =~ /\.(page|sequence)/);
 4121:     my $select = '<select name="selectpage">'."\n";
 4122:     my $ctr=0;
 4123:     foreach (@$titles) {
 4124: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4125: 	$select.='<option value="'.$ctr.'" '.
 4126: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4127: 	    '>'.$showtitle.'</option>'."\n";
 4128: 	$ctr++;
 4129:     }
 4130:     $select.= '</select>';
 4131:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4132: 
 4133:     $ctr=0;
 4134:     foreach (@$titles) {
 4135: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4136: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4137: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4138: 	$ctr++;
 4139:     }
 4140:     $result.='<input type="hidden" name="page" />'."\n".
 4141: 	'<input type="hidden" name="title" />'."\n";
 4142: 
 4143:     my $options =
 4144: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4145: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4146:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4147: 
 4148:     $options =
 4149: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4150: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4151: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4152:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4153:     
 4154:     $result.=&build_section_inputs();
 4155:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4156:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4157: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4158: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4159: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4160: 
 4161:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4162: 			  '<input type="text" name="CODE" value="" />').
 4163: 			      '<br />'."\n";
 4164: 
 4165:     $result.='&nbsp;<input type="button" '.
 4166: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4167: 
 4168:     $request->print($result);
 4169: 
 4170:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4171: 	&Apache::loncommon::start_data_table().
 4172: 	&Apache::loncommon::start_data_table_header_row().
 4173: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4174: 	'<th>'.&nameUserString('header').'</th>'.
 4175: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4176: 	'<th>'.&nameUserString('header').'</th>'.
 4177: 	&Apache::loncommon::end_data_table_header_row();
 4178:  
 4179:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4180:     my $ptr = 1;
 4181:     foreach my $student (sort 
 4182: 			 {
 4183: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4184: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4185: 			     }
 4186: 			     return $a cmp $b;
 4187: 			 } (keys(%$fullname))) {
 4188: 	my ($uname,$udom) = split(/:/,$student);
 4189: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4190:                                   : '</td>');
 4191: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4192: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4193: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4194: 	$studentTable.=
 4195: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4196:                          : '');
 4197: 	$ptr++;
 4198:     }
 4199:     if ($ptr%2 == 0) {
 4200: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4201: 	    &Apache::loncommon::end_data_table_row();
 4202:     }
 4203:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4204:     $studentTable.='<input type="button" '.
 4205: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4206: 
 4207:     $studentTable.=&show_grading_menu_form($symb);
 4208:     $request->print($studentTable);
 4209: 
 4210:     return '';
 4211: }
 4212: 
 4213: sub getSymbMap {
 4214:     my $navmap = Apache::lonnavmaps::navmap->new();
 4215: 
 4216:     my %symbx = ();
 4217:     my @titles = ();
 4218:     my $minder = 0;
 4219: 
 4220:     # Gather every sequence that has problems.
 4221:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4222: 					       1,0,1);
 4223:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4224: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4225: 	    my $title = $minder.'.'.
 4226: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4227: 	    push(@titles, $title); # minder in case two titles are identical
 4228: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4229: 	    $minder++;
 4230: 	}
 4231:     }
 4232:     return \@titles,\%symbx;
 4233: }
 4234: 
 4235: #
 4236: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4237: sub displayPage {
 4238:     my ($request) = shift;
 4239: 
 4240:     my ($symb) = &get_symb($request);
 4241:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4242:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4243:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4244:     my $pageTitle = $env{'form.page'};
 4245:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4246:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4247:     my $usec=$classlist->{$env{'form.student'}}[5];
 4248: 
 4249:     #need to make sure we have the correct data for later EXT calls, 
 4250:     #thus invalidate the cache
 4251:     &Apache::lonnet::devalidatecourseresdata(
 4252:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4253:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4254:     &Apache::lonnet::clear_EXT_cache_status();
 4255: 
 4256:     if (!&canview($usec)) {
 4257: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4258: 	$request->print(&show_grading_menu_form($symb));
 4259: 	return;
 4260:     }
 4261:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4262:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4263: 	'</h3>'."\n";
 4264:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4265:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4266: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4267:     } else {
 4268: 	delete($env{'form.CODE'});
 4269:     }
 4270:     &sub_page_js($request);
 4271:     $request->print($result);
 4272: 
 4273:     my $navmap = Apache::lonnavmaps::navmap->new();
 4274:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4275:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4276:     if (!$map) {
 4277: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4278: 	$request->print(&show_grading_menu_form($symb));
 4279: 	return; 
 4280:     }
 4281:     my $iterator = $navmap->getIterator($map->map_start(),
 4282: 					$map->map_finish());
 4283: 
 4284:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4285: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4286: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4287: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4288: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4289: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4290: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4291: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4292: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4293: 
 4294:     if (defined($env{'form.CODE'})) {
 4295: 	$studentTable.=
 4296: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4297:     }
 4298:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4299: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4300: 
 4301:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4302: 	&Apache::loncommon::start_data_table().
 4303: 	&Apache::loncommon::start_data_table_header_row().
 4304: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4305: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4306: 	&Apache::loncommon::end_data_table_header_row();
 4307: 
 4308:     &Apache::lonxml::clear_problem_counter();
 4309:     my ($depth,$question,$prob) = (1,1,1);
 4310:     $iterator->next(); # skip the first BEGIN_MAP
 4311:     my $curRes = $iterator->next(); # for "current resource"
 4312:     while ($depth > 0) {
 4313:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4314:         if($curRes == $iterator->END_MAP) { $depth--; }
 4315: 
 4316:         if (ref($curRes) && $curRes->is_problem()) {
 4317: 	    my $parts = $curRes->parts();
 4318:             my $title = $curRes->compTitle();
 4319: 	    my $symbx = $curRes->symb();
 4320: 	    $studentTable.=
 4321: 		&Apache::loncommon::start_data_table_row().
 4322: 		'<td align="center" valign="top" >'.$prob.
 4323: 		(scalar(@{$parts}) == 1 ? '' 
 4324: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4325: 							scalar(@{$parts}))
 4326: 		 ).
 4327: 		 '</td>';
 4328: 	    $studentTable.='<td valign="top">';
 4329: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4330: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4331: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4332: 					     undef,'both',\%form);
 4333: 	    } else {
 4334: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4335: 		$companswer =~ s|<form(.*?)>||g;
 4336: 		$companswer =~ s|</form>||g;
 4337: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4338: #		    $companswer =~ s/$1/ /ms;
 4339: #		    $request->print('match='.$1."<br />\n");
 4340: #		}
 4341: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4342: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4343: 	    }
 4344: 
 4345: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4346: 
 4347: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4348: 		if ($record{'version'} eq '') {
 4349: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4350: 		} else {
 4351: 		    my %responseType = ();
 4352: 		    foreach my $partid (@{$parts}) {
 4353: 			my @responseIds =$curRes->responseIds($partid);
 4354: 			my @responseType =$curRes->responseType($partid);
 4355: 			my %responseIds;
 4356: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4357: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4358: 			}
 4359: 			$responseType{$partid} = \%responseIds;
 4360: 		    }
 4361: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4362: 
 4363: 		}
 4364: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4365: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4366: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4367: 									$env{'request.course.id'},
 4368: 									'','.submission');
 4369:  
 4370: 	    }
 4371: 	    if (&canmodify($usec)) {
 4372: 		foreach my $partid (@{$parts}) {
 4373: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4374: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4375: 		    $question++;
 4376: 		}
 4377: 		$prob++;
 4378: 	    }
 4379: 	    $studentTable.='</td></tr>';
 4380: 
 4381: 	}
 4382:         $curRes = $iterator->next();
 4383:     }
 4384: 
 4385:     $studentTable.='</table>'."\n".
 4386: 	'<input type="button" value="'.&mt('Save').'" '.
 4387: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4388: 	'</form>'."\n";
 4389:     $studentTable.=&show_grading_menu_form($symb);
 4390:     $request->print($studentTable);
 4391: 
 4392:     return '';
 4393: }
 4394: 
 4395: sub displaySubByDates {
 4396:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4397:     my $isCODE=0;
 4398:     my $isTask = ($symb =~/\.task$/);
 4399:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4400:     my $studentTable=&Apache::loncommon::start_data_table().
 4401: 	&Apache::loncommon::start_data_table_header_row().
 4402: 	'<th>'.&mt('Date/Time').'</th>'.
 4403: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4404: 	'<th>'.&mt('Submission').'</th>'.
 4405: 	'<th>'.&mt('Status').'</th>'.
 4406: 	&Apache::loncommon::end_data_table_header_row();
 4407:     my ($version);
 4408:     my %mark;
 4409:     my %orders;
 4410:     $mark{'correct_by_student'} = $checkIcon;
 4411:     if (!exists($$record{'1:timestamp'})) {
 4412: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4413:     }
 4414: 
 4415:     my $interaction;
 4416:     my $no_increment = 1;
 4417:     for ($version=1;$version<=$$record{'version'};$version++) {
 4418: 	my $timestamp = 
 4419: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4420: 	if (exists($$record{$version.':resource.0.version'})) {
 4421: 	    $interaction = $$record{$version.':resource.0.version'};
 4422: 	}
 4423: 
 4424: 	my $where = ($isTask ? "$version:resource.$interaction"
 4425: 		             : "$version:resource");
 4426: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4427: 	    '<td>'.$timestamp.'</td>';
 4428: 	if ($isCODE) {
 4429: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4430: 	}
 4431: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4432: 	my @displaySub = ();
 4433: 	foreach my $partid (@{$parts}) {
 4434: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4435: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4436: 	    
 4437: 
 4438: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4439: 	    my $display_part=&get_display_part($partid,$symb);
 4440: 	    foreach my $matchKey (@matchKey) {
 4441: 		if (exists($$record{$version.':'.$matchKey}) &&
 4442: 		    $$record{$version.':'.$matchKey} ne '') {
 4443: 
 4444: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4445: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4446: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4447: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4448: 			$responseId.')</span>&nbsp;<b>';
 4449: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4450: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4451: 		    } else {
 4452: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4453: 					    $$record{"$where.$partid.tries"});
 4454: 		    }
 4455: 		    my $responseType=($isTask ? 'Task'
 4456:                                               : $responseType->{$partid}->{$responseId});
 4457: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4458: 		    if (!exists($orders{$partid}->{$responseId})) {
 4459: 			$orders{$partid}->{$responseId}=
 4460: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4461:                                        $no_increment);
 4462: 		    }
 4463: 		    $displaySub[0].='</b>&nbsp; '.
 4464: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4465: 		}
 4466: 	    }
 4467: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4468: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4469: 				    $$record{"$where.$partid.checkedin"},
 4470: 				    $$record{"$where.$partid.checkedin.slot"}).
 4471: 					'<br />';
 4472: 	    }
 4473: 	    if (exists $$record{"$where.$partid.award"}) {
 4474: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4475: 		    lc($$record{"$where.$partid.award"}).' '.
 4476: 		    $mark{$$record{"$where.$partid.solved"}}.
 4477: 		    '<br />';
 4478: 	    }
 4479: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4480: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4481: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4482: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4483: 		$displaySub[2].=
 4484: 		    $$record{"$version:resource.$partid.regrader"}.
 4485: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4486: 	    }
 4487: 	}
 4488: 	# needed because old essay regrader has not parts info
 4489: 	if (exists $$record{"$version:resource.regrader"}) {
 4490: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4491: 	}
 4492: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4493: 	if ($displaySub[2]) {
 4494: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4495: 	}
 4496: 	$studentTable.='&nbsp;</td>'.
 4497: 	    &Apache::loncommon::end_data_table_row();
 4498:     }
 4499:     $studentTable.=&Apache::loncommon::end_data_table();
 4500:     return $studentTable;
 4501: }
 4502: 
 4503: sub updateGradeByPage {
 4504:     my ($request) = shift;
 4505: 
 4506:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4507:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4508:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4509:     my $pageTitle = $env{'form.page'};
 4510:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4511:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4512:     my $usec=$classlist->{$env{'form.student'}}[5];
 4513:     if (!&canmodify($usec)) {
 4514: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4515: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4516: 	return;
 4517:     }
 4518:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4519:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4520: 	'</h3>'."\n";
 4521: 
 4522:     $request->print($result);
 4523: 
 4524:     my $navmap = Apache::lonnavmaps::navmap->new();
 4525:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4526:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4527:     if (!$map) {
 4528: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4529: 	my ($symb)=&get_symb($request);
 4530: 	$request->print(&show_grading_menu_form($symb));
 4531: 	return; 
 4532:     }
 4533:     my $iterator = $navmap->getIterator($map->map_start(),
 4534: 					$map->map_finish());
 4535: 
 4536:     my $studentTable=
 4537: 	&Apache::loncommon::start_data_table().
 4538: 	&Apache::loncommon::start_data_table_header_row().
 4539: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4540: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4541: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4542: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4543: 	&Apache::loncommon::end_data_table_header_row();
 4544: 
 4545:     $iterator->next(); # skip the first BEGIN_MAP
 4546:     my $curRes = $iterator->next(); # for "current resource"
 4547:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4548:     while ($depth > 0) {
 4549:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4550:         if($curRes == $iterator->END_MAP) { $depth--; }
 4551: 
 4552:         if (ref($curRes) && $curRes->is_problem()) {
 4553: 	    my $parts = $curRes->parts();
 4554:             my $title = $curRes->compTitle();
 4555: 	    my $symbx = $curRes->symb();
 4556: 	    $studentTable.=
 4557: 		&Apache::loncommon::start_data_table_row().
 4558: 		'<td align="center" valign="top" >'.$prob.
 4559: 		(scalar(@{$parts}) == 1 ? '' 
 4560:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4561: 		.')').'</td>';
 4562: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4563: 
 4564: 	    my %newrecord=();
 4565: 	    my @displayPts=();
 4566:             my %aggregate = ();
 4567:             my $aggregateflag = 0;
 4568: 	    foreach my $partid (@{$parts}) {
 4569: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4570: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4571: 
 4572: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4573: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4574: 		my $partial = $newpts/$wgt;
 4575: 		my $score;
 4576: 		if ($partial > 0) {
 4577: 		    $score = 'correct_by_override';
 4578: 		} elsif ($newpts ne '') { #empty is taken as 0
 4579: 		    $score = 'incorrect_by_override';
 4580: 		}
 4581: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4582: 		if ($dropMenu eq 'excused') {
 4583: 		    $partial = '';
 4584: 		    $score = 'excused';
 4585: 		} elsif ($dropMenu eq 'reset status'
 4586: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4587: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4588: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4589: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4590: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4591: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4592: 		    $changeflag++;
 4593: 		    $newpts = '';
 4594:                     
 4595:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4596:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4597:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4598:                     if ($aggtries > 0) {
 4599:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4600:                         $aggregateflag = 1;
 4601:                     }
 4602: 		}
 4603: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4604: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4605: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4606: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4607: 		    '&nbsp;<br />';
 4608: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4609: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4610: 		    '&nbsp;<br />';
 4611: 		$question++;
 4612: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4613: 
 4614: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4615: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4616: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4617: 		    if (scalar(keys(%newrecord)) > 0);
 4618: 
 4619: 		$changeflag++;
 4620: 	    }
 4621: 	    if (scalar(keys(%newrecord)) > 0) {
 4622: 		my %record = 
 4623: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4624: 					     $udom,$uname);
 4625: 
 4626: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4627: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4628: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4629: 		    $newrecord{'resource.CODE'} = '';
 4630: 		}
 4631: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4632: 					$udom,$uname);
 4633: 		%record = &Apache::lonnet::restore($symbx,
 4634: 						   $env{'request.course.id'},
 4635: 						   $udom,$uname);
 4636: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4637: 					     $cdom,$cnum,$udom,$uname);
 4638: 	    }
 4639: 	    
 4640:             if ($aggregateflag) {
 4641:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4642:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4643:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4644:             }
 4645: 
 4646: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4647: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4648: 		&Apache::loncommon::end_data_table_row();
 4649: 
 4650: 	    $prob++;
 4651: 	}
 4652:         $curRes = $iterator->next();
 4653:     }
 4654: 
 4655:     $studentTable.=&Apache::loncommon::end_data_table();
 4656:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4657:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4658: 		  &mt('The scores were changed for [quant,_1,problem].',
 4659: 		  $changeflag));
 4660:     $request->print($grademsg.$studentTable);
 4661: 
 4662:     return '';
 4663: }
 4664: 
 4665: #-------- end of section for handling grading by page/sequence ---------
 4666: #
 4667: #-------------------------------------------------------------------
 4668: 
 4669: #--------------------Scantron Grading-----------------------------------
 4670: #
 4671: #------ start of section for handling grading by page/sequence ---------
 4672: 
 4673: =pod
 4674: 
 4675: =head1 Bubble sheet grading routines
 4676: 
 4677:   For this documentation:
 4678: 
 4679:    'scanline' refers to the full line of characters
 4680:    from the file that we are parsing that represents one entire sheet
 4681: 
 4682:    'bubble line' refers to the data
 4683:    representing the line of bubbles that are on the physical bubble sheet
 4684: 
 4685: 
 4686: The overall process is that a scanned in bubble sheet data is uploaded
 4687: into a course. When a user wants to grade, they select a
 4688: sequence/folder of resources, a file of bubble sheet info, and pick
 4689: one of the predefined configurations for what each scanline looks
 4690: like.
 4691: 
 4692: Next each scanline is checked for any errors of either 'missing
 4693: bubbles' (it's an error because it may have been mis-scanned
 4694: because too light bubbling), 'double bubble' (each bubble line should
 4695: have no more that one letter picked), invalid or duplicated CODE,
 4696: invalid student ID
 4697: 
 4698: If the CODE option is used that determines the randomization of the
 4699: homework problems, either way the student ID is looked up into a
 4700: username:domain.
 4701: 
 4702: During the validation phase the instructor can choose to skip scanlines. 
 4703: 
 4704: After the validation phase, there are now 3 bubble sheet files
 4705: 
 4706:   scantron_original_filename (unmodified original file)
 4707:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4708:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4709: 
 4710: Also there is a separate hash nohist_scantrondata that contains extra
 4711: correction information that isn't representable in the bubble sheet
 4712: file (see &scantron_getfile() for more information)
 4713: 
 4714: After all scanlines are either valid, marked as valid or skipped, then
 4715: foreach line foreach problem in the picked sequence, an ssi request is
 4716: made that simulates a user submitting their selected letter(s) against
 4717: the homework problem.
 4718: 
 4719: =over 4
 4720: 
 4721: 
 4722: 
 4723: =item defaultFormData
 4724: 
 4725:   Returns html hidden inputs used to hold context/default values.
 4726: 
 4727:  Arguments:
 4728:   $symb - $symb of the current resource 
 4729: 
 4730: =cut
 4731: 
 4732: sub defaultFormData {
 4733:     my ($symb)=@_;
 4734:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4735:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4736:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4737: }
 4738: 
 4739: 
 4740: =pod 
 4741: 
 4742: =item getSequenceDropDown
 4743: 
 4744:    Return html dropdown of possible sequences to grade
 4745:  
 4746:  Arguments:
 4747:    $symb - $symb of the current resource 
 4748: 
 4749: =cut
 4750: 
 4751: sub getSequenceDropDown {
 4752:     my ($symb)=@_;
 4753:     my $result='<select name="selectpage">'."\n";
 4754:     my ($titles,$symbx) = &getSymbMap();
 4755:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4756:     my $ctr=0;
 4757:     foreach (@$titles) {
 4758: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4759: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4760: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4761: 	    '>'.$showtitle.'</option>'."\n";
 4762: 	$ctr++;
 4763:     }
 4764:     $result.= '</select>';
 4765:     return $result;
 4766: }
 4767: 
 4768: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4769:                                    # index is "symb.part_id"
 4770: 
 4771: my %first_bubble_line;             # First bubble line no. for each bubble.
 4772: 
 4773: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4774:                                    # matchresponse or rankresponse, where 
 4775:                                    # an individual response can have multiple 
 4776:                                    # lines
 4777: 
 4778: my %responsetype_per_response;     # responsetype for each response
 4779: 
 4780: # Save and restore the bubble lines array to the form env.
 4781: 
 4782: 
 4783: sub save_bubble_lines {
 4784:     foreach my $line (keys(%bubble_lines_per_response)) {
 4785: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4786: 	$env{"form.scantron.first_bubble_line.$line"} =
 4787: 	    $first_bubble_line{$line};
 4788:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4789:             $subdivided_bubble_lines{$line};
 4790:         $env{"form.scantron.responsetype.$line"} =
 4791:             $responsetype_per_response{$line};
 4792:     }
 4793: }
 4794: 
 4795: 
 4796: sub restore_bubble_lines {
 4797:     my $line = 0;
 4798:     %bubble_lines_per_response = ();
 4799:     while ($env{"form.scantron.bubblelines.$line"}) {
 4800: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4801: 	$bubble_lines_per_response{$line} = $value;
 4802: 	$first_bubble_line{$line}  =
 4803: 	    $env{"form.scantron.first_bubble_line.$line"};
 4804:         $subdivided_bubble_lines{$line} =
 4805:             $env{"form.scantron.sub_bubblelines.$line"};
 4806:         $responsetype_per_response{$line} =
 4807:             $env{"form.scantron.responsetype.$line"};
 4808: 	$line++;
 4809:     }
 4810: 
 4811: }
 4812: 
 4813: #  Given the parsed scanline, get the response for 
 4814: #  'answer' number n:
 4815: 
 4816: sub get_response_bubbles {
 4817:     my ($parsed_line, $response)  = @_;
 4818: 
 4819: 
 4820:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4821:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4822:     
 4823:     my $selected = "";
 4824: 
 4825:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4826: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4827: 	$bubble_line++;
 4828:     }
 4829:     return $selected;
 4830: }
 4831: 
 4832: =pod 
 4833: 
 4834: =item scantron_filenames
 4835: 
 4836:    Returns a list of the scantron files in the current course 
 4837: 
 4838: =cut
 4839: 
 4840: sub scantron_filenames {
 4841:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4842:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4843:     my $getpropath = 1;
 4844:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4845:                                        $getpropath);
 4846:     my @possiblenames;
 4847:     foreach my $filename (sort(@files)) {
 4848: 	($filename)=split(/&/,$filename);
 4849: 	if ($filename!~/^scantron_orig_/) { next ; }
 4850: 	$filename=~s/^scantron_orig_//;
 4851: 	push(@possiblenames,$filename);
 4852:     }
 4853:     return @possiblenames;
 4854: }
 4855: 
 4856: =pod 
 4857: 
 4858: =item scantron_uploads
 4859: 
 4860:    Returns  html drop-down list of scantron files in current course.
 4861: 
 4862:  Arguments:
 4863:    $file2grade - filename to set as selected in the dropdown
 4864: 
 4865: =cut
 4866: 
 4867: sub scantron_uploads {
 4868:     my ($file2grade) = @_;
 4869:     my $result=	'<select name="scantron_selectfile">';
 4870:     $result.="<option></option>";
 4871:     foreach my $filename (sort(&scantron_filenames())) {
 4872: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4873:     }
 4874:     $result.="</select>";
 4875:     return $result;
 4876: }
 4877: 
 4878: =pod 
 4879: 
 4880: =item scantron_scantab
 4881: 
 4882:   Returns html drop down of the scantron formats in the scantronformat.tab
 4883:   file.
 4884: 
 4885: =cut
 4886: 
 4887: sub scantron_scantab {
 4888:     my $result='<select name="scantron_format">'."\n";
 4889:     $result.='<option></option>'."\n";
 4890:     my @lines = &get_scantronformat_file();
 4891:     if (@lines > 0) {
 4892:         foreach my $line (@lines) {
 4893:             next if (($line =~ /^\#/) || ($line eq ''));
 4894: 	    my ($name,$descrip)=split(/:/,$line);
 4895: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4896:         }
 4897:     }
 4898:     $result.='</select>'."\n";
 4899:     return $result;
 4900: }
 4901: 
 4902: =pod
 4903: 
 4904: =item get_scantronformat_file
 4905: 
 4906:   Returns an array containing lines from the scantron format file for
 4907:   the domain of the course.
 4908: 
 4909:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4910:   lines are from this file.
 4911: 
 4912:   Otherwise, if a default.tab has been published in RES space by the 
 4913:   domainconfig user, lines are from this file.
 4914: 
 4915:   Otherwise, fall back to getting lines from the legacy file on the
 4916:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4917: 
 4918: =cut
 4919: 
 4920: sub get_scantronformat_file {
 4921:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4922:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4923:     my $gottab = 0;
 4924:     my @lines;
 4925:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4926:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4927:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4928:             if ($formatfile ne '-1') {
 4929:                 @lines = split("\n",$formatfile,-1);
 4930:                 $gottab = 1;
 4931:             }
 4932:         }
 4933:     }
 4934:     if (!$gottab) {
 4935:         my $confname = $cdom.'-domainconfig';
 4936:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4937:         my $formatfile =  &Apache::lonnet::getfile($default);
 4938:         if ($formatfile ne '-1') {
 4939:             @lines = split("\n",$formatfile,-1);
 4940:             $gottab = 1;
 4941:         }
 4942:     }
 4943:     if (!$gottab) {
 4944:         my @domains = &Apache::lonnet::current_machine_domains();
 4945:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4946:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4947:             @lines = <$fh>;
 4948:             close($fh);
 4949:         } else {
 4950:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4951:             @lines = <$fh>;
 4952:             close($fh);
 4953:         }
 4954:     }
 4955:     return @lines;
 4956: }
 4957: 
 4958: =pod 
 4959: 
 4960: =item scantron_CODElist
 4961: 
 4962:   Returns html drop down of the saved CODE lists from current course,
 4963:   generated from earlier printings.
 4964: 
 4965: =cut
 4966: 
 4967: sub scantron_CODElist {
 4968:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4969:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4970:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4971:     my $namechoice='<option></option>';
 4972:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4973: 	if ($name =~ /^error: 2 /) { next; }
 4974: 	if ($name =~ /^type\0/) { next; }
 4975: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4976:     }
 4977:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4978:     return $namechoice;
 4979: }
 4980: 
 4981: =pod 
 4982: 
 4983: =item scantron_CODEunique
 4984: 
 4985:   Returns the html for "Each CODE to be used once" radio.
 4986: 
 4987: =cut
 4988: 
 4989: sub scantron_CODEunique {
 4990:     my $result='<span class="LC_nobreak">
 4991:                  <label><input type="radio" name="scantron_CODEunique"
 4992:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4993:                 </span>
 4994:                 <span class="LC_nobreak">
 4995:                  <label><input type="radio" name="scantron_CODEunique"
 4996:                         value="no" />'.&mt('No').' </label>
 4997:                 </span>';
 4998:     return $result;
 4999: }
 5000: 
 5001: =pod 
 5002: 
 5003: =item scantron_selectphase
 5004: 
 5005:   Generates the initial screen to start the bubble sheet process.
 5006:   Allows for - starting a grading run.
 5007:              - downloading existing scan data (original, corrected
 5008:                                                 or skipped info)
 5009: 
 5010:              - uploading new scan data
 5011: 
 5012:  Arguments:
 5013:   $r          - The Apache request object
 5014:   $file2grade - name of the file that contain the scanned data to score
 5015: 
 5016: =cut
 5017: 
 5018: sub scantron_selectphase {
 5019:     my ($r,$file2grade) = @_;
 5020:     my ($symb)=&get_symb($r);
 5021:     if (!$symb) {return '';}
 5022:     my $sequence_selector=&getSequenceDropDown($symb);
 5023:     my $default_form_data=&defaultFormData($symb);
 5024:     my $grading_menu_button=&show_grading_menu_form($symb);
 5025:     my $file_selector=&scantron_uploads($file2grade);
 5026:     my $format_selector=&scantron_scantab();
 5027:     my $CODE_selector=&scantron_CODElist();
 5028:     my $CODE_unique=&scantron_CODEunique();
 5029:     my $result;
 5030: 
 5031:     $ssi_error = 0;
 5032: 
 5033:     # Chunk of form to prompt for a file to grade and how:
 5034: 
 5035:     $result.= '
 5036:     <br />
 5037:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5038:     <input type="hidden" name="command" value="scantron_warning" />
 5039:     '.$default_form_data.'
 5040:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5041:        '.&Apache::loncommon::start_data_table_header_row().'
 5042:             <th colspan="2">
 5043:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5044:             </th>
 5045:        '.&Apache::loncommon::end_data_table_header_row().'
 5046:        '.&Apache::loncommon::start_data_table_row().'
 5047:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5048:        '.&Apache::loncommon::end_data_table_row().'
 5049:        '.&Apache::loncommon::start_data_table_row().'
 5050:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5051:        '.&Apache::loncommon::end_data_table_row().'
 5052:        '.&Apache::loncommon::start_data_table_row().'
 5053:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5054:        '.&Apache::loncommon::end_data_table_row().'
 5055:        '.&Apache::loncommon::start_data_table_row().'
 5056:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5057:        '.&Apache::loncommon::end_data_table_row().'
 5058:        '.&Apache::loncommon::start_data_table_row().'
 5059:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5060:        '.&Apache::loncommon::end_data_table_row().'
 5061:        '.&Apache::loncommon::start_data_table_row().'
 5062: 	    <td> '.&mt('Options:').' </td>
 5063:             <td>
 5064: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5065:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5066:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5067: 	    </td>
 5068:        '.&Apache::loncommon::end_data_table_row().'
 5069:        '.&Apache::loncommon::start_data_table_row().'
 5070:             <td colspan="2">
 5071:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5072:             </td>
 5073:        '.&Apache::loncommon::end_data_table_row().'
 5074:     '.&Apache::loncommon::end_data_table().'
 5075:     </form>
 5076: ';
 5077:    
 5078:     $r->print($result);
 5079: 
 5080:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5081:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5082: 
 5083: 	# Chunk of form to prompt for a scantron file upload.
 5084: 
 5085:         $r->print('
 5086:     <br />
 5087:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5088:        '.&Apache::loncommon::start_data_table_header_row().'
 5089:             <th>
 5090:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5091:             </th>
 5092:        '.&Apache::loncommon::end_data_table_header_row().'
 5093:        '.&Apache::loncommon::start_data_table_row().'
 5094:             <td>
 5095: ');
 5096:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5097:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5098:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5099:     $r->print('
 5100:               <script type="text/javascript" language="javascript">
 5101:     function checkUpload(formname) {
 5102: 	if (formname.upfile.value == "") {
 5103: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5104: 	    return false;
 5105: 	}
 5106: 	formname.submit();
 5107:     }
 5108:               </script>
 5109: 
 5110:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5111:                 '.$default_form_data.'
 5112:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5113:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5114:                 <input name="command" value="scantronupload_save" type="hidden" />
 5115:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5116:                 <br />
 5117:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5118:               </form>
 5119: ');
 5120: 
 5121:         $r->print('
 5122:             </td>
 5123:        '.&Apache::loncommon::end_data_table_row().'
 5124:        '.&Apache::loncommon::end_data_table().'
 5125: ');
 5126:     }
 5127: 
 5128:     # Chunk of the form that prompts to view a scoring office file,
 5129:     # corrected file, skipped records in a file.
 5130: 
 5131:     $r->print('
 5132:    <br />
 5133:    <form action="/adm/grades" name="scantron_download">
 5134:      '.$default_form_data.'
 5135:      <input type="hidden" name="command" value="scantron_download" />
 5136:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5137:        '.&Apache::loncommon::start_data_table_header_row().'
 5138:               <th>
 5139:                 &nbsp;'.&mt('Download a scoring office file').'
 5140:               </th>
 5141:        '.&Apache::loncommon::end_data_table_header_row().'
 5142:        '.&Apache::loncommon::start_data_table_row().'
 5143:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5144:                 <br />
 5145:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5146:        '.&Apache::loncommon::end_data_table_row().'
 5147:      '.&Apache::loncommon::end_data_table().'
 5148:    </form>
 5149:    <br />
 5150: ');
 5151: 
 5152:     &Apache::lonpickcode::code_list($r,2);
 5153: 
 5154:     $r->print('<br /><form method="post" name="checkscantron">'.
 5155:              $default_form_data."\n".
 5156:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5157:              &Apache::loncommon::start_data_table_header_row()."\n".
 5158:              '<th colspan="2">
 5159:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5160:              '</th>'."\n".
 5161:               &Apache::loncommon::end_data_table_header_row()."\n".
 5162:               &Apache::loncommon::start_data_table_row()."\n".
 5163:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5164:               '<td> '.$sequence_selector.' </td>'.
 5165:               &Apache::loncommon::end_data_table_row()."\n".
 5166:               &Apache::loncommon::start_data_table_row()."\n".
 5167:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5168:               '<td> '.$file_selector.' </td>'."\n".
 5169:               &Apache::loncommon::end_data_table_row()."\n".
 5170:               &Apache::loncommon::start_data_table_row()."\n".
 5171:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5172:               '<td> '.$format_selector.' </td>'."\n".
 5173:               &Apache::loncommon::end_data_table_row()."\n".
 5174:               &Apache::loncommon::start_data_table_row()."\n".
 5175:               '<td colspan="2">'."\n".
 5176:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5177:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5178:               '</td>'."\n".
 5179:               &Apache::loncommon::end_data_table_row()."\n".
 5180:               &Apache::loncommon::end_data_table()."\n".
 5181:               '</form><br />');
 5182:     $r->print($grading_menu_button);
 5183:     return;
 5184: }
 5185: 
 5186: =pod
 5187: 
 5188: =item get_scantron_config
 5189: 
 5190:    Parse and return the scantron configuration line selected as a
 5191:    hash of configuration file fields.
 5192: 
 5193:  Arguments:
 5194:     which - the name of the configuration to parse from the file.
 5195: 
 5196: 
 5197:  Returns:
 5198:             If the named configuration is not in the file, an empty
 5199:             hash is returned.
 5200:     a hash with the fields
 5201:       name         - internal name for the this configuration setup
 5202:       description  - text to display to operator that describes this config
 5203:       CODElocation - if 0 or the string 'none'
 5204:                           - no CODE exists for this config
 5205:                      if -1 || the string 'letter'
 5206:                           - a CODE exists for this config and is
 5207:                             a string of letters
 5208:                      Unsupported value (but planned for future support)
 5209:                           if a positive integer
 5210:                                - The CODE exists as the first n items from
 5211:                                  the question section of the form
 5212:                           if the string 'number'
 5213:                                - The CODE exists for this config and is
 5214:                                  a string of numbers
 5215:       CODEstart   - (only matter if a CODE exists) column in the line where
 5216:                      the CODE starts
 5217:       CODElength  - length of the CODE
 5218:       IDstart     - column where the student ID number starts
 5219:       IDlength    - length of the student ID info
 5220:       Qstart      - column where the information from the bubbled
 5221:                     'questions' start
 5222:       Qlength     - number of columns comprising a single bubble line from
 5223:                     the sheet. (usually either 1 or 10)
 5224:       Qon         - either a single character representing the character used
 5225:                     to signal a bubble was chosen in the positional setup, or
 5226:                     the string 'letter' if the letter of the chosen bubble is
 5227:                     in the final, or 'number' if a number representing the
 5228:                     chosen bubble is in the file (1->A 0->J)
 5229:       Qoff        - the character used to represent that a bubble was
 5230:                     left blank
 5231:       PaperID     - if the scanning process generates a unique number for each
 5232:                     sheet scanned the column that this ID number starts in
 5233:       PaperIDlength - number of columns that comprise the unique ID number
 5234:                       for the sheet of paper
 5235:       FirstName   - column that the first name starts in
 5236:       FirstNameLength - number of columns that the first name spans
 5237:  
 5238:       LastName    - column that the last name starts in
 5239:       LastNameLength - number of columns that the last name spans
 5240: 
 5241: =cut
 5242: 
 5243: sub get_scantron_config {
 5244:     my ($which) = @_;
 5245:     my @lines = &get_scantronformat_file();
 5246:     my %config;
 5247:     #FIXME probably should move to XML it has already gotten a bit much now
 5248:     foreach my $line (@lines) {
 5249: 	my ($name,$descrip)=split(/:/,$line);
 5250: 	if ($name ne $which ) { next; }
 5251: 	chomp($line);
 5252: 	my @config=split(/:/,$line);
 5253: 	$config{'name'}=$config[0];
 5254: 	$config{'description'}=$config[1];
 5255: 	$config{'CODElocation'}=$config[2];
 5256: 	$config{'CODEstart'}=$config[3];
 5257: 	$config{'CODElength'}=$config[4];
 5258: 	$config{'IDstart'}=$config[5];
 5259: 	$config{'IDlength'}=$config[6];
 5260: 	$config{'Qstart'}=$config[7];
 5261:  	$config{'Qlength'}=$config[8];
 5262: 	$config{'Qoff'}=$config[9];
 5263: 	$config{'Qon'}=$config[10];
 5264: 	$config{'PaperID'}=$config[11];
 5265: 	$config{'PaperIDlength'}=$config[12];
 5266: 	$config{'FirstName'}=$config[13];
 5267: 	$config{'FirstNamelength'}=$config[14];
 5268: 	$config{'LastName'}=$config[15];
 5269: 	$config{'LastNamelength'}=$config[16];
 5270: 	last;
 5271:     }
 5272:     return %config;
 5273: }
 5274: 
 5275: =pod 
 5276: 
 5277: =item username_to_idmap
 5278: 
 5279:     creates a hash keyed by student id with values of the corresponding
 5280:     student username:domain.
 5281: 
 5282:   Arguments:
 5283: 
 5284:     $classlist - reference to the class list hash. This is a hash
 5285:                  keyed by student name:domain  whose elements are references
 5286:                  to arrays containing various chunks of information
 5287:                  about the student. (See loncoursedata for more info).
 5288: 
 5289:   Returns
 5290:     %idmap - the constructed hash
 5291: 
 5292: =cut
 5293: 
 5294: sub username_to_idmap {
 5295:     my ($classlist)= @_;
 5296:     my %idmap;
 5297:     foreach my $student (keys(%$classlist)) {
 5298: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5299: 	    $student;
 5300:     }
 5301:     return %idmap;
 5302: }
 5303: 
 5304: =pod
 5305: 
 5306: =item scantron_fixup_scanline
 5307: 
 5308:    Process a requested correction to a scanline.
 5309: 
 5310:   Arguments:
 5311:     $scantron_config   - hash from &get_scantron_config()
 5312:     $scan_data         - hash of correction information 
 5313:                           (see &scantron_getfile())
 5314:     $line              - existing scanline
 5315:     $whichline         - line number of the passed in scanline
 5316:     $field             - type of change to process 
 5317:                          (either 
 5318:                           'ID'     -> correct the student ID number
 5319:                           'CODE'   -> correct the CODE
 5320:                           'answer' -> fixup the submitted answers)
 5321:     
 5322:    $args               - hash of additional info,
 5323:                           - 'ID' 
 5324:                                'newid' -> studentID to use in replacement
 5325:                                           of existing one
 5326:                           - 'CODE' 
 5327:                                'CODE_ignore_dup' - set to true if duplicates
 5328:                                                    should be ignored.
 5329: 	                       'CODE' - is new code or 'use_unfound'
 5330:                                         if the existing unfound code should
 5331:                                         be used as is
 5332:                           - 'answer'
 5333:                                'response' - new answer or 'none' if blank
 5334:                                'question' - the bubble line to change
 5335:                                'questionnum' - the question identifier,
 5336:                                                may include subquestion. 
 5337: 
 5338:   Returns:
 5339:     $line - the modified scanline
 5340: 
 5341:   Side effects: 
 5342:     $scan_data - may be updated
 5343: 
 5344: =cut
 5345: 
 5346: 
 5347: sub scantron_fixup_scanline {
 5348:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5349:     if ($field eq 'ID') {
 5350: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5351: 	    return ($line,1,'New value too large');
 5352: 	}
 5353: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5354: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5355: 				     $args->{'newid'});
 5356: 	}
 5357: 	substr($line,$$scantron_config{'IDstart'}-1,
 5358: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5359: 	if ($args->{'newid'}=~/^\s*$/) {
 5360: 	    &scan_data($scan_data,"$whichline.user",
 5361: 		       $args->{'username'}.':'.$args->{'domain'});
 5362: 	}
 5363:     } elsif ($field eq 'CODE') {
 5364: 	if ($args->{'CODE_ignore_dup'}) {
 5365: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5366: 	}
 5367: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5368: 	if ($args->{'CODE'} ne 'use_unfound') {
 5369: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5370: 		return ($line,1,'New CODE value too large');
 5371: 	    }
 5372: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5373: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5374: 	    }
 5375: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5376: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5377: 	}
 5378:     } elsif ($field eq 'answer') {
 5379: 	my $length=$scantron_config->{'Qlength'};
 5380: 	my $off=$scantron_config->{'Qoff'};
 5381: 	my $on=$scantron_config->{'Qon'};
 5382: 	my $answer=${off}x$length;
 5383: 	if ($args->{'response'} eq 'none') {
 5384: 	    &scan_data($scan_data,
 5385: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5386: 	} else {
 5387: 	    if ($on eq 'letter') {
 5388: 		my @alphabet=('A'..'Z');
 5389: 		$answer=$alphabet[$args->{'response'}];
 5390: 	    } elsif ($on eq 'number') {
 5391: 		$answer=$args->{'response'}+1;
 5392: 		if ($answer == 10) { $answer = '0'; }
 5393: 	    } else {
 5394: 		substr($answer,$args->{'response'},1)=$on;
 5395: 	    }
 5396: 	    &scan_data($scan_data,
 5397: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5398: 	}
 5399: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5400: 	substr($line,$where-1,$length)=$answer;
 5401:     }
 5402:     return $line;
 5403: }
 5404: 
 5405: =pod
 5406: 
 5407: =item scan_data
 5408: 
 5409:     Edit or look up  an item in the scan_data hash.
 5410: 
 5411:   Arguments:
 5412:     $scan_data  - The hash (see scantron_getfile)
 5413:     $key        - shorthand of the key to edit (actual key is
 5414:                   scantronfilename_key).
 5415:     $data        - New value of the hash entry.
 5416:     $delete      - If true, the entry is removed from the hash.
 5417: 
 5418:   Returns:
 5419:     The new value of the hash table field (undefined if deleted).
 5420: 
 5421: =cut
 5422: 
 5423: 
 5424: sub scan_data {
 5425:     my ($scan_data,$key,$value,$delete)=@_;
 5426:     my $filename=$env{'form.scantron_selectfile'};
 5427:     if (defined($value)) {
 5428: 	$scan_data->{$filename.'_'.$key} = $value;
 5429:     }
 5430:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5431:     return $scan_data->{$filename.'_'.$key};
 5432: }
 5433: 
 5434: # ----- These first few routines are general use routines.----
 5435: 
 5436: # Return the number of occurences of a pattern in a string.
 5437: 
 5438: sub occurence_count {
 5439:     my ($string, $pattern) = @_;
 5440: 
 5441:     my @matches = ($string =~ /$pattern/g);
 5442: 
 5443:     return scalar(@matches);
 5444: }
 5445: 
 5446: 
 5447: # Take a string known to have digits and convert all the
 5448: # digits into letters in the range J,A..I.
 5449: 
 5450: sub digits_to_letters {
 5451:     my ($input) = @_;
 5452: 
 5453:     my @alphabet = ('J', 'A'..'I');
 5454: 
 5455:     my @input    = split(//, $input);
 5456:     my $output ='';
 5457:     for (my $i = 0; $i < scalar(@input); $i++) {
 5458: 	if ($input[$i] =~ /\d/) {
 5459: 	    $output .= $alphabet[$input[$i]];
 5460: 	} else {
 5461: 	    $output .= $input[$i];
 5462: 	}
 5463:     }
 5464:     return $output;
 5465: }
 5466: 
 5467: =pod 
 5468: 
 5469: =item scantron_parse_scanline
 5470: 
 5471:   Decodes a scanline from the selected scantron file
 5472: 
 5473:  Arguments:
 5474:     line             - The text of the scantron file line to process
 5475:     whichline        - Line number
 5476:     scantron_config  - Hash describing the format of the scantron lines.
 5477:     scan_data        - Hash of extra information about the scanline
 5478:                        (see scantron_getfile for more information)
 5479:     just_header      - True if should not process question answers but only
 5480:                        the stuff to the left of the answers.
 5481:  Returns:
 5482:    Hash containing the result of parsing the scanline
 5483: 
 5484:    Keys are all proceeded by the string 'scantron.'
 5485: 
 5486:        CODE    - the CODE in use for this scanline
 5487:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5488:                  by the operator
 5489:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5490:                             CODEs were selected, but the usage has been
 5491:                             forced by the operator
 5492:        ID  - student ID
 5493:        PaperID - if used, the ID number printed on the sheet when the 
 5494:                  paper was scanned
 5495:        FirstName - first name from the sheet
 5496:        LastName  - last name from the sheet
 5497: 
 5498:      if just_header was not true these key may also exist
 5499: 
 5500:        missingerror - a list of bubble ranges that are considered to be answers
 5501:                       to a single question that don't have any bubbles filled in.
 5502:                       Of the form questionnumber:firstbubblenumber:count.
 5503:        doubleerror  - a list of bubble ranges that are considered to be answers
 5504:                       to a single question that have more than one bubble filled in.
 5505:                       Of the form questionnumber::firstbubblenumber:count
 5506:    
 5507:                 In the above, count is the number of bubble responses in the
 5508:                 input line needed to represent the possible answers to the question.
 5509:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5510:                 per line would have count = 2.
 5511: 
 5512:        maxquest     - the number of the last bubble line that was parsed
 5513: 
 5514:        (<number> starts at 1)
 5515:        <number>.answer - zero or more letters representing the selected
 5516:                          letters from the scanline for the bubble line 
 5517:                          <number>.
 5518:                          if blank there was either no bubble or there where
 5519:                          multiple bubbles, (consult the keys missingerror and
 5520:                          doubleerror if this is an error condition)
 5521: 
 5522: =cut
 5523: 
 5524: sub scantron_parse_scanline {
 5525:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5526: 
 5527:     my %record;
 5528:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5529:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5530:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5531: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5532: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5533: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5534: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5535: 	    $record{'scantron.CODE'}=substr($data,
 5536: 					    $$scantron_config{'CODEstart'}-1,
 5537: 					    $$scantron_config{'CODElength'});
 5538: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5539: 		$record{'scantron.useCODE'}=1;
 5540: 	    }
 5541: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5542: 		$record{'scantron.CODE_ignore_dup'}=1;
 5543: 	    }
 5544: 	} else {
 5545: 	    #FIXME interpret first N questions
 5546: 	}
 5547:     }
 5548:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5549: 				  $$scantron_config{'IDlength'});
 5550:     $record{'scantron.PaperID'}=
 5551: 	substr($data,$$scantron_config{'PaperID'}-1,
 5552: 	       $$scantron_config{'PaperIDlength'});
 5553:     $record{'scantron.FirstName'}=
 5554: 	substr($data,$$scantron_config{'FirstName'}-1,
 5555: 	       $$scantron_config{'FirstNamelength'});
 5556:     $record{'scantron.LastName'}=
 5557: 	substr($data,$$scantron_config{'LastName'}-1,
 5558: 	       $$scantron_config{'LastNamelength'});
 5559:     if ($just_header) { return \%record; }
 5560: 
 5561:     my @alphabet=('A'..'Z');
 5562:     my $questnum=0;
 5563:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5564: 
 5565:     chomp($questions);		# Get rid of any trailing \n.
 5566:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5567:     while (length($questions)) {
 5568: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5570:                              || 1;
 5571:         $questnum++;
 5572:         my $quest_id = $questnum;
 5573:         my $currentquest = substr($questions,0,$answer_length);
 5574:         $questions       = substr($questions,$answer_length);
 5575:         if (length($currentquest) < $answer_length) { next; }
 5576: 
 5577:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5578:             my $subquestnum = 1;
 5579:             my $subquestions = $currentquest;
 5580:             my @subanswers_needed = 
 5581:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5582:             foreach my $subans (@subanswers_needed) {
 5583:                 my $subans_length =
 5584:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5585:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5586:                 $subquestions   = substr($subquestions,$subans_length);
 5587:                 $quest_id = "$questnum.$subquestnum";
 5588:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5589:                     ($$scantron_config{'Qon'} eq 'number')) {
 5590:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5591:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5592:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5593:                 } else {
 5594:                     $ansnum = &scantron_validator_positional($ansnum,
 5595:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5596:                 }
 5597:                 $subquestnum ++;
 5598:             }
 5599:         } else {
 5600:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5601:                 ($$scantron_config{'Qon'} eq 'number')) {
 5602:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5603:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5604:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5605:             } else {
 5606:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5607:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5608:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5609:             }
 5610:         }
 5611:     }
 5612:     $record{'scantron.maxquest'}=$questnum;
 5613:     return \%record;
 5614: }
 5615: 
 5616: sub scantron_validator_lettnum {
 5617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5618:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5619: 
 5620:     # Qon 'letter' implies for each slot in currquest we have:
 5621:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5622:     #    about anything else (esp. a value of Qoff) for missing
 5623:     #    bubbles.
 5624:     #
 5625:     # Qon 'number' implies each slot gives a digit that indexes the
 5626:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5627:     #    and * or ? for double bubbles on a single line.
 5628:     #
 5629: 
 5630:     my $matchon;
 5631:     if ($$scantron_config{'Qon'} eq 'letter') {
 5632:         $matchon = '[A-Z]';
 5633:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5634:         $matchon = '\d';
 5635:     }
 5636:     my $occurrences = 0;
 5637:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5638:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5639:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5640:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5641:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5642:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5643:         my @singlelines = split('',$currquest);
 5644:         foreach my $entry (@singlelines) {
 5645:             $occurrences = &occurence_count($entry,$matchon);
 5646:             if ($occurrences > 1) {
 5647:                 last;
 5648:             }
 5649:         } 
 5650:     } else {
 5651:         $occurrences = &occurence_count($currquest,$matchon); 
 5652:     }
 5653:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5654:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5655:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5656:             my $bubble = substr($currquest,$ans,1);
 5657:             if ($bubble =~ /$matchon/ ) {
 5658:                 if ($$scantron_config{'Qon'} eq 'number') {
 5659:                     if ($bubble == 0) {
 5660:                         $bubble = 10; 
 5661:                     }
 5662:                     $record->{"scantron.$ansnum.answer"} = 
 5663:                         $alphabet->[$bubble-1];
 5664:                 } else {
 5665:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5666:                 }
 5667:             } else {
 5668:                 $record->{"scantron.$ansnum.answer"}='';
 5669:             }
 5670:             $ansnum++;
 5671:         }
 5672:     } elsif (!defined($currquest)
 5673:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5674:             || (&occurence_count($currquest,$matchon) == 0)) {
 5675:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5676:             $record->{"scantron.$ansnum.answer"}='';
 5677:             $ansnum++;
 5678:         }
 5679:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5680:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5681:         }
 5682:     } else {
 5683:         if ($$scantron_config{'Qon'} eq 'number') {
 5684:             $currquest = &digits_to_letters($currquest);            
 5685:         }
 5686:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5687:             my $bubble = substr($currquest,$ans,1);
 5688:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5689:             $ansnum++;
 5690:         }
 5691:     }
 5692:     return $ansnum;
 5693: }
 5694: 
 5695: sub scantron_validator_positional {
 5696:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5697:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5698: 
 5699:     # Otherwise there's a positional notation;
 5700:     # each bubble line requires Qlength items, and there are filled in
 5701:     # bubbles for each case where there 'Qon' characters.
 5702:     #
 5703: 
 5704:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5705: 
 5706:     # If the split only gives us one element.. the full length of the
 5707:     # answer string, no bubbles are filled in:
 5708: 
 5709:     if ($answers_needed eq '') {
 5710:         return;
 5711:     }
 5712: 
 5713:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5714:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5715:             $record->{"scantron.$ansnum.answer"}='';
 5716:             $ansnum++;
 5717:         }
 5718:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5719:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5720:         }
 5721:     } elsif (scalar(@array) == 2) {
 5722:         my $location = length($array[0]);
 5723:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5724:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5725:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5726:             if ($ans eq $line_num) {
 5727:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5728:             } else {
 5729:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5730:             }
 5731:             $ansnum++;
 5732:          }
 5733:     } else {
 5734:         #  If there's more than one instance of a bubble character
 5735:         #  That's a double bubble; with positional notation we can
 5736:         #  record all the bubbles filled in as well as the
 5737:         #  fact this response consists of multiple bubbles.
 5738:         #
 5739:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5740:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5741:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5742:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5743:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5744:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5745:             my $doubleerror = 0;
 5746:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5747:                    (!$doubleerror)) {
 5748:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5749:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5750:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5751:                if (length(@currarray) > 2) {
 5752:                    $doubleerror = 1;
 5753:                } 
 5754:             }
 5755:             if ($doubleerror) {
 5756:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5757:             }
 5758:         } else {
 5759:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5760:         }
 5761:         my $item = $ansnum;
 5762:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5763:             $record->{"scantron.$item.answer"} = '';
 5764:             $item ++;
 5765:         }
 5766: 
 5767:         my @ans=@array;
 5768:         my $i=0;
 5769:         my $increment = 0;
 5770:         while ($#ans) {
 5771:             $i+=length($ans[0]) + $increment;
 5772:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5773:             my $bubble = $i%$$scantron_config{'Qlength'};
 5774:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5775:             shift(@ans);
 5776:             $increment = 1;
 5777:         }
 5778:         $ansnum += $answers_needed;
 5779:     }
 5780:     return $ansnum;
 5781: }
 5782: 
 5783: =pod
 5784: 
 5785: =item scantron_add_delay
 5786: 
 5787:    Adds an error message that occurred during the grading phase to a
 5788:    queue of messages to be shown after grading pass is complete
 5789: 
 5790:  Arguments:
 5791:    $delayqueue  - arrary ref of hash ref of error messages
 5792:    $scanline    - the scanline that caused the error
 5793:    $errormesage - the error message
 5794:    $errorcode   - a numeric code for the error
 5795: 
 5796:  Side Effects:
 5797:    updates the $delayqueue to have a new hash ref of the error
 5798: 
 5799: =cut
 5800: 
 5801: sub scantron_add_delay {
 5802:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5803:     push(@$delayqueue,
 5804: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5805: 	  'ecode' => $errorcode }
 5806: 	 );
 5807: }
 5808: 
 5809: =pod
 5810: 
 5811: =item scantron_find_student
 5812: 
 5813:    Finds the username for the current scanline
 5814: 
 5815:   Arguments:
 5816:    $scantron_record - hash result from scantron_parse_scanline
 5817:    $scan_data       - hash of correction information 
 5818:                       (see &scantron_getfile() form more information)
 5819:    $idmap           - hash from &username_to_idmap()
 5820:    $line            - number of current scanline
 5821:  
 5822:   Returns:
 5823:    Either 'username:domain' or undef if unknown
 5824: 
 5825: =cut
 5826: 
 5827: sub scantron_find_student {
 5828:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5829:     my $scanID=$$scantron_record{'scantron.ID'};
 5830:     if ($scanID =~ /^\s*$/) {
 5831:  	return &scan_data($scan_data,"$line.user");
 5832:     }
 5833:     foreach my $id (keys(%$idmap)) {
 5834:  	if (lc($id) eq lc($scanID)) {
 5835:  	    return $$idmap{$id};
 5836:  	}
 5837:     }
 5838:     return undef;
 5839: }
 5840: 
 5841: =pod
 5842: 
 5843: =item scantron_filter
 5844: 
 5845:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5846:    hidden resources was selected
 5847: 
 5848: =cut
 5849: 
 5850: sub scantron_filter {
 5851:     my ($curres)=@_;
 5852: 
 5853:     if (ref($curres) && $curres->is_problem()) {
 5854: 	# if the user has asked to not have either hidden
 5855: 	# or 'randomout' controlled resources to be graded
 5856: 	# don't include them
 5857: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5858: 	    && $curres->randomout) {
 5859: 	    return 0;
 5860: 	}
 5861: 	return 1;
 5862:     }
 5863:     return 0;
 5864: }
 5865: 
 5866: =pod
 5867: 
 5868: =item scantron_process_corrections
 5869: 
 5870:    Gets correction information out of submitted form data and corrects
 5871:    the scanline
 5872: 
 5873: =cut
 5874: 
 5875: sub scantron_process_corrections {
 5876:     my ($r) = @_;
 5877:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5878:     my ($scanlines,$scan_data)=&scantron_getfile();
 5879:     my $classlist=&Apache::loncoursedata::get_classlist();
 5880:     my $which=$env{'form.scantron_line'};
 5881:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5882:     my ($skip,$err,$errmsg);
 5883:     if ($env{'form.scantron_skip_record'}) {
 5884: 	$skip=1;
 5885:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5886: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5887: 	    $env{'form.scantron_domain'};
 5888: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5889: 	($line,$err,$errmsg)=
 5890: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5891: 				     'ID',{'newid'=>$newid,
 5892: 				    'username'=>$env{'form.scantron_username'},
 5893: 				    'domain'=>$env{'form.scantron_domain'}});
 5894:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5895: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5896: 	my $newCODE;
 5897: 	my %args;
 5898: 	if      ($resolution eq 'use_unfound') {
 5899: 	    $newCODE='use_unfound';
 5900: 	} elsif ($resolution eq 'use_found') {
 5901: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5902: 	} elsif ($resolution eq 'use_typed') {
 5903: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5904: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5905: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5906: 	}
 5907: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5908: 	    $args{'CODE_ignore_dup'}=1;
 5909: 	}
 5910: 	$args{'CODE'}=$newCODE;
 5911: 	($line,$err,$errmsg)=
 5912: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5913: 				     'CODE',\%args);
 5914:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5915: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5916: 	    ($line,$err,$errmsg)=
 5917: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5918: 					 $which,'answer',
 5919: 					 { 'question'=>$question,
 5920: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5921:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5922: 	    if ($err) { last; }
 5923: 	}
 5924:     }
 5925:     if ($err) {
 5926: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5927:     } else {
 5928: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5929: 	&scantron_putfile($scanlines,$scan_data);
 5930:     }
 5931: }
 5932: 
 5933: =pod
 5934: 
 5935: =item reset_skipping_status
 5936: 
 5937:    Forgets the current set of remember skipped scanlines (and thus
 5938:    reverts back to considering all lines in the
 5939:    scantron_skipped_<filename> file)
 5940: 
 5941: =cut
 5942: 
 5943: sub reset_skipping_status {
 5944:     my ($scanlines,$scan_data)=&scantron_getfile();
 5945:     &scan_data($scan_data,'remember_skipping',undef,1);
 5946:     &scantron_putfile(undef,$scan_data);
 5947: }
 5948: 
 5949: =pod
 5950: 
 5951: =item start_skipping
 5952: 
 5953:    Marks a scanline to be skipped. 
 5954: 
 5955: =cut
 5956: 
 5957: sub start_skipping {
 5958:     my ($scan_data,$i)=@_;
 5959:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5960:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5961: 	$remembered{$i}=2;
 5962:     } else {
 5963: 	$remembered{$i}=1;
 5964:     }
 5965:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5966: }
 5967: 
 5968: =pod
 5969: 
 5970: =item should_be_skipped
 5971: 
 5972:    Checks whether a scanline should be skipped.
 5973: 
 5974: =cut
 5975: 
 5976: sub should_be_skipped {
 5977:     my ($scanlines,$scan_data,$i)=@_;
 5978:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5979: 	# not redoing old skips
 5980: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5981: 	return 0;
 5982:     }
 5983:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5984: 
 5985:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5986: 	return 0;
 5987:     }
 5988:     return 1;
 5989: }
 5990: 
 5991: =pod
 5992: 
 5993: =item remember_current_skipped
 5994: 
 5995:    Discovers what scanlines are in the scantron_skipped_<filename>
 5996:    file and remembers them into scan_data for later use.
 5997: 
 5998: =cut
 5999: 
 6000: sub remember_current_skipped {
 6001:     my ($scanlines,$scan_data)=&scantron_getfile();
 6002:     my %to_remember;
 6003:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6004: 	if ($scanlines->{'skipped'}[$i]) {
 6005: 	    $to_remember{$i}=1;
 6006: 	}
 6007:     }
 6008: 
 6009:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6010:     &scantron_putfile(undef,$scan_data);
 6011: }
 6012: 
 6013: =pod
 6014: 
 6015: =item check_for_error
 6016: 
 6017:     Checks if there was an error when attempting to remove a specific
 6018:     scantron_.. bubble sheet data file. Prints out an error if
 6019:     something went wrong.
 6020: 
 6021: =cut
 6022: 
 6023: sub check_for_error {
 6024:     my ($r,$result)=@_;
 6025:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6026: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6027:     }
 6028: }
 6029: 
 6030: =pod
 6031: 
 6032: =item scantron_warning_screen
 6033: 
 6034:    Interstitial screen to make sure the operator has selected the
 6035:    correct options before we start the validation phase.
 6036: 
 6037: =cut
 6038: 
 6039: sub scantron_warning_screen {
 6040:     my ($button_text)=@_;
 6041:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6043:     my $CODElist;
 6044:     if ($scantron_config{'CODElocation'} &&
 6045: 	$scantron_config{'CODEstart'} &&
 6046: 	$scantron_config{'CODElength'}) {
 6047: 	$CODElist=$env{'form.scantron_CODElist'};
 6048: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6049: 	$CODElist=
 6050: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6051: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6052:     }
 6053:     return ('
 6054: <p>
 6055: <span class="LC_warning">
 6056: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6057: </p>
 6058: <table>
 6059: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6060: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6061: '.$CODElist.'
 6062: </table>
 6063: <br />
 6064: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6065: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6066: 
 6067: <br />
 6068: ');
 6069: }
 6070: 
 6071: =pod
 6072: 
 6073: =item scantron_do_warning
 6074: 
 6075:    Check if the operator has picked something for all required
 6076:    fields. Error out if something is missing.
 6077: 
 6078: =cut
 6079: 
 6080: sub scantron_do_warning {
 6081:     my ($r)=@_;
 6082:     my ($symb)=&get_symb($r);
 6083:     if (!$symb) {return '';}
 6084:     my $default_form_data=&defaultFormData($symb);
 6085:     $r->print(&scantron_form_start().$default_form_data);
 6086:     if ( $env{'form.selectpage'} eq '' ||
 6087: 	 $env{'form.scantron_selectfile'} eq '' ||
 6088: 	 $env{'form.scantron_format'} eq '' ) {
 6089: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6090: 	if ( $env{'form.selectpage'} eq '') {
 6091: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6092: 	} 
 6093: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6094: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6095: 	} 
 6096: 	if ( $env{'form.scantron_format'} eq '') {
 6097: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6098: 	} 
 6099:     } else {
 6100: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6101: 	$r->print('
 6102: '.$warning.'
 6103: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6104: <input type="hidden" name="command" value="scantron_validate" />
 6105: ');
 6106:     }
 6107:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6108:     return '';
 6109: }
 6110: 
 6111: =pod
 6112: 
 6113: =item scantron_form_start
 6114: 
 6115:     html hidden input for remembering all selected grading options
 6116: 
 6117: =cut
 6118: 
 6119: sub scantron_form_start {
 6120:     my ($max_bubble)=@_;
 6121:     my $result= <<SCANTRONFORM;
 6122: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6123:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6124:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6125:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6126:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6127:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6128:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6129:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6130:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6131:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6132: SCANTRONFORM
 6133: 
 6134:   my $line = 0;
 6135:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6136:        my $chunk =
 6137: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6138:        $chunk .=
 6139: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6140:        $chunk .= 
 6141:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6142:        $chunk .=
 6143:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6144:        $result .= $chunk;
 6145:        $line++;
 6146:    }
 6147:     return $result;
 6148: }
 6149: 
 6150: =pod
 6151: 
 6152: =item scantron_validate_file
 6153: 
 6154:     Dispatch routine for doing validation of a bubble sheet data file.
 6155: 
 6156:     Also processes any necessary information resets that need to
 6157:     occur before validation begins (ignore previous corrections,
 6158:     restarting the skipped records processing)
 6159: 
 6160: =cut
 6161: 
 6162: sub scantron_validate_file {
 6163:     my ($r) = @_;
 6164:     my ($symb)=&get_symb($r);
 6165:     if (!$symb) {return '';}
 6166:     my $default_form_data=&defaultFormData($symb);
 6167:     
 6168:     # do the detection of only doing skipped records first befroe we delete
 6169:     # them when doing the corrections reset
 6170:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6171: 	&reset_skipping_status();
 6172:     }
 6173:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6174: 	&remember_current_skipped();
 6175: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6176:     }
 6177: 
 6178:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6179: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6180: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6181: 	&check_for_error($r,&scantron_remove_scan_data());
 6182: 	$env{'form.scantron_options_ignore'}='done';
 6183:     }
 6184: 
 6185:     if ($env{'form.scantron_corrections'}) {
 6186: 	&scantron_process_corrections($r);
 6187:     }
 6188:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6189:     #get the student pick code ready
 6190:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6191:     my $max_bubble=&scantron_get_maxbubble();
 6192:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6193:     $r->print($result);
 6194:     
 6195:     my @validate_phases=( 'sequence',
 6196: 			  'ID',
 6197: 			  'CODE',
 6198: 			  'doublebubble',
 6199: 			  'missingbubbles');
 6200:     if (!$env{'form.validatepass'}) {
 6201: 	$env{'form.validatepass'} = 0;
 6202:     }
 6203:     my $currentphase=$env{'form.validatepass'};
 6204: 
 6205: 
 6206:     my $stop=0;
 6207:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6208: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6209: 	$r->rflush();
 6210: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6211: 	{
 6212: 	    no strict 'refs';
 6213: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6214: 	}
 6215:     }
 6216:     if (!$stop) {
 6217:         my $warning=&scantron_warning_screen('Start Grading');
 6218:         $r->print(&mt('Validation process complete.').'<br />'.
 6219:                   $warning.
 6220:                   &mt('Perform verification for each student after storage of submissions?').
 6221:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6222:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6223:                   ('&nbsp;'x3).'<label>'.
 6224:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6225:                   '</label></span><br />'.
 6226:                   &mt('Grading will take longer if you use verification.').'<br />'.                  &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6227:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6228:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6229:     } else {
 6230:         $r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6231:         $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6232:     }
 6233:     if ($stop) {
 6234: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6235: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6236: 	    $r->print(' '.&mt('this error').' <br />');
 6237: 
 6238: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6239: 	} else {
 6240:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6241: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6242:             } else {
 6243:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6244:             }
 6245: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6246: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6247: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6248: 	}
 6249:     }
 6250:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6251:     return '';
 6252: }
 6253: 
 6254: 
 6255: =pod
 6256: 
 6257: =item scantron_remove_file
 6258: 
 6259:    Removes the requested bubble sheet data file, makes sure that
 6260:    scantron_original_<filename> is never removed
 6261: 
 6262: 
 6263: =cut
 6264: 
 6265: sub scantron_remove_file {
 6266:     my ($which)=@_;
 6267:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6268:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6269:     my $file='scantron_';
 6270:     if ($which eq 'corrected' || $which eq 'skipped') {
 6271: 	$file.=$which.'_';
 6272:     } else {
 6273: 	return 'refused';
 6274:     }
 6275:     $file.=$env{'form.scantron_selectfile'};
 6276:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6277: }
 6278: 
 6279: 
 6280: =pod
 6281: 
 6282: =item scantron_remove_scan_data
 6283: 
 6284:    Removes all scan_data correction for the requested bubble sheet
 6285:    data file.  (In the case that both the are doing skipped records we need
 6286:    to remember the old skipped lines for the time being so that element
 6287:    persists for a while.)
 6288: 
 6289: =cut
 6290: 
 6291: sub scantron_remove_scan_data {
 6292:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6293:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6294:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6295:     my @todelete;
 6296:     my $filename=$env{'form.scantron_selectfile'};
 6297:     foreach my $key (@keys) {
 6298: 	if ($key=~/^\Q$filename\E_/) {
 6299: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6300: 		$key=~/remember_skipping/) {
 6301: 		next;
 6302: 	    }
 6303: 	    push(@todelete,$key);
 6304: 	}
 6305:     }
 6306:     my $result;
 6307:     if (@todelete) {
 6308: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6309: 				       \@todelete,$cdom,$cname);
 6310:     } else {
 6311: 	$result = 'ok';
 6312:     }
 6313:     return $result;
 6314: }
 6315: 
 6316: 
 6317: =pod
 6318: 
 6319: =item scantron_getfile
 6320: 
 6321:     Fetches the requested bubble sheet data file (all 3 versions), and
 6322:     the scan_data hash
 6323:   
 6324:   Arguments:
 6325:     None
 6326: 
 6327:   Returns:
 6328:     2 hash references
 6329: 
 6330:      - first one has 
 6331:          orig      -
 6332:          corrected -
 6333:          skipped   -  each of which points to an array ref of the specified
 6334:                       file broken up into individual lines
 6335:          count     - number of scanlines
 6336:  
 6337:      - second is the scan_data hash possible keys are
 6338:        ($number refers to scanline numbered $number and thus the key affects
 6339:         only that scanline
 6340:         $bubline refers to the specific bubble line element and the aspects
 6341:         refers to that specific bubble line element)
 6342: 
 6343:        $number.user - username:domain to use
 6344:        $number.CODE_ignore_dup 
 6345:                     - ignore the duplicate CODE error 
 6346:        $number.useCODE
 6347:                     - use the CODE in the scanline as is
 6348:        $number.no_bubble.$bubline
 6349:                     - it is valid that there is no bubbled in bubble
 6350:                       at $number $bubline
 6351:        remember_skipping
 6352:                     - a frozen hash containing keys of $number and values
 6353:                       of either 
 6354:                         1 - we are on a 'do skipped records pass' and plan
 6355:                             on processing this line
 6356:                         2 - we are on a 'do skipped records pass' and this
 6357:                             scanline has been marked to skip yet again
 6358: 
 6359: =cut
 6360: 
 6361: sub scantron_getfile {
 6362:     #FIXME really would prefer a scantron directory
 6363:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6365:     my $lines;
 6366:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6367: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6368:     my %scanlines;
 6369:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6370:     my $temp=$scanlines{'orig'};
 6371:     $scanlines{'count'}=$#$temp;
 6372: 
 6373:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6374: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6375:     if ($lines eq '-1') {
 6376: 	$scanlines{'corrected'}=[];
 6377:     } else {
 6378: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6379:     }
 6380:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6381: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6382:     if ($lines eq '-1') {
 6383: 	$scanlines{'skipped'}=[];
 6384:     } else {
 6385: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6386:     }
 6387:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6388:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6389:     my %scan_data = @tmp;
 6390:     return (\%scanlines,\%scan_data);
 6391: }
 6392: 
 6393: =pod
 6394: 
 6395: =item lonnet_putfile
 6396: 
 6397:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6398: 
 6399:  Arguments:
 6400:    $contents - data to store
 6401:    $filename - filename to store $contents into
 6402: 
 6403:  Returns:
 6404:    result value from &Apache::lonnet::finishuserfileupload
 6405: 
 6406: =cut
 6407: 
 6408: sub lonnet_putfile {
 6409:     my ($contents,$filename)=@_;
 6410:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6411:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6412:     $env{'form.sillywaytopassafilearound'}=$contents;
 6413:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6414: 
 6415: }
 6416: 
 6417: =pod
 6418: 
 6419: =item scantron_putfile
 6420: 
 6421:     Stores the current version of the bubble sheet data files, and the
 6422:     scan_data hash. (Does not modify the original version only the
 6423:     corrected and skipped versions.
 6424: 
 6425:  Arguments:
 6426:     $scanlines - hash ref that looks like the first return value from
 6427:                  &scantron_getfile()
 6428:     $scan_data - hash ref that looks like the second return value from
 6429:                  &scantron_getfile()
 6430: 
 6431: =cut
 6432: 
 6433: sub scantron_putfile {
 6434:     my ($scanlines,$scan_data) = @_;
 6435:     #FIXME really would prefer a scantron directory
 6436:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6438:     if ($scanlines) {
 6439: 	my $prefix='scantron_';
 6440: # no need to update orig, shouldn't change
 6441: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6442: #		    $env{'form.scantron_selectfile'});
 6443: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6444: 			$prefix.'corrected_'.
 6445: 			$env{'form.scantron_selectfile'});
 6446: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6447: 			$prefix.'skipped_'.
 6448: 			$env{'form.scantron_selectfile'});
 6449:     }
 6450:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6451: }
 6452: 
 6453: =pod
 6454: 
 6455: =item scantron_get_line
 6456: 
 6457:    Returns the correct version of the scanline
 6458: 
 6459:  Arguments:
 6460:     $scanlines - hash ref that looks like the first return value from
 6461:                  &scantron_getfile()
 6462:     $scan_data - hash ref that looks like the second return value from
 6463:                  &scantron_getfile()
 6464:     $i         - number of the requested line (starts at 0)
 6465: 
 6466:  Returns:
 6467:    A scanline, (either the original or the corrected one if it
 6468:    exists), or undef if the requested scanline should be
 6469:    skipped. (Either because it's an skipped scanline, or it's an
 6470:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6471:    pass.
 6472: 
 6473: =cut
 6474: 
 6475: sub scantron_get_line {
 6476:     my ($scanlines,$scan_data,$i)=@_;
 6477:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6478:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6479:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6480:     return $scanlines->{'orig'}[$i]; 
 6481: }
 6482: 
 6483: =pod
 6484: 
 6485: =item scantron_todo_count
 6486: 
 6487:     Counts the number of scanlines that need processing.
 6488: 
 6489:  Arguments:
 6490:     $scanlines - hash ref that looks like the first return value from
 6491:                  &scantron_getfile()
 6492:     $scan_data - hash ref that looks like the second return value from
 6493:                  &scantron_getfile()
 6494: 
 6495:  Returns:
 6496:     $count - number of scanlines to process
 6497: 
 6498: =cut
 6499: 
 6500: sub get_todo_count {
 6501:     my ($scanlines,$scan_data)=@_;
 6502:     my $count=0;
 6503:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6504: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6505: 	if ($line=~/^[\s\cz]*$/) { next; }
 6506: 	$count++;
 6507:     }
 6508:     return $count;
 6509: }
 6510: 
 6511: =pod
 6512: 
 6513: =item scantron_put_line
 6514: 
 6515:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6516:     data file.
 6517: 
 6518:  Arguments:
 6519:     $scanlines - hash ref that looks like the first return value from
 6520:                  &scantron_getfile()
 6521:     $scan_data - hash ref that looks like the second return value from
 6522:                  &scantron_getfile()
 6523:     $i         - line number to update
 6524:     $newline   - contents of the updated scanline
 6525:     $skip      - if true make the line for skipping and update the
 6526:                  'skipped' file
 6527: 
 6528: =cut
 6529: 
 6530: sub scantron_put_line {
 6531:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6532:     if ($skip) {
 6533: 	$scanlines->{'skipped'}[$i]=$newline;
 6534: 	&start_skipping($scan_data,$i);
 6535: 	return;
 6536:     }
 6537:     $scanlines->{'corrected'}[$i]=$newline;
 6538: }
 6539: 
 6540: =pod
 6541: 
 6542: =item scantron_clear_skip
 6543: 
 6544:    Remove a line from the 'skipped' file
 6545: 
 6546:  Arguments:
 6547:     $scanlines - hash ref that looks like the first return value from
 6548:                  &scantron_getfile()
 6549:     $scan_data - hash ref that looks like the second return value from
 6550:                  &scantron_getfile()
 6551:     $i         - line number to update
 6552: 
 6553: =cut
 6554: 
 6555: sub scantron_clear_skip {
 6556:     my ($scanlines,$scan_data,$i)=@_;
 6557:     if (exists($scanlines->{'skipped'}[$i])) {
 6558: 	undef($scanlines->{'skipped'}[$i]);
 6559: 	return 1;
 6560:     }
 6561:     return 0;
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item scantron_filter_not_exam
 6567: 
 6568:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6569:    filter out resources that are not marked as 'exam' mode
 6570: 
 6571: =cut
 6572: 
 6573: sub scantron_filter_not_exam {
 6574:     my ($curres)=@_;
 6575:     
 6576:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6577: 	# if the user has asked to not have either hidden
 6578: 	# or 'randomout' controlled resources to be graded
 6579: 	# don't include them
 6580: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6581: 	    && $curres->randomout) {
 6582: 	    return 0;
 6583: 	}
 6584: 	return 1;
 6585:     }
 6586:     return 0;
 6587: }
 6588: 
 6589: =pod
 6590: 
 6591: =item scantron_validate_sequence
 6592: 
 6593:     Validates the selected sequence, checking for resource that are
 6594:     not set to exam mode.
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_validate_sequence {
 6599:     my ($r,$currentphase) = @_;
 6600: 
 6601:     my $navmap=Apache::lonnavmaps::navmap->new();
 6602:     my (undef,undef,$sequence)=
 6603: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6604: 
 6605:     my $map=$navmap->getResourceByUrl($sequence);
 6606: 
 6607:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6608:                                     value="ignore" />');
 6609:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6610: 	my @resources=
 6611: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6612: 	if (@resources) {
 6613: 	    $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>");
 6614: 	    return (1,$currentphase);
 6615: 	}
 6616:     }
 6617: 
 6618:     return (0,$currentphase+1);
 6619: }
 6620: 
 6621: =pod
 6622: 
 6623: =item scantron_validate_ID
 6624: 
 6625:    Validates all scanlines in the selected file to not have any
 6626:    invalid or underspecified student IDs
 6627: 
 6628: =cut
 6629: 
 6630: sub scantron_validate_ID {
 6631:     my ($r,$currentphase) = @_;
 6632:     
 6633:     #get student info
 6634:     my $classlist=&Apache::loncoursedata::get_classlist();
 6635:     my %idmap=&username_to_idmap($classlist);
 6636: 
 6637:     #get scantron line setup
 6638:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6639:     my ($scanlines,$scan_data)=&scantron_getfile();
 6640:     
 6641:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6642: 
 6643:     my %found=('ids'=>{},'usernames'=>{});
 6644:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6645: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6646: 	if ($line=~/^[\s\cz]*$/) { next; }
 6647: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6648: 						 $scan_data);
 6649: 	my $id=$$scan_record{'scantron.ID'};
 6650: 	my $found;
 6651: 	foreach my $checkid (keys(%idmap)) {
 6652: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6653: 	}
 6654: 	if ($found) {
 6655: 	    my $username=$idmap{$found};
 6656: 	    if ($found{'ids'}{$found}) {
 6657: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6658: 					 $line,'duplicateID',$found);
 6659: 		return(1,$currentphase);
 6660: 	    } elsif ($found{'usernames'}{$username}) {
 6661: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6662: 					 $line,'duplicateID',$username);
 6663: 		return(1,$currentphase);
 6664: 	    }
 6665: 	    #FIXME store away line we previously saw the ID on to use above
 6666: 	    $found{'ids'}{$found}++;
 6667: 	    $found{'usernames'}{$username}++;
 6668: 	} else {
 6669: 	    if ($id =~ /^\s*$/) {
 6670: 		my $username=&scan_data($scan_data,"$i.user");
 6671: 		if (defined($username) && $found{'usernames'}{$username}) {
 6672: 		    &scantron_get_correction($r,$i,$scan_record,
 6673: 					     \%scantron_config,
 6674: 					     $line,'duplicateID',$username);
 6675: 		    return(1,$currentphase);
 6676: 		} elsif (!defined($username)) {
 6677: 		    &scantron_get_correction($r,$i,$scan_record,
 6678: 					     \%scantron_config,
 6679: 					     $line,'incorrectID');
 6680: 		    return(1,$currentphase);
 6681: 		}
 6682: 		$found{'usernames'}{$username}++;
 6683: 	    } else {
 6684: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6685: 					 $line,'incorrectID');
 6686: 		return(1,$currentphase);
 6687: 	    }
 6688: 	}
 6689:     }
 6690: 
 6691:     return (0,$currentphase+1);
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_get_correction
 6697: 
 6698:    Builds the interface screen to interact with the operator to fix a
 6699:    specific error condition in a specific scanline
 6700: 
 6701:  Arguments:
 6702:     $r           - Apache request object
 6703:     $i           - number of the current scanline
 6704:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6705:     $scan_config - hash ref as returned from &get_scantron_config()
 6706:     $line        - full contents of the current scanline
 6707:     $error       - error condition, valid values are
 6708:                    'incorrectCODE', 'duplicateCODE',
 6709:                    'doublebubble', 'missingbubble',
 6710:                    'duplicateID', 'incorrectID'
 6711:     $arg         - extra information needed
 6712:        For errors:
 6713:          - duplicateID   - paper number that this studentID was seen before on
 6714:          - duplicateCODE - array ref of the paper numbers this CODE was
 6715:                            seen on before
 6716:          - incorrectCODE - current incorrect CODE 
 6717:          - doublebubble  - array ref of the bubble lines that have double
 6718:                            bubble errors
 6719:          - missingbubble - array ref of the bubble lines that have missing
 6720:                            bubble errors
 6721: 
 6722: =cut
 6723: 
 6724: sub scantron_get_correction {
 6725:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6726: #FIXME in the case of a duplicated ID the previous line, probably need
 6727: #to show both the current line and the previous one and allow skipping
 6728: #the previous one or the current one
 6729: 
 6730:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6731: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6732: 			    " for PaperID <tt>[_1]</tt>",
 6733: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6734:     } else {
 6735: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6736: 			    " in scanline [_1] <pre>[_2]</pre>",
 6737: 			    $i,$line)."</p> \n");
 6738:     }
 6739:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6740: 			  "The name on the paper is [_2],[_3]",
 6741: 			  $$scan_record{'scantron.ID'},
 6742: 			  $$scan_record{'scantron.LastName'},
 6743: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6744: 
 6745:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6746:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6747:                            # Array populated for doublebubble or
 6748:     my @lines_to_correct;  # missingbubble errors to build javascript
 6749:                            # to validate radio button checking   
 6750: 
 6751:     if ($error =~ /ID$/) {
 6752: 	if ($error eq 'incorrectID') {
 6753: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6754: 		      "</p>\n");
 6755: 	} elsif ($error eq 'duplicateID') {
 6756: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6757: 	}
 6758: 	$r->print($message);
 6759: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6760: 	$r->print("\n<ul><li> ");
 6761: 	#FIXME it would be nice if this sent back the user ID and
 6762: 	#could do partial userID matches
 6763: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6764: 				       'scantron_username','scantron_domain'));
 6765: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6766: 	$r->print("\n@".
 6767: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6768: 
 6769: 	$r->print('</li>');
 6770:     } elsif ($error =~ /CODE$/) {
 6771: 	if ($error eq 'incorrectCODE') {
 6772: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6773: 	} elsif ($error eq 'duplicateCODE') {
 6774: 	    $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");
 6775: 	}
 6776: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6777: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6778: 	$r->print($message);
 6779: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6780: 	$r->print("\n<br /> ");
 6781: 	my $i=0;
 6782: 	if ($error eq 'incorrectCODE' 
 6783: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6784: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6785: 	    if ($closest > 0) {
 6786: 		foreach my $testcode (@{$closest}) {
 6787: 		    my $checked='';
 6788: 		    if (!$i) { $checked=' checked="checked" '; }
 6789: 		    $r->print("
 6790:    <label>
 6791:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6792:        ".&mt("Use the similar CODE [_1] instead.",
 6793: 	    "<b><tt>".$testcode."</tt></b>")."
 6794:     </label>
 6795:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6796: 		    $r->print("\n<br />");
 6797: 		    $i++;
 6798: 		}
 6799: 	    }
 6800: 	}
 6801: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6802: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6803: 	    $r->print("
 6804:     <label>
 6805:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6806:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6807: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6808:     </label>");
 6809: 	    $r->print("\n<br />");
 6810: 	}
 6811: 
 6812: 	$r->print(<<ENDSCRIPT);
 6813: <script type="text/javascript">
 6814: function change_radio(field) {
 6815:     var slct=document.scantronupload.scantron_CODE_resolution;
 6816:     var i;
 6817:     for (i=0;i<slct.length;i++) {
 6818:         if (slct[i].value==field) { slct[i].checked=true; }
 6819:     }
 6820: }
 6821: </script>
 6822: ENDSCRIPT
 6823: 	my $href="/adm/pickcode?".
 6824: 	   "form=".&escape("scantronupload").
 6825: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6826: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6827: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6828: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6829: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6830: 	    $r->print("
 6831:     <label>
 6832:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6833:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6834: 	     "<a target='_blank' href='$href'>","</a>")."
 6835:     </label> 
 6836:     ".&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')\" />"));
 6837: 	    $r->print("\n<br />");
 6838: 	}
 6839: 	$r->print("
 6840:     <label>
 6841:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6842:        ".&mt("Use [_1] as the CODE.",
 6843: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6844: 	$r->print("\n<br /><br />");
 6845:     } elsif ($error eq 'doublebubble') {
 6846: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6847: 
 6848: 	# The form field scantron_questions is acutally a list of line numbers.
 6849: 	# represented by this form so:
 6850: 
 6851: 	my $line_list = &questions_to_line_list($arg);
 6852: 
 6853: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6854: 		  $line_list.'" />');
 6855: 	$r->print($message);
 6856: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6857: 	foreach my $question (@{$arg}) {
 6858: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6859:                                                    $scan_record, $error);
 6860:             push(@lines_to_correct,@linenums);
 6861: 	}
 6862:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6863:     } elsif ($error eq 'missingbubble') {
 6864: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6865: 	$r->print($message);
 6866: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6867: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6868: 
 6869: 	# The form field scantron_questions is actually a list of line numbers not
 6870: 	# a list of question numbers. Therefore:
 6871: 	#
 6872: 	
 6873: 	my $line_list = &questions_to_line_list($arg);
 6874: 
 6875: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6876: 		  $line_list.'" />');
 6877: 	foreach my $question (@{$arg}) {
 6878: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6879:                                                    $scan_record, $error);
 6880:             push(@lines_to_correct,@linenums);
 6881: 	}
 6882:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6883:     } else {
 6884: 	$r->print("\n<ul>");
 6885:     }
 6886:     $r->print("\n</li></ul>");
 6887: }
 6888: 
 6889: sub verify_bubbles_checked {
 6890:     my (@ansnums) = @_;
 6891:     my $ansnumstr = join('","',@ansnums);
 6892:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6893:     my $output = (<<ENDSCRIPT);
 6894: <script type="text/javascript">
 6895: function verify_bubble_radio(form) {
 6896:     var ansnumArray = new Array ("$ansnumstr");
 6897:     var need_bubble_count = 0;
 6898:     for (var i=0; i<ansnumArray.length; i++) {
 6899:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6900:             var bubble_picked = 0; 
 6901:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6902:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6903:                     bubble_picked = 1;
 6904:                 }
 6905:             }
 6906:             if (bubble_picked == 0) {
 6907:                 need_bubble_count ++;
 6908:             }
 6909:         }
 6910:     }
 6911:     if (need_bubble_count) {
 6912:         alert("$warning");
 6913:         return;
 6914:     }
 6915:     form.submit(); 
 6916: }
 6917: </script>
 6918: ENDSCRIPT
 6919:     return $output;
 6920: }
 6921: 
 6922: =pod
 6923: 
 6924: =item  questions_to_line_list
 6925: 
 6926: Converts a list of questions into a string of comma separated
 6927: line numbers in the answer sheet used by the questions.  This is
 6928: used to fill in the scantron_questions form field.
 6929: 
 6930:   Arguments:
 6931:      questions    - Reference to an array of questions.
 6932: 
 6933: =cut
 6934: 
 6935: 
 6936: sub questions_to_line_list {
 6937:     my ($questions) = @_;
 6938:     my @lines;
 6939: 
 6940:     foreach my $item (@{$questions}) {
 6941:         my $question = $item;
 6942:         my ($first,$count,$last);
 6943:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6944:             $question = $1;
 6945:             my $subquestion = $2;
 6946:             $first = $first_bubble_line{$question-1} + 1;
 6947:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6948:             my $subcount = 1;
 6949:             while ($subcount<$subquestion) {
 6950:                 $first += $subans[$subcount-1];
 6951:                 $subcount ++;
 6952:             }
 6953:             $count = $subans[$subquestion-1];
 6954:         } else {
 6955: 	    $first   = $first_bubble_line{$question-1} + 1;
 6956: 	    $count   = $bubble_lines_per_response{$question-1};
 6957:         }
 6958:         $last = $first+$count-1;
 6959:         push(@lines, ($first..$last));
 6960:     }
 6961:     return join(',', @lines);
 6962: }
 6963: 
 6964: =pod 
 6965: 
 6966: =item prompt_for_corrections
 6967: 
 6968: Prompts for a potentially multiline correction to the
 6969: user's bubbling (factors out common code from scantron_get_correction
 6970: for multi and missing bubble cases).
 6971: 
 6972:  Arguments:
 6973:    $r           - Apache request object.
 6974:    $question    - The question number to prompt for.
 6975:    $scan_config - The scantron file configuration hash.
 6976:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6977:    $error       - Type of error
 6978: 
 6979:  Implicit inputs:
 6980:    %bubble_lines_per_response   - Starting line numbers for each question.
 6981:                                   Numbered from 0 (but question numbers are from
 6982:                                   1.
 6983:    %first_bubble_line           - Starting bubble line for each question.
 6984:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6985:                                   type problems render as separate sub-questions, 
 6986:                                   in exam mode. This hash contains a 
 6987:                                   comma-separated list of the lines per 
 6988:                                   sub-question.
 6989:    %responsetype_per_response   - essayresponse, formularesponse,
 6990:                                   stringresponse, imageresponse, reactionresponse,
 6991:                                   and organicresponse type problem parts can have
 6992:                                   multiple lines per response if the weight
 6993:                                   assigned exceeds 10.  In this case, only
 6994:                                   one bubble per line is permitted, but more 
 6995:                                   than one line might contain bubbles, e.g.
 6996:                                   bubbling of: line 1 - J, line 2 - J, 
 6997:                                   line 3 - B would assign 22 points.  
 6998: 
 6999: =cut
 7000: 
 7001: sub prompt_for_corrections {
 7002:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7003:     my ($current_line,$lines);
 7004:     my @linenums;
 7005:     my $questionnum = $question;
 7006:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7007:         $question = $1;
 7008:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7009:         my $subquestion = $2;
 7010:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7011:         my $subcount = 1;
 7012:         while ($subcount<$subquestion) {
 7013:             $current_line += $subans[$subcount-1];
 7014:             $subcount ++;
 7015:         }
 7016:         $lines = $subans[$subquestion-1];
 7017:     } else {
 7018:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7019:         $lines        = $bubble_lines_per_response{$question-1};
 7020:     }
 7021:     if ($lines > 1) {
 7022:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7023:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7024:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7025:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7026:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7027:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7028:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7029:             $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 />');
 7030:         } else {
 7031:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7032:         }
 7033:     }
 7034:     for (my $i =0; $i < $lines; $i++) {
 7035:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7036: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7037: 	        		  $questionnum,$error,split('', $selected));
 7038:         push(@linenums,$current_line);
 7039: 	$current_line++;
 7040:     }
 7041:     if ($lines > 1) {
 7042: 	$r->print("<hr /><br />");
 7043:     }
 7044:     return @linenums;
 7045: }
 7046: 
 7047: =pod
 7048: 
 7049: =item scantron_bubble_selector
 7050:   
 7051:    Generates the html radiobuttons to correct a single bubble line
 7052:    possibly showing the existing the selected bubbles if known
 7053: 
 7054:  Arguments:
 7055:     $r           - Apache request object
 7056:     $scan_config - hash from &get_scantron_config()
 7057:     $line        - Number of the line being displayed.
 7058:     $questionnum - Question number (may include subquestion)
 7059:     $error       - Type of error.
 7060:     @selected    - Array of bubbles picked on this line.
 7061: 
 7062: =cut
 7063: 
 7064: sub scantron_bubble_selector {
 7065:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7066:     my $max=$$scan_config{'Qlength'};
 7067: 
 7068:     my $scmode=$$scan_config{'Qon'};
 7069:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7070: 
 7071:     my @alphabet=('A'..'Z');
 7072:     $r->print(&Apache::loncommon::start_data_table().
 7073:               &Apache::loncommon::start_data_table_row());
 7074:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7075:     for (my $i=0;$i<$max+1;$i++) {
 7076: 	$r->print("\n".'<td align="center">');
 7077: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7078: 	else { $r->print('&nbsp;'); }
 7079: 	$r->print('</td>');
 7080:     }
 7081:     $r->print(&Apache::loncommon::end_data_table_row().
 7082:               &Apache::loncommon::start_data_table_row());
 7083:     for (my $i=0;$i<$max;$i++) {
 7084: 	$r->print("\n".
 7085: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7086: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7087:     }
 7088:     my $nobub_checked = ' ';
 7089:     if ($error eq 'missingbubble') {
 7090:         $nobub_checked = ' checked = "checked" ';
 7091:     }
 7092:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7093: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7094:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7095:               $line.'" value="'.$questionnum.'" /></td>');
 7096:     $r->print(&Apache::loncommon::end_data_table_row().
 7097:               &Apache::loncommon::end_data_table());
 7098: }
 7099: 
 7100: =pod
 7101: 
 7102: =item num_matches
 7103: 
 7104:    Counts the number of characters that are the same between the two arguments.
 7105: 
 7106:  Arguments:
 7107:    $orig - CODE from the scanline
 7108:    $code - CODE to match against
 7109: 
 7110:  Returns:
 7111:    $count - integer count of the number of same characters between the
 7112:             two arguments
 7113: 
 7114: =cut
 7115: 
 7116: sub num_matches {
 7117:     my ($orig,$code) = @_;
 7118:     my @code=split(//,$code);
 7119:     my @orig=split(//,$orig);
 7120:     my $same=0;
 7121:     for (my $i=0;$i<scalar(@code);$i++) {
 7122: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7123:     }
 7124:     return $same;
 7125: }
 7126: 
 7127: =pod
 7128: 
 7129: =item scantron_get_closely_matching_CODEs
 7130: 
 7131:    Cycles through all CODEs and finds the set that has the greatest
 7132:    number of same characters as the provided CODE
 7133: 
 7134:  Arguments:
 7135:    $allcodes - hash ref returned by &get_codes()
 7136:    $CODE     - CODE from the current scanline
 7137: 
 7138:  Returns:
 7139:    2 element list
 7140:     - first elements is number of how closely matching the best fit is 
 7141:       (5 means best set has 5 matching characters)
 7142:     - second element is an arrary ref containing the set of valid CODEs
 7143:       that best fit the passed in CODE
 7144: 
 7145: =cut
 7146: 
 7147: sub scantron_get_closely_matching_CODEs {
 7148:     my ($allcodes,$CODE)=@_;
 7149:     my @CODEs;
 7150:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7151: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7152:     }
 7153: 
 7154:     return ($#CODEs,$CODEs[-1]);
 7155: }
 7156: 
 7157: =pod
 7158: 
 7159: =item get_codes
 7160: 
 7161:    Builds a hash which has keys of all of the valid CODEs from the selected
 7162:    set of remembered CODEs.
 7163: 
 7164:  Arguments:
 7165:   $old_name - name of the set of remembered CODEs
 7166:   $cdom     - domain of the course
 7167:   $cnum     - internal course name
 7168: 
 7169:  Returns:
 7170:   %allcodes - keys are the valid CODEs, values are all 1
 7171: 
 7172: =cut
 7173: 
 7174: sub get_codes {
 7175:     my ($old_name, $cdom, $cnum) = @_;
 7176:     if (!$old_name) {
 7177: 	$old_name=$env{'form.scantron_CODElist'};
 7178:     }
 7179:     if (!$cdom) {
 7180: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7181:     }
 7182:     if (!$cnum) {
 7183: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7184:     }
 7185:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7186: 				    $cdom,$cnum);
 7187:     my %allcodes;
 7188:     if ($result{"type\0$old_name"} eq 'number') {
 7189: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7190:     } else {
 7191: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7192:     }
 7193:     return %allcodes;
 7194: }
 7195: 
 7196: =pod
 7197: 
 7198: =item scantron_validate_CODE
 7199: 
 7200:    Validates all scanlines in the selected file to not have any
 7201:    invalid or underspecified CODEs and that none of the codes are
 7202:    duplicated if this was requested.
 7203: 
 7204: =cut
 7205: 
 7206: sub scantron_validate_CODE {
 7207:     my ($r,$currentphase) = @_;
 7208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7209:     if ($scantron_config{'CODElocation'} &&
 7210: 	$scantron_config{'CODEstart'} &&
 7211: 	$scantron_config{'CODElength'}) {
 7212: 	if (!defined($env{'form.scantron_CODElist'})) {
 7213: 	    &FIXME_blow_up()
 7214: 	}
 7215:     } else {
 7216: 	return (0,$currentphase+1);
 7217:     }
 7218:     
 7219:     my %usedCODEs;
 7220: 
 7221:     my %allcodes=&get_codes();
 7222: 
 7223:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7224: 
 7225:     my ($scanlines,$scan_data)=&scantron_getfile();
 7226:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7227: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7228: 	if ($line=~/^[\s\cz]*$/) { next; }
 7229: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7230: 						 $scan_data);
 7231: 	my $CODE=$$scan_record{'scantron.CODE'};
 7232: 	my $error=0;
 7233: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7234: 	    &scantron_get_correction($r,$i,$scan_record,
 7235: 				     \%scantron_config,
 7236: 				     $line,'incorrectCODE',\%allcodes);
 7237: 	    return(1,$currentphase);
 7238: 	}
 7239: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7240: 	    && !$$scan_record{'scantron.useCODE'}) {
 7241: 	    &scantron_get_correction($r,$i,$scan_record,
 7242: 				     \%scantron_config,
 7243: 				     $line,'incorrectCODE',\%allcodes);
 7244: 	    return(1,$currentphase);
 7245: 	}
 7246: 	if (exists($usedCODEs{$CODE}) 
 7247: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7248: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7249: 	    &scantron_get_correction($r,$i,$scan_record,
 7250: 				     \%scantron_config,
 7251: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7252: 	    return(1,$currentphase);
 7253: 	}
 7254: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7255:     }
 7256:     return (0,$currentphase+1);
 7257: }
 7258: 
 7259: =pod
 7260: 
 7261: =item scantron_validate_doublebubble
 7262: 
 7263:    Validates all scanlines in the selected file to not have any
 7264:    bubble lines with multiple bubbles marked.
 7265: 
 7266: =cut
 7267: 
 7268: sub scantron_validate_doublebubble {
 7269:     my ($r,$currentphase) = @_;
 7270:     #get student info
 7271:     my $classlist=&Apache::loncoursedata::get_classlist();
 7272:     my %idmap=&username_to_idmap($classlist);
 7273: 
 7274:     #get scantron line setup
 7275:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7276:     my ($scanlines,$scan_data)=&scantron_getfile();
 7277:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7278: 
 7279:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7280: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7281: 	if ($line=~/^[\s\cz]*$/) { next; }
 7282: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7283: 						 $scan_data);
 7284: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7285: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7286: 				 'doublebubble',
 7287: 				 $$scan_record{'scantron.doubleerror'});
 7288:     	return (1,$currentphase);
 7289:     }
 7290:     return (0,$currentphase+1);
 7291: }
 7292: 
 7293: =pod
 7294: 
 7295: =item scantron_get_maxbubble
 7296: 
 7297:    Returns the maximum number of bubble lines that are expected to
 7298:    occur. Does this by walking the selected sequence rendering the
 7299:    resource and then checking &Apache::lonxml::get_problem_counter()
 7300:    for what the current value of the problem counter is.
 7301: 
 7302:    Caches the results to $env{'form.scantron_maxbubble'},
 7303:    $env{'form.scantron.bubble_lines.n'}, 
 7304:    $env{'form.scantron.first_bubble_line.n'} and
 7305:    $env{"form.scantron.sub_bubblelines.n"}
 7306:    which are the total number of bubble, lines, the number of bubble
 7307:    lines for response n and number of the first bubble line for response n,
 7308:    and a comma separated list of numbers of bubble lines for sub-questions
 7309:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7310: 
 7311: =cut
 7312: 
 7313: sub scantron_get_maxbubble {
 7314:     if (defined($env{'form.scantron_maxbubble'}) &&
 7315: 	$env{'form.scantron_maxbubble'}) {
 7316: 	&restore_bubble_lines();
 7317: 	return $env{'form.scantron_maxbubble'};
 7318:     }
 7319: 
 7320:     my (undef, undef, $sequence) =
 7321: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7322: 
 7323:     my $navmap=Apache::lonnavmaps::navmap->new();
 7324:     my $map=$navmap->getResourceByUrl($sequence);
 7325:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7326: 
 7327:     &Apache::lonxml::clear_problem_counter();
 7328: 
 7329:     my $uname       = $env{'form.student'};
 7330:     my $udom        = $env{'form.userdom'};
 7331:     my $cid         = $env{'request.course.id'};
 7332:     my $total_lines = 0;
 7333:     %bubble_lines_per_response = ();
 7334:     %first_bubble_line         = ();
 7335:     %subdivided_bubble_lines   = ();
 7336:     %responsetype_per_response = ();
 7337:   
 7338:     my $response_number = 0;
 7339:     my $bubble_line     = 0;
 7340:     foreach my $resource (@resources) {
 7341:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7342:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7343:             foreach my $part_id (@{$parts}) {
 7344: 
 7345:                 my $lines;
 7346: 
 7347: 	        # TODO - make this a persistent hash not an array.
 7348: 
 7349:                 # optionresponse, matchresponse and rankresponse type items 
 7350:                 # render as separate sub-questions in exam mode.
 7351:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7352:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7353:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7354:                     my ($numbub,$numshown);
 7355:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7356:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7357:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7358:                         }
 7359:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7360:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7361:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7362:                         }
 7363:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7364:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7365:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7366:                         }
 7367:                     }
 7368:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7369:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7370:                     }
 7371:                     my $bubbles_per_line = 10;
 7372:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7373:                     if (($numbub % $bubbles_per_line) != 0) {
 7374:                         $inner_bubble_lines++;
 7375:                     }
 7376:                     for (my $i=0; $i<$numshown; $i++) {
 7377:                         $subdivided_bubble_lines{$response_number} .= 
 7378:                             $inner_bubble_lines.',';
 7379:                     }
 7380:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7381:                     $lines = $numshown * $inner_bubble_lines;
 7382:                 } else {
 7383:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7384:                 } 
 7385: 
 7386:                 $first_bubble_line{$response_number} = $bubble_line;
 7387: 	        $bubble_lines_per_response{$response_number} = $lines;
 7388:                 $responsetype_per_response{$response_number} = 
 7389:                     $analysis->{$part_id.'.type'};
 7390: 	        $response_number++;
 7391: 
 7392: 	        $bubble_line +=  $lines;
 7393: 	        $total_lines +=  $lines;
 7394: 	    }
 7395:         }
 7396:     }
 7397:     &Apache::lonnet::delenv('scantron\.');
 7398: 
 7399:     &save_bubble_lines();
 7400:     $env{'form.scantron_maxbubble'} =
 7401: 	$total_lines;
 7402:     return $env{'form.scantron_maxbubble'};
 7403: }
 7404: 
 7405: sub scantron_partids_tograde {
 7406:     my ($resource,$cid,$uname,$udom) = @_;
 7407:     my (%analysis,@parts);
 7408: 
 7409:     if (ref($resource)) {
 7410:         my $symb = $resource->symb();
 7411:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7412:                                         ('symb' => $symb,
 7413:                                          'grade_target' => 'analyze',
 7414:                                          'grade_courseid' => $cid,
 7415:                                          'grade_domain' => $udom,
 7416:                                          'grade_username' => $uname));
 7417:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
 7418:         %analysis = &Apache::lonnet::str2hash($an);
 7419: 
 7420:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7421:             foreach my $part (@{$analysis{'parts'}}) {
 7422:                 my ($id,$respid) = split(/\./,$part);
 7423:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7424:                     push(@parts,$part);
 7425:                 }
 7426:             }
 7427:         }
 7428:     }
 7429:     return (\%analysis,\@parts);
 7430: }
 7431: 
 7432: =pod
 7433: 
 7434: =item scantron_validate_missingbubbles
 7435: 
 7436:    Validates all scanlines in the selected file to not have any
 7437:     answers that don't have bubbles that have not been verified
 7438:     to be bubble free.
 7439: 
 7440: =cut
 7441: 
 7442: sub scantron_validate_missingbubbles {
 7443:     my ($r,$currentphase) = @_;
 7444:     #get student info
 7445:     my $classlist=&Apache::loncoursedata::get_classlist();
 7446:     my %idmap=&username_to_idmap($classlist);
 7447: 
 7448:     #get scantron line setup
 7449:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7450:     my ($scanlines,$scan_data)=&scantron_getfile();
 7451:     my $max_bubble=&scantron_get_maxbubble();
 7452:     if (!$max_bubble) { $max_bubble=2**31; }
 7453:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7454: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7455: 	if ($line=~/^[\s\cz]*$/) { next; }
 7456: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7457: 						 $scan_data);
 7458: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7459: 	my @to_correct;
 7460: 	
 7461: 	# Probably here's where the error is...
 7462: 
 7463: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7464:             my $lastbubble;
 7465:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7466:                my $question = $1;
 7467:                my $subquestion = $2;
 7468:                if (!defined($first_bubble_line{$question -1})) { next; }
 7469:                my $first = $first_bubble_line{$question-1};
 7470:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7471:                my $subcount = 1;
 7472:                while ($subcount<$subquestion) {
 7473:                    $first += $subans[$subcount-1];
 7474:                    $subcount ++;
 7475:                }
 7476:                my $count = $subans[$subquestion-1];
 7477:                $lastbubble = $first + $count;
 7478:             } else {
 7479:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7480:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7481:             }
 7482:             if ($lastbubble > $max_bubble) { next; }
 7483: 	    push(@to_correct,$missing);
 7484: 	}
 7485: 	if (@to_correct) {
 7486: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7487: 				     $line,'missingbubble',\@to_correct);
 7488: 	    return (1,$currentphase);
 7489: 	}
 7490: 
 7491:     }
 7492:     return (0,$currentphase+1);
 7493: }
 7494: 
 7495: =pod
 7496: 
 7497: =item scantron_process_students
 7498: 
 7499:    Routine that does the actual grading of the bubble sheet information.
 7500: 
 7501:    The parsed scanline hash is added to %env 
 7502: 
 7503:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7504:    foreach resource , with the form data of
 7505: 
 7506: 	'submitted'     =>'scantron' 
 7507: 	'grade_target'  =>'grade',
 7508: 	'grade_username'=> username of student
 7509: 	'grade_domain'  => domain of student
 7510: 	'grade_courseid'=> of course
 7511: 	'grade_symb'    => symb of resource to grade
 7512: 
 7513:     This triggers a grading pass. The problem grading code takes care
 7514:     of converting the bubbled letter information (now in %env) into a
 7515:     valid submission.
 7516: 
 7517: =cut
 7518: 
 7519: sub scantron_process_students {
 7520:     my ($r) = @_;
 7521: 
 7522:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7523:     my ($symb)=&get_symb($r);
 7524:     if (!$symb) {
 7525: 	return '';
 7526:     }
 7527:     my $default_form_data=&defaultFormData($symb);
 7528: 
 7529:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7530:     my ($scanlines,$scan_data)=&scantron_getfile();
 7531:     my $classlist=&Apache::loncoursedata::get_classlist();
 7532:     my %idmap=&username_to_idmap($classlist);
 7533:     my $navmap=Apache::lonnavmaps::navmap->new();
 7534:     my $map=$navmap->getResourceByUrl($sequence);
 7535:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7536: 
 7537:     my ($uname,$udom,%partids_by_symb);
 7538:     foreach my $resource (@resources) {
 7539:         my $ressymb = $resource->symb();
 7540:         my ($analysis,$parts) =
 7541:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7542:         $partids_by_symb{$ressymb} = $parts;
 7543:     }
 7544: #    $r->print("geto ".scalar(@resources)."<br />");
 7545:     my $result= <<SCANTRONFORM;
 7546: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7547:   <input type="hidden" name="command" value="scantron_configphase" />
 7548:   $default_form_data
 7549: SCANTRONFORM
 7550:     $r->print($result);
 7551: 
 7552:     my @delayqueue;
 7553:     my (%completedstudents,,%scandata);
 7554:     
 7555:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7556:     my $count=&get_todo_count($scanlines,$scan_data);
 7557:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7558:  				    'Scantron Progress',$count,
 7559: 				    'inline',undef,'scantronupload');
 7560:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7561: 					  'Processing first student');
 7562:     $r->print('<br />');
 7563:     my $start=&Time::HiRes::time();
 7564:     my $i=-1;
 7565:     my $started;
 7566: 
 7567:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7568:     
 7569: 
 7570:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7571:     # the user and return.
 7572: 
 7573:     if ($ssi_error) {
 7574: 	$r->print("</form>");
 7575: 	&ssi_print_error($r);
 7576: 	$r->print(&show_grading_menu_form($symb));
 7577:         &Apache::lonnet::remove_lock($lock);
 7578: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7579:     }
 7580: 
 7581:     my %lettdig = &letter_to_digits();
 7582:     my $numletts = scalar(keys(%lettdig));
 7583: 
 7584:     while ($i<$scanlines->{'count'}) {
 7585:  	($uname,$udom)=('','');
 7586:  	$i++;
 7587:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7588:  	if ($line=~/^[\s\cz]*$/) { next; }
 7589: 	if ($started) {
 7590: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7591: 						     'last student');
 7592: 	}
 7593: 	$started=1;
 7594:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7595:  						 $scan_data);
 7596:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7597:  					      \%idmap,$i)) {
 7598:   	    &scantron_add_delay(\@delayqueue,$line,
 7599:  				'Unable to find a student that matches',1);
 7600:  	    next;
 7601:   	}
 7602:  	if (exists $completedstudents{$uname}) {
 7603:  	    &scantron_add_delay(\@delayqueue,$line,
 7604:  				'Student '.$uname.' has multiple sheets',2);
 7605:  	    next;
 7606:  	}
 7607:   	($uname,$udom)=split(/:/,$uname);
 7608: 
 7609: 	&Apache::lonxml::clear_problem_counter();
 7610:   	&Apache::lonnet::appenv($scan_record);
 7611: 
 7612: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7613: 	    &scantron_putfile($scanlines,$scan_data);
 7614: 	}
 7615: 
 7616:         my $scancode;
 7617:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7618:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7619:             $scancode = $scan_record->{'scantron.CODE'};
 7620:         } else {
 7621:             $scancode = '';
 7622:         }
 7623: 
 7624:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7625:                                    @resources) eq 'ssi_error') {
 7626:             $ssi_error = 0; # So end of handler error message does not trigger.
 7627:             $r->print("</form>");
 7628:             &ssi_print_error($r);
 7629:             $r->print(&show_grading_menu_form($symb));
 7630:             &Apache::lonnet::remove_lock($lock);
 7631:             return '';      # Why return ''?  Beats me.
 7632:         }
 7633: 
 7634: 	$completedstudents{$uname}={'line'=>$line};
 7635:         if ($env{'form.verifyrecord'}) {
 7636:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7637:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7638:             chomp($studentdata);
 7639:             $studentdata =~ s/\r$//;
 7640:             my $studentrecord = '';
 7641:             my $counter = -1;
 7642:             foreach my $resource (@resources) {
 7643:                 ($counter,my $recording) =
 7644:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7645:                                              $counter,$studentdata,\%partids_by_symb,
 7646:                                              \%scantron_config,\%lettdig,$numletts);
 7647:                 $studentrecord .= $recording;
 7648:             }
 7649:             if ($studentrecord ne $studentdata) {
 7650:                 $counter = -1;
 7651:                 $studentrecord = '';
 7652:                 foreach my $resource (@resources) {
 7653:                     ($counter,my $recording) =
 7654:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7655:                                                  $counter,$studentdata,\%partids_by_symb,
 7656:                                                  \%scantron_config,\%lettdig,$numletts);
 7657:                     $studentrecord .= $recording;
 7658:                 }
 7659:                 if ($studentrecord ne $studentdata) {
 7660:                     $r->print('<p><span class="LC_error">');
 7661:                     if ($scancode eq '') {
 7662:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7663:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7664:                     } else {
 7665:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7666:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7667:                     }
 7668:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7669:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7670:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7671:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7672:                               &Apache::loncommon::start_data_table_row().
 7673:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7674:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7675:                               &Apache::loncommon::end_data_table_row().
 7676:                               &Apache::loncommon::start_data_table_row().
 7677:                               '<td>Stored submissions</td>'.
 7678:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7679:                               &Apache::loncommon::end_data_table_row().
 7680:                               &Apache::loncommon::end_data_table().'</p>');
 7681:                 } else {
 7682:                     $r->print('<br /><span class="LC_warning">'.
 7683:                              &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 />'.
 7684:                              &mt("As a consequence, this user's submission history records two tries.").
 7685:                                  '</span><br />');
 7686:                 }
 7687:             }
 7688:         }
 7689: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7690:     } continue {
 7691: 	&Apache::lonxml::clear_problem_counter();
 7692: 	&Apache::lonnet::delenv('scantron\.');
 7693:     }
 7694:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7695:     &Apache::lonnet::remove_lock($lock);
 7696: #    my $lasttime = &Time::HiRes::time()-$start;
 7697: #    $r->print("<p>took $lasttime</p>");
 7698: 
 7699:     $r->print("</form>");
 7700:     $r->print(&show_grading_menu_form($symb));
 7701:     return '';
 7702: }
 7703: 
 7704: sub grade_student_bubbles {
 7705:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
 7706:     foreach my $resource (@resources) {
 7707:         my %form = ('submitted'     => 'scantron',
 7708:                     'grade_target'  => 'grade',
 7709:                     'grade_username'=> $uname,
 7710:                     'grade_domain'  => $udom,
 7711:                     'grade_courseid'=> $env{'request.course.id'},
 7712:                     'grade_symb'    => $resource->symb(),
 7713:                     'code'          => $scancode);
 7714:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7715:         return 'ssi_error' if ($ssi_error);
 7716:         last if (&Apache::loncommon::connection_aborted($r));
 7717:     }
 7718:     return;
 7719: }
 7720: 
 7721: =pod
 7722: 
 7723: =item scantron_upload_scantron_data
 7724: 
 7725:     Creates the screen for adding a new bubble sheet data file to a course.
 7726: 
 7727: =cut
 7728: 
 7729: sub scantron_upload_scantron_data {
 7730:     my ($r)=@_;
 7731:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7732:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7733: 							  'domainid',
 7734: 							  'coursename');
 7735:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7736: 						   'domainid');
 7737:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7738:     $r->print('
 7739: <script type="text/javascript" language="javascript">
 7740:     function checkUpload(formname) {
 7741: 	if (formname.upfile.value == "") {
 7742: 	    alert("Please use the browse button to select a file from your local directory.");
 7743: 	    return false;
 7744: 	}
 7745: 	formname.submit();
 7746:     }
 7747: </script>
 7748: 
 7749: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7750: '.$default_form_data.'
 7751: <table>
 7752: <tr><td>'.$select_link.'                             </td></tr>
 7753: <tr><td>'.&mt('Course ID:').'     </td>
 7754:     <td><input name="courseid"   type="text" />      </td></tr>
 7755: <tr><td>'.&mt('Course Name:').'   </td>
 7756:     <td><input name="coursename" type="text" />      </td></tr>
 7757: <tr><td>'.&mt('Domain:').'        </td>
 7758:     <td>'.$domsel.'                                  </td></tr>
 7759: <tr><td>'.&mt('File to upload:').'</td>
 7760:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7761: </table>
 7762: <input name="command" value="scantronupload_save" type="hidden" />
 7763: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7764: </form>
 7765: ');
 7766:     return '';
 7767: }
 7768: 
 7769: =pod
 7770: 
 7771: =item scantron_upload_scantron_data_save
 7772: 
 7773:    Adds a provided bubble information data file to the course if user
 7774:    has the correct privileges to do so.  
 7775: 
 7776: =cut
 7777: 
 7778: sub scantron_upload_scantron_data_save {
 7779:     my($r)=@_;
 7780:     my ($symb)=&get_symb($r,1);
 7781:     my $doanotherupload=
 7782: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7783: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7784: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7785: 	'</form>'."\n";
 7786:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7787: 	!&Apache::lonnet::allowed('usc',
 7788: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7789: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7790: 	if ($symb) {
 7791: 	    $r->print(&show_grading_menu_form($symb));
 7792: 	} else {
 7793: 	    $r->print($doanotherupload);
 7794: 	}
 7795: 	return '';
 7796:     }
 7797:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7798:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7799:     my $fname=$env{'form.upfile.filename'};
 7800:     #FIXME
 7801:     #copied from lonnet::userfileupload()
 7802:     #make that function able to target a specified course
 7803:     # Replace Windows backslashes by forward slashes
 7804:     $fname=~s/\\/\//g;
 7805:     # Get rid of everything but the actual filename
 7806:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7807:     # Replace spaces by underscores
 7808:     $fname=~s/\s+/\_/g;
 7809:     # Replace all other weird characters by nothing
 7810:     $fname=~s/[^\w\.\-]//g;
 7811:     # See if there is anything left
 7812:     unless ($fname) { return 'error: no uploaded file'; }
 7813:     my $uploadedfile=$fname;
 7814:     $fname='scantron_orig_'.$fname;
 7815:     if (length($env{'form.upfile'}) < 2) {
 7816: 	$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>"));
 7817:     } else {
 7818: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7819: 	if ($result =~ m|^/uploaded/|) {
 7820: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7821: 			  (length($env{'form.upfile'})-1),
 7822: 			  '<span class="LC_filename">'.$result."</span>"));
 7823: 	} else {
 7824: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7825: 			  $result,
 7826: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7827: 
 7828: 	}
 7829:     }
 7830:     if ($symb) {
 7831: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7832:     } else {
 7833: 	$r->print($doanotherupload);
 7834:     }
 7835:     return '';
 7836: }
 7837: 
 7838: =pod
 7839: 
 7840: =item valid_file
 7841: 
 7842:    Validates that the requested bubble data file exists in the course.
 7843: 
 7844: =cut
 7845: 
 7846: sub valid_file {
 7847:     my ($requested_file)=@_;
 7848:     foreach my $filename (sort(&scantron_filenames())) {
 7849: 	if ($requested_file eq $filename) { return 1; }
 7850:     }
 7851:     return 0;
 7852: }
 7853: 
 7854: =pod
 7855: 
 7856: =item scantron_download_scantron_data
 7857: 
 7858:    Shows a list of the three internal files (original, corrected,
 7859:    skipped) for a specific bubble sheet data file that exists in the
 7860:    course.
 7861: 
 7862: =cut
 7863: 
 7864: sub scantron_download_scantron_data {
 7865:     my ($r)=@_;
 7866:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7867:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7869:     my $file=$env{'form.scantron_selectfile'};
 7870:     if (! &valid_file($file)) {
 7871: 	$r->print('
 7872: 	<p>
 7873: 	    '.&mt('The requested file name was invalid.').'
 7874:         </p>
 7875: ');
 7876: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7877: 	return;
 7878:     }
 7879:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7880:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7881:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7882:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7883:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7884:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7885:     $r->print('
 7886:     <p>
 7887: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7888: 	      '<a href="'.$orig.'">','</a>').'
 7889:     </p>
 7890:     <p>
 7891: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7892: 	      '<a href="'.$corrected.'">','</a>').'
 7893:     </p>
 7894:     <p>
 7895: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7896: 	      '<a href="'.$skipped.'">','</a>').'
 7897:     </p>
 7898: ');
 7899:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7900:     return '';
 7901: }
 7902: 
 7903: sub checkscantron_results {
 7904:     my ($r) = @_;
 7905:     my ($symb)=&get_symb($r);
 7906:     if (!$symb) {return '';}
 7907:     my $grading_menu_button=&show_grading_menu_form($symb);
 7908:     my $cid = $env{'request.course.id'};
 7909:     my %lettdig = &letter_to_digits();
 7910:     my $numletts = scalar(keys(%lettdig));
 7911:     my $cnum = $env{'course.'.$cid.'.num'};
 7912:     my $cdom = $env{'course.'.$cid.'.domain'};
 7913:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7914:     my %record;
 7915:     my %scantron_config =
 7916:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7917:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7918:     my $classlist=&Apache::loncoursedata::get_classlist();
 7919:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7920:     my $navmap=Apache::lonnavmaps::navmap->new();
 7921:     my $map=$navmap->getResourceByUrl($sequence);
 7922:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7923:     my ($uname,$udom,%partids_by_symb);
 7924:     foreach my $resource (@resources) {
 7925:         my $ressymb = $resource->symb();
 7926:         my ($analysis,$parts) =
 7927:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7928:         $partids_by_symb{$ressymb} = $parts;
 7929:     }
 7930:     my (%scandata,%lastname,%bylast);
 7931:     $r->print('
 7932: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7933: 
 7934:     my @delayqueue;
 7935:     my %completedstudents;
 7936: 
 7937:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7938:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7939:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7940:                                     'inline',undef,'checkscantron');
 7941:     my ($username,$domain,$started);
 7942: 
 7943:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7944: 
 7945:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7946:                                           'Processing first student');
 7947:     my $start=&Time::HiRes::time();
 7948:     my $i=-1;
 7949: 
 7950:     while ($i<$scanlines->{'count'}) {
 7951:         ($username,$domain,$uname)=('','','');
 7952:         $i++;
 7953:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7954:         if ($line=~/^[\s\cz]*$/) { next; }
 7955:         if ($started) {
 7956:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7957:                                                      'last student');
 7958:         }
 7959:         $started=1;
 7960:         my $scan_record=
 7961:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7962:                                                      $scan_data);
 7963:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7964:                                                               \%idmap,$i)) {
 7965:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7966:                                 'Unable to find a student that matches',1);
 7967:             next;
 7968:         }
 7969:         if (exists $completedstudents{$uname}) {
 7970:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7971:                                 'Student '.$uname.' has multiple sheets',2);
 7972:             next;
 7973:         }
 7974:         my $pid = $scan_record->{'scantron.ID'};
 7975:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7976:         push(@{$bylast{$lastname{$pid}}},$pid);
 7977:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7978:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7979:         chomp($scandata{$pid});
 7980:         $scandata{$pid} =~ s/\r$//;
 7981:         ($username,$domain)=split(/:/,$uname);
 7982:         my $counter = -1;
 7983:         foreach my $resource (@resources) {
 7984:             ($counter,my $recording) =
 7985:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7986:                                          $scandata{$pid},\%partids_by_symb,
 7987:                                          \%scantron_config,\%lettdig,$numletts);
 7988:             $record{$pid} .= $recording;
 7989:         }
 7990:     }
 7991:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7992:     $r->print('<br />');
 7993:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7994:     $passed = 0;
 7995:     $failed = 0;
 7996:     $numstudents = 0;
 7997:     foreach my $last (sort(keys(%bylast))) {
 7998:         if (ref($bylast{$last}) eq 'ARRAY') {
 7999:             foreach my $pid (sort(@{$bylast{$last}})) {
 8000:                 my $showscandata = $scandata{$pid};
 8001:                 my $showrecord = $record{$pid};
 8002:                 $showscandata =~ s/\s/&nbsp;/g;
 8003:                 $showrecord =~ s/\s/&nbsp;/g;
 8004:                 if ($scandata{$pid} eq $record{$pid}) {
 8005:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8006:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8007: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8008: '</tr>'."\n".
 8009: '<tr class="'.$css_class.'">'."\n".
 8010: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8011:                     $passed ++;
 8012:                 } else {
 8013:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8014:                     $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".
 8015: '</tr>'."\n".
 8016: '<tr class="'.$css_class.'">'."\n".
 8017: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8018: '</tr>'."\n";
 8019:                     $failed ++;
 8020:                 }
 8021:                 $numstudents ++;
 8022:             }
 8023:         }
 8024:     }
 8025:     $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>');
 8026:     $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>');
 8027:     if ($passed) {
 8028:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8029:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8030:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8031:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8032:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8033:                  $okstudents."\n".
 8034:                  &Apache::loncommon::end_data_table().'<br />');
 8035:     }
 8036:     if ($failed) {
 8037:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8038:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8039:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8040:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8041:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8042:                  $badstudents."\n".
 8043:                  &Apache::loncommon::end_data_table()).'<br />'.
 8044:                  &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.');  
 8045:     }
 8046:     $r->print('</form><br />'.$grading_menu_button);
 8047:     return;
 8048: }
 8049: 
 8050: sub verify_scantron_grading {
 8051:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
 8052:         $scantron_config,$lettdig,$numletts) = @_;
 8053:     my ($record,%expected,%startpos);
 8054:     return ($counter,$record) if (!ref($resource));
 8055:     return ($counter,$record) if (!$resource->is_problem());
 8056:     my $symb = $resource->symb();
 8057:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
 8058:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
 8059:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8060:         $counter ++;
 8061:         $expected{$part_id} = 0;
 8062:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8063:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8064:             foreach my $item (@sub_lines) {
 8065:                 $expected{$part_id} += $item;
 8066:             }
 8067:         } else {
 8068:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8069:         }
 8070:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8071:     }
 8072:     if ($symb) {
 8073:         my %recorded;
 8074:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8075:         if ($returnhash{'version'}) {
 8076:             my %lasthash=();
 8077:             my $version;
 8078:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8079:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8080:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8081:                 }
 8082:             }
 8083:             foreach my $key (keys(%lasthash)) {
 8084:                 if ($key =~ /\.scantron$/) {
 8085:                     my $value = &unescape($lasthash{$key});
 8086:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8087:                     if ($value eq '') {
 8088:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8089:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8090:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8091:                             }
 8092:                         }
 8093:                     } else {
 8094:                         my @tocheck;
 8095:                         my @items = split(//,$value);
 8096:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8097:                             ($scantron_config->{'Qon'} eq 'number')) {
 8098:                             if (@items < $expected{$part_id}) {
 8099:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8100:                                 my @singles = split(//,$fragment);
 8101:                                 foreach my $pos (@singles) {
 8102:                                     if ($pos eq ' ') {
 8103:                                         push(@tocheck,$pos);
 8104:                                     } else {
 8105:                                         my $next = shift(@items);
 8106:                                         push(@tocheck,$next);
 8107:                                     }
 8108:                                 }
 8109:                             } else {
 8110:                                 @tocheck = @items;
 8111:                             }
 8112:                             foreach my $letter (@tocheck) {
 8113:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8114:                                     if ($letter !~ /^[A-J]$/) {
 8115:                                         $letter = $scantron_config->{'Qoff'};
 8116:                                     }
 8117:                                     $recorded{$part_id} .= $letter;
 8118:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8119:                                     my $digit;
 8120:                                     if ($letter !~ /^[A-J]$/) {
 8121:                                         $digit = $scantron_config->{'Qoff'};
 8122:                                     } else {
 8123:                                         $digit = $lettdig->{$letter};
 8124:                                     }
 8125:                                     $recorded{$part_id} .= $digit;
 8126:                                 }
 8127:                             }
 8128:                         } else {
 8129:                             @tocheck = @items;
 8130:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8131:                                 my $curr_sub = shift(@tocheck);
 8132:                                 my $digit;
 8133:                                 if ($curr_sub =~ /^[A-J]$/) {
 8134:                                     $digit = $lettdig->{$curr_sub}-1;
 8135:                                 }
 8136:                                 if ($curr_sub eq 'J') {
 8137:                                     $digit += scalar($numletts);
 8138:                                 }
 8139:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8140:                                     if ($j == $digit) {
 8141:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8142:                                     } else {
 8143:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8144:                                     }
 8145:                                 }
 8146:                             }
 8147:                         }
 8148:                     }
 8149:                 }
 8150:             }
 8151:         }
 8152:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8153:             if ($recorded{$part_id} eq '') {
 8154:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8155:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8156:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8157:                     }
 8158:                 }
 8159:             }
 8160:             $record .= $recorded{$part_id};
 8161:         }
 8162:     }
 8163:     return ($counter,$record);
 8164: }
 8165: 
 8166: sub letter_to_digits {
 8167:     my %lettdig = (
 8168:                     A => 1,
 8169:                     B => 2,
 8170:                     C => 3,
 8171:                     D => 4,
 8172:                     E => 5,
 8173:                     F => 6,
 8174:                     G => 7,
 8175:                     H => 8,
 8176:                     I => 9,
 8177:                     J => 0,
 8178:                   );
 8179:     return %lettdig;
 8180: }
 8181: 
 8182: =pod
 8183: 
 8184: =back
 8185: 
 8186: =cut
 8187: 
 8188: #-------- end of section for handling grading scantron forms -------
 8189: #
 8190: #-------------------------------------------------------------------
 8191: 
 8192: #-------------------------- Menu interface -------------------------
 8193: #
 8194: #--- Show a Grading Menu button - Calls the next routine ---
 8195: sub show_grading_menu_form {
 8196:     my ($symb)=@_;
 8197:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8198: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8199: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8200: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8201: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8202: 	'</form>'."\n";
 8203:     return $result;
 8204: }
 8205: 
 8206: # -- Retrieve choices for grading form
 8207: sub savedState {
 8208:     my %savedState = ();
 8209:     if ($env{'form.saveState'}) {
 8210: 	foreach (split(/:/,$env{'form.saveState'})) {
 8211: 	    my ($key,$value) = split(/=/,$_,2);
 8212: 	    $savedState{$key} = $value;
 8213: 	}
 8214:     }
 8215:     return \%savedState;
 8216: }
 8217: 
 8218: sub grading_menu {
 8219:     my ($request) = @_;
 8220:     my ($symb)=&get_symb($request);
 8221:     if (!$symb) {return '';}
 8222:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8223:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8224: 
 8225:     $request->print($table);
 8226:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8227:                   'handgrade'=>$hdgrade,
 8228:                   'probTitle'=>$probTitle,
 8229:                   'command'=>'submit_options',
 8230:                   'saveState'=>"",
 8231:                   'gradingMenu'=>1,
 8232:                   'showgrading'=>"yes");
 8233:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8234:     my @menu = ({ url => $url,
 8235:                      name => &mt('Manual Grading/View Submissions'),
 8236:                      short_description => 
 8237:     &mt('Start the process of hand grading submissions.'),
 8238:                  });
 8239:     $fields{'command'} = 'csvform';
 8240:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8241:     push(@menu, { url => $url,
 8242:                    name => &mt('Upload Scores'),
 8243:                    short_description => 
 8244:             &mt('Specify a file containing the class scores for current resource.')});
 8245:     $fields{'command'} = 'processclicker';
 8246:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8247:     push(@menu, { url => $url,
 8248:                    name => &mt('Process Clicker'),
 8249:                    short_description => 
 8250:             &mt('Specify a file containing the clicker information for this resource.')});
 8251:     $fields{'command'} = 'scantron_selectphase';
 8252:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8253:     push(@menu, { url => $url,
 8254:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8255:                    short_description => 
 8256:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8257:     $fields{'command'} = 'verify';
 8258:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8259:     push(@menu, { url => "",
 8260:                    name => &mt('Verify Receipt'),
 8261:                    short_description => 
 8262:             &mt('')});
 8263:     #
 8264:     # Create the menu
 8265:     my $Str;
 8266:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8267:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8268:     $Str .= '<input type="hidden" name="command" value="" />'.
 8269:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8270: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8271: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8272: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8273: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8274: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8275: 
 8276:     foreach my $menudata (@menu) {
 8277:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8278:             $Str .='    <h3><a '.
 8279:                 $menudata->{'jscript'}.
 8280:                 ' href="'.
 8281:                 $menudata->{'url'}.'" >'.
 8282:                 $menudata->{'name'}."</a></h3>\n";
 8283:         } else {
 8284:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8285:                 $menudata->{'jscript'}.
 8286:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8287:                 ' /> '.
 8288: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8289:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8290:         }
 8291:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8292:             "\n";
 8293:     }
 8294:     $Str .="</form>\n";
 8295:     $request->print(<<GRADINGMENUJS);
 8296: <script type="text/javascript" language="javascript">
 8297:     function checkChoice(formname,val,cmdx) {
 8298: 	if (val <= 2) {
 8299: 	    var cmd = radioSelection(formname.radioChoice);
 8300: 	    var cmdsave = cmd;
 8301: 	} else {
 8302: 	    cmd = cmdx;
 8303: 	    cmdsave = 'submission';
 8304: 	}
 8305: 	formname.command.value = cmd;
 8306: 	if (val < 5) formname.submit();
 8307: 	if (val == 5) {
 8308: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8309: 	        return false;
 8310: 	    } else {
 8311: 	        formname.submit();
 8312: 	    }
 8313: 	}
 8314:     }
 8315: 
 8316:     function checkReceiptNo(formname,nospace) {
 8317: 	var receiptNo = formname.receipt.value;
 8318: 	var checkOpt = false;
 8319: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8320: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8321: 	if (checkOpt) {
 8322: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8323: 	    formname.receipt.value = "";
 8324: 	    formname.receipt.focus();
 8325: 	    return false;
 8326: 	}
 8327: 	return true;
 8328:     }
 8329: </script>
 8330: GRADINGMENUJS
 8331:     &commonJSfunctions($request);
 8332:     return $Str;    
 8333: }
 8334: 
 8335: 
 8336: #--- Displays the submissions first page -------
 8337: sub submit_options {
 8338:     my ($request) = @_;
 8339:     my ($symb)=&get_symb($request);
 8340:     if (!$symb) {return '';}
 8341:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8342: 
 8343:     $request->print(<<GRADINGMENUJS);
 8344: <script type="text/javascript" language="javascript">
 8345:     function checkChoice(formname,val,cmdx) {
 8346: 	if (val <= 2) {
 8347: 	    var cmd = radioSelection(formname.radioChoice);
 8348: 	    var cmdsave = cmd;
 8349: 	} else {
 8350: 	    cmd = cmdx;
 8351: 	    cmdsave = 'submission';
 8352: 	}
 8353: 	formname.command.value = cmd;
 8354: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8355: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8356: 	if (val < 5) formname.submit();
 8357: 	if (val == 5) {
 8358: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8359: 	    formname.submit();
 8360: 	}
 8361: 	if (val < 7) formname.submit();
 8362:     }
 8363: 
 8364:     function checkReceiptNo(formname,nospace) {
 8365: 	var receiptNo = formname.receipt.value;
 8366: 	var checkOpt = false;
 8367: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8368: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8369: 	if (checkOpt) {
 8370: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8371: 	    formname.receipt.value = "";
 8372: 	    formname.receipt.focus();
 8373: 	    return false;
 8374: 	}
 8375: 	return true;
 8376:     }
 8377: </script>
 8378: GRADINGMENUJS
 8379:     &commonJSfunctions($request);
 8380:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8381:     my $result;
 8382:     my (undef,$sections) = &getclasslist('all','0');
 8383:     my $savedState = &savedState();
 8384:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8385:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8386:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8387:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8388: 
 8389:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8390: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8391: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8392: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8393: 	'<input type="hidden" name="command"     value="" />'."\n".
 8394: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8395: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8396: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8397: 
 8398:     $result.='
 8399:     <div class="LC_grade_select_mode">
 8400:       <div class="LC_grade_select_mode_current">
 8401:         <h2>
 8402:           '.&mt('Grade Current Resource').'
 8403:         </h2>
 8404:         <div class="LC_grade_select_mode_body">
 8405:           <div class="LC_grades_resource_info">
 8406:            '.$table.'
 8407:           </div>
 8408:           <div class="LC_grade_select_mode_selector">
 8409:              <div class="LC_grade_select_mode_selector_header">
 8410:                 '.&mt('Sections').'
 8411:              </div>
 8412:              <div class="LC_grade_select_mode_selector_body">
 8413: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8414:     if (ref($sections)) {
 8415: 	foreach my $section (sort(@$sections)) {
 8416: 	    $result.='<option value="'.$section.'" '.
 8417: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8418: 	}
 8419:     }
 8420:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8421:     $result.='
 8422:              </div>
 8423:           </div>
 8424:           <div class="LC_grade_select_mode_selector">
 8425:              <div class="LC_grade_select_mode_selector_header">
 8426:                 '.&mt('Groups').'
 8427:              </div>
 8428:              <div class="LC_grade_select_mode_selector_body">
 8429:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8430:              </div>
 8431:           </div>
 8432:           <div class="LC_grade_select_mode_selector">
 8433:              <div class="LC_grade_select_mode_selector_header">
 8434:                 '.&mt('Access Status').'
 8435:              </div>
 8436:              <div class="LC_grade_select_mode_selector_body">
 8437:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8438:              </div>
 8439:           </div>
 8440:           <div class="LC_grade_select_mode_selector">
 8441:              <div class="LC_grade_select_mode_selector_header">
 8442:                 '.&mt('Submission Status').'
 8443:              </div>
 8444:              <div class="LC_grade_select_mode_selector_body">
 8445:                <select name="submitonly" size="5">
 8446: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8447: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8448: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8449: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8450:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8451:                </select>
 8452:              </div>
 8453:           </div>
 8454:           <div class="LC_grade_select_mode_type_body">
 8455:             <div class="LC_grade_select_mode_type">
 8456:               <label>
 8457:                 <input type="radio" name="radioChoice" value="submission" '.
 8458:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8459:              &mt('Select individual students to grade and view submissions.').'
 8460: 	      </label> 
 8461:             </div>
 8462:             <div class="LC_grade_select_mode_type">
 8463: 	      <label>
 8464:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8465:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8466:                     &mt('Grade all selected students in a grading table.').'
 8467:               </label>
 8468:             </div>
 8469:             <div class="LC_grade_select_mode_type">
 8470: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8471:             </div>
 8472:           </div>
 8473:         </div>
 8474:       </div>
 8475:       <div class="LC_grade_select_mode_page">
 8476:         <h2>
 8477:          '.&mt('Grade Complete Folder for One Student').'
 8478:         </h2>
 8479:         <div class="LC_grades_select_mode_body">
 8480:           <div class="LC_grade_select_mode_type_body">
 8481:             <div class="LC_grade_select_mode_type">
 8482:               <label>
 8483:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8484: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8485:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8486:               </label>
 8487:             </div>
 8488:             <div class="LC_grade_select_mode_type">
 8489: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8490:             </div>
 8491:           </div>
 8492:         </div>
 8493:       </div>
 8494:     </div>
 8495:   </form>';
 8496:     $result .= &show_grading_menu_form($symb);
 8497:     return $result;
 8498: }
 8499: 
 8500: sub reset_perm {
 8501:     undef(%perm);
 8502: }
 8503: 
 8504: sub init_perm {
 8505:     &reset_perm();
 8506:     foreach my $test_perm ('vgr','mgr','opa') {
 8507: 
 8508: 	my $scope = $env{'request.course.id'};
 8509: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8510: 
 8511: 	    $scope .= '/'.$env{'request.course.sec'};
 8512: 	    if ( $perm{$test_perm}=
 8513: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8514: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8515: 	    } else {
 8516: 		delete($perm{$test_perm});
 8517: 	    }
 8518: 	}
 8519:     }
 8520: }
 8521: 
 8522: sub gather_clicker_ids {
 8523:     my %clicker_ids;
 8524: 
 8525:     my $classlist = &Apache::loncoursedata::get_classlist();
 8526: 
 8527:     # Set up a couple variables.
 8528:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8529:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8530:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8531: 
 8532:     foreach my $student (keys(%$classlist)) {
 8533:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8534:         my $username = $classlist->{$student}->[$username_idx];
 8535:         my $domain   = $classlist->{$student}->[$domain_idx];
 8536:         my $clickers =
 8537: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8538:         foreach my $id (split(/\,/,$clickers)) {
 8539:             $id=~s/^[\#0]+//;
 8540:             $id=~s/[\-\:]//g;
 8541:             if (exists($clicker_ids{$id})) {
 8542: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8543:             } else {
 8544: 		$clicker_ids{$id}=$username.':'.$domain;
 8545:             }
 8546:         }
 8547:     }
 8548:     return %clicker_ids;
 8549: }
 8550: 
 8551: sub gather_adv_clicker_ids {
 8552:     my %clicker_ids;
 8553:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8554:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8555:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8556:     foreach my $element (sort(keys(%coursepersonnel))) {
 8557:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8558:             my ($puname,$pudom)=split(/\:/,$person);
 8559:             my $clickers =
 8560: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8561:             foreach my $id (split(/\,/,$clickers)) {
 8562: 		$id=~s/^[\#0]+//;
 8563:                 $id=~s/[\-\:]//g;
 8564: 		if (exists($clicker_ids{$id})) {
 8565: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8566: 		} else {
 8567: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8568: 		}
 8569:             }
 8570:         }
 8571:     }
 8572:     return %clicker_ids;
 8573: }
 8574: 
 8575: sub clicker_grading_parameters {
 8576:     return ('gradingmechanism' => 'scalar',
 8577:             'upfiletype' => 'scalar',
 8578:             'specificid' => 'scalar',
 8579:             'pcorrect' => 'scalar',
 8580:             'pincorrect' => 'scalar');
 8581: }
 8582: 
 8583: sub process_clicker {
 8584:     my ($r)=@_;
 8585:     my ($symb)=&get_symb($r);
 8586:     if (!$symb) {return '';}
 8587:     my $result=&checkforfile_js();
 8588:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8589:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8590:     $result.=$table;
 8591:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8592:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8593:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8594:         '.</b></td></tr>'."\n";
 8595:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8596: # Attempt to restore parameters from last session, set defaults if not present
 8597:     my %Saveable_Parameters=&clicker_grading_parameters();
 8598:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8599:                                                  \%Saveable_Parameters);
 8600:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8601:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8602:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8603:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8604: 
 8605:     my %checked;
 8606:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8607:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8608:           $checked{$gradingmechanism}="checked='checked'";
 8609:        }
 8610:     }
 8611: 
 8612:     my $upload=&mt("Upload File");
 8613:     my $type=&mt("Type");
 8614:     my $attendance=&mt("Award points just for participation");
 8615:     my $personnel=&mt("Correctness determined from response by course personnel");
 8616:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8617:     my $given=&mt("Correctness determined from given list of answers").' '.
 8618:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8619:     my $pcorrect=&mt("Percentage points for correct solution");
 8620:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8621:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8622: 						   ('iclicker' => 'i>clicker',
 8623:                                                     'interwrite' => 'interwrite PRS'));
 8624:     $symb = &Apache::lonenc::check_encrypt($symb);
 8625:     $result.=<<ENDUPFORM;
 8626: <script type="text/javascript">
 8627: function sanitycheck() {
 8628: // Accept only integer percentages
 8629:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8630:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8631: // Find out grading choice
 8632:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8633:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8634:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8635:       }
 8636:    }
 8637: // By default, new choice equals user selection
 8638:    newgradingchoice=gradingchoice;
 8639: // Not good to give more points for false answers than correct ones
 8640:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8641:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8642:    }
 8643: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8644:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8645:       document.forms.gradesupload.pcorrect.value=100;
 8646:       document.forms.gradesupload.pincorrect.value=100;
 8647:    }
 8648: // If the values are different, cannot be attendance only
 8649:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8650:        (gradingchoice=='attendance')) {
 8651:        newgradingchoice='personnel';
 8652:    }
 8653: // Change grading choice to new one
 8654:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8655:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8656:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8657:       } else {
 8658:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8659:       }
 8660:    }
 8661: // Remember the old state
 8662:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8663: }
 8664: </script>
 8665: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8666: <input type="hidden" name="symb" value="$symb" />
 8667: <input type="hidden" name="command" value="processclickerfile" />
 8668: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8669: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8670: <input type="file" name="upfile" size="50" />
 8671: <br /><label>$type: $selectform</label>
 8672: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8673: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8674: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8675: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8676: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8677: <br />&nbsp;&nbsp;&nbsp;
 8678: <input type="text" name="givenanswer" size="50" />
 8679: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8680: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8681: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8682: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8683: </form>
 8684: ENDUPFORM
 8685:     $result.='</td></tr></table>'."\n".
 8686:              '</td></tr></table><br /><br />'."\n";
 8687:     $result.=&show_grading_menu_form($symb);
 8688:     return $result;
 8689: }
 8690: 
 8691: sub process_clicker_file {
 8692:     my ($r)=@_;
 8693:     my ($symb)=&get_symb($r);
 8694:     if (!$symb) {return '';}
 8695: 
 8696:     my %Saveable_Parameters=&clicker_grading_parameters();
 8697:     &Apache::loncommon::store_course_settings('grades_clicker',
 8698:                                               \%Saveable_Parameters);
 8699: 
 8700:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8701:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8702: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8703: 	return $result.&show_grading_menu_form($symb);
 8704:     }
 8705:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8706:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8707:         return $result.&show_grading_menu_form($symb);
 8708:     }
 8709:     my $foundgiven=0;
 8710:     if ($env{'form.gradingmechanism'} eq 'given') {
 8711:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8712:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8713:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8714:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8715:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8716:         $foundgiven=$#answers+1;
 8717:     }
 8718:     my %clicker_ids=&gather_clicker_ids();
 8719:     my %correct_ids;
 8720:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8721: 	%correct_ids=&gather_adv_clicker_ids();
 8722:     }
 8723:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8724: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8725: 	   $correct_id=~tr/a-z/A-Z/;
 8726: 	   $correct_id=~s/\s//gs;
 8727: 	   $correct_id=~s/^[\#0]+//;
 8728:            $correct_id=~s/[\-\:]//g;
 8729:            if ($correct_id) {
 8730: 	      $correct_ids{$correct_id}='specified';
 8731:            }
 8732:         }
 8733:     }
 8734:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8735: 	$result.=&mt('Score based on attendance only');
 8736:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8737:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8738:     } else {
 8739: 	my $number=0;
 8740: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8741: 	foreach my $id (sort(keys(%correct_ids))) {
 8742: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8743: 	    if ($correct_ids{$id} eq 'specified') {
 8744: 		$result.=&mt('specified');
 8745: 	    } else {
 8746: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8747: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8748: 	    }
 8749: 	    $number++;
 8750: 	}
 8751:         $result.="</p>\n";
 8752: 	if ($number==0) {
 8753: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8754: 	    return $result.&show_grading_menu_form($symb);
 8755: 	}
 8756:     }
 8757:     if (length($env{'form.upfile'}) < 2) {
 8758:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8759: 		     '<span class="LC_error">',
 8760: 		     '</span>',
 8761: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8762:         return $result.&show_grading_menu_form($symb);
 8763:     }
 8764: 
 8765: # Were able to get all the info needed, now analyze the file
 8766: 
 8767:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8768:     $symb = &Apache::lonenc::check_encrypt($symb);
 8769:     my $heading=&mt('Scanning clicker file');
 8770:     $result.=(<<ENDHEADER);
 8771: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8772: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8773: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8774: <form method="post" action="/adm/grades" name="clickeranalysis">
 8775: <input type="hidden" name="symb" value="$symb" />
 8776: <input type="hidden" name="command" value="assignclickergrades" />
 8777: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8778: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8779: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8780: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8781: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8782: ENDHEADER
 8783:     if ($env{'form.gradingmechanism'} eq 'given') {
 8784:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8785:     } 
 8786:     my %responses;
 8787:     my @questiontitles;
 8788:     my $errormsg='';
 8789:     my $number=0;
 8790:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8791: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8792:     }
 8793:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8794:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8795:     }
 8796:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8797:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8798:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8799:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8800:              '<br />';
 8801:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8802:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8803:        return $result.&show_grading_menu_form($symb);
 8804:     } 
 8805: # Remember Question Titles
 8806: # FIXME: Possibly need delimiter other than ":"
 8807:     for (my $i=0;$i<$number;$i++) {
 8808:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8809:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8810:     }
 8811:     my $correct_count=0;
 8812:     my $student_count=0;
 8813:     my $unknown_count=0;
 8814: # Match answers with usernames
 8815: # FIXME: Possibly need delimiter other than ":"
 8816:     foreach my $id (keys(%responses)) {
 8817:        if ($correct_ids{$id}) {
 8818:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8819:           $correct_count++;
 8820:        } elsif ($clicker_ids{$id}) {
 8821:           if ($clicker_ids{$id}=~/\,/) {
 8822: # More than one user with the same clicker!
 8823:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8824:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8825:                            "<select name='multi".$id."'>";
 8826:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8827:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8828:              }
 8829:              $result.='</select>';
 8830:              $unknown_count++;
 8831:           } else {
 8832: # Good: found one and only one user with the right clicker
 8833:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8834:              $student_count++;
 8835:           }
 8836:        } else {
 8837:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8838:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8839:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8840:                    "\n".&mt("Domain").": ".
 8841:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8842:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8843:           $unknown_count++;
 8844:        }
 8845:     }
 8846:     $result.='<hr />'.
 8847:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8848:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8849:        if ($correct_count==0) {
 8850:           $errormsg.="Found no correct answers answers for grading!";
 8851:        } elsif ($correct_count>1) {
 8852:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8853:        }
 8854:     }
 8855:     if ($number<1) {
 8856:        $errormsg.="Found no questions.";
 8857:     }
 8858:     if ($errormsg) {
 8859:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8860:     } else {
 8861:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8862:     }
 8863:     $result.='</form></td></tr></table>'."\n".
 8864:              '</td></tr></table><br /><br />'."\n";
 8865:     return $result.&show_grading_menu_form($symb);
 8866: }
 8867: 
 8868: sub iclicker_eval {
 8869:     my ($questiontitles,$responses)=@_;
 8870:     my $number=0;
 8871:     my $errormsg='';
 8872:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8873:         my %components=&Apache::loncommon::record_sep($line);
 8874:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8875: 	if ($entries[0] eq 'Question') {
 8876: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8877: 		$$questiontitles[$number]=$entries[$i];
 8878: 		$number++;
 8879: 	    }
 8880: 	}
 8881: 	if ($entries[0]=~/^\#/) {
 8882: 	    my $id=$entries[0];
 8883: 	    my @idresponses;
 8884: 	    $id=~s/^[\#0]+//;
 8885: 	    for (my $i=0;$i<$number;$i++) {
 8886: 		my $idx=3+$i*6;
 8887: 		push(@idresponses,$entries[$idx]);
 8888: 	    }
 8889: 	    $$responses{$id}=join(',',@idresponses);
 8890: 	}
 8891:     }
 8892:     return ($errormsg,$number);
 8893: }
 8894: 
 8895: sub interwrite_eval {
 8896:     my ($questiontitles,$responses)=@_;
 8897:     my $number=0;
 8898:     my $errormsg='';
 8899:     my $skipline=1;
 8900:     my $questionnumber=0;
 8901:     my %idresponses=();
 8902:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8903:         my %components=&Apache::loncommon::record_sep($line);
 8904:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8905:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8906:         if ($entries[1] eq 'Response') { $skipline=1; }
 8907:         next if $skipline;
 8908:         if ($entries[0]!=$questionnumber) {
 8909:            $questionnumber=$entries[0];
 8910:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8911:            $number++;
 8912:         }
 8913:         my $id=$entries[4];
 8914:         $id=~s/^[\#0]+//;
 8915:         $id=~s/^v\d*\://i;
 8916:         $id=~s/[\-\:]//g;
 8917:         $idresponses{$id}[$number]=$entries[6];
 8918:     }
 8919:     foreach my $id (keys(%idresponses)) {
 8920:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8921:        $$responses{$id}=~s/^\s*\,//;
 8922:     }
 8923:     return ($errormsg,$number);
 8924: }
 8925: 
 8926: sub assign_clicker_grades {
 8927:     my ($r)=@_;
 8928:     my ($symb)=&get_symb($r);
 8929:     if (!$symb) {return '';}
 8930: # See which part we are saving to
 8931:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8932: # FIXME: This should probably look for the first handgradeable part
 8933:     my $part=$$partlist[0];
 8934: # Start screen output
 8935:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8936: 
 8937:     my $heading=&mt('Assigning grades based on clicker file');
 8938:     $result.=(<<ENDHEADER);
 8939: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8940: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8941: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8942: ENDHEADER
 8943: # Get correct result
 8944: # FIXME: Possibly need delimiter other than ":"
 8945:     my @correct=();
 8946:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8947:     my $number=$env{'form.number'};
 8948:     if ($gradingmechanism ne 'attendance') {
 8949:        foreach my $key (keys(%env)) {
 8950:           if ($key=~/^form\.correct\:/) {
 8951:              my @input=split(/\,/,$env{$key});
 8952:              for (my $i=0;$i<=$#input;$i++) {
 8953:                  if (($correct[$i]) && ($input[$i]) &&
 8954:                      ($correct[$i] ne $input[$i])) {
 8955:                     $result.='<br /><span class="LC_warning">'.
 8956:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8957:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8958:                  } elsif ($input[$i]) {
 8959:                     $correct[$i]=$input[$i];
 8960:                  }
 8961:              }
 8962:           }
 8963:        }
 8964:        for (my $i=0;$i<$number;$i++) {
 8965:           if (!$correct[$i]) {
 8966:              $result.='<br /><span class="LC_error">'.
 8967:                       &mt('No correct result given for question "[_1]"!',
 8968:                           $env{'form.question:'.$i}).'</span>';
 8969:           }
 8970:        }
 8971:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8972:     }
 8973: # Start grading
 8974:     my $pcorrect=$env{'form.pcorrect'};
 8975:     my $pincorrect=$env{'form.pincorrect'};
 8976:     my $storecount=0;
 8977:     foreach my $key (keys(%env)) {
 8978:        my $user='';
 8979:        if ($key=~/^form\.student\:(.*)$/) {
 8980:           $user=$1;
 8981:        }
 8982:        if ($key=~/^form\.unknown\:(.*)$/) {
 8983:           my $id=$1;
 8984:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8985:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8986:           } elsif ($env{'form.multi'.$id}) {
 8987:              $user=$env{'form.multi'.$id};
 8988:           }
 8989:        }
 8990:        if ($user) { 
 8991:           my @answer=split(/\,/,$env{$key});
 8992:           my $sum=0;
 8993:           my $realnumber=$number;
 8994:           for (my $i=0;$i<$number;$i++) {
 8995:              if ($answer[$i]) {
 8996:                 if ($gradingmechanism eq 'attendance') {
 8997:                    $sum+=$pcorrect;
 8998:                 } elsif ($answer[$i] eq '*') {
 8999:                    $sum+=$pcorrect;
 9000:                 } elsif ($answer[$i] eq '-') {
 9001:                    $realnumber--;
 9002:                 } else {
 9003:                    if ($answer[$i] eq $correct[$i]) {
 9004:                       $sum+=$pcorrect;
 9005:                    } else {
 9006:                       $sum+=$pincorrect;
 9007:                    }
 9008:                 }
 9009:              }
 9010:           }
 9011:           my $ave=$sum/(100*$realnumber);
 9012: # Store
 9013:           my ($username,$domain)=split(/\:/,$user);
 9014:           my %grades=();
 9015:           $grades{"resource.$part.solved"}='correct_by_override';
 9016:           $grades{"resource.$part.awarded"}=$ave;
 9017:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9018:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9019:                                                  $env{'request.course.id'},
 9020:                                                  $domain,$username);
 9021:           if ($returncode ne 'ok') {
 9022:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9023:           } else {
 9024:              $storecount++;
 9025:           }
 9026:        }
 9027:     }
 9028: # We are done
 9029:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 9030:              '</td></tr></table>'."\n".
 9031:              '</td></tr></table><br /><br />'."\n";
 9032:     return $result.&show_grading_menu_form($symb);
 9033: }
 9034: 
 9035: sub handler {
 9036:     my $request=$_[0];
 9037:     &reset_caches();
 9038:     if ($env{'browser.mathml'}) {
 9039: 	&Apache::loncommon::content_type($request,'text/xml');
 9040:     } else {
 9041: 	&Apache::loncommon::content_type($request,'text/html');
 9042:     }
 9043:     $request->send_http_header;
 9044:     return '' if $request->header_only;
 9045:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9046:     my $symb=&get_symb($request,1);
 9047:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9048:     my $command=$commands[0];
 9049: 
 9050:     if ($#commands > 0) {
 9051: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9052:     }
 9053: 
 9054:     $ssi_error = 0;
 9055:     $request->print(&Apache::loncommon::start_page('Grading'));
 9056:     if ($symb eq '' && $command eq '') {
 9057: 	if ($env{'user.adv'}) {
 9058: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9059: 		($env{'form.codethree'})) {
 9060: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9061: 		    $env{'form.codethree'};
 9062: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9063: 		    &Apache::lonnet::checkin($token);
 9064: 		if ($tsymb) {
 9065: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9066: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9067: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9068: 					  ('grade_username' => $tuname,
 9069: 					   'grade_domain' => $tudom,
 9070: 					   'grade_courseid' => $tcrsid,
 9071: 					   'grade_symb' => $tsymb)));
 9072: 		    } else {
 9073: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9074: 		    }
 9075: 		} else {
 9076: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9077: 		}
 9078: 	    } else {
 9079: 		$request->print(&Apache::lonxml::tokeninputfield());
 9080: 	    }
 9081: 	}
 9082:     } else {
 9083: 	&init_perm();
 9084: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9085: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9086: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9087: 	    &pickStudentPage($request);
 9088: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9089: 	    &displayPage($request);
 9090: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9091: 	    &updateGradeByPage($request);
 9092: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9093: 	    &processGroup($request);
 9094: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9095: 	    $request->print(&grading_menu($request));
 9096: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9097: 	    $request->print(&submit_options($request));
 9098: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9099: 	    $request->print(&viewgrades($request));
 9100: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9101: 	    $request->print(&processHandGrade($request));
 9102: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9103: 	    $request->print(&editgrades($request));
 9104: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9105: 	    $request->print(&verifyreceipt($request));
 9106:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9107:             $request->print(&process_clicker($request));
 9108:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9109:             $request->print(&process_clicker_file($request));
 9110:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9111:             $request->print(&assign_clicker_grades($request));
 9112: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9113: 	    $request->print(&upcsvScores_form($request));
 9114: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9115: 	    $request->print(&csvupload($request));
 9116: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9117: 	    $request->print(&csvuploadmap($request));
 9118: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9119: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9120: 		$request->print(&csvuploadoptions($request));
 9121: 	    } else {
 9122: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9123: 		    $env{'form.upfile_associate'} = 'reverse';
 9124: 		} else {
 9125: 		    $env{'form.upfile_associate'} = 'forward';
 9126: 		}
 9127: 		$request->print(&csvuploadmap($request));
 9128: 	    }
 9129: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9130: 	    $request->print(&csvuploadassign($request));
 9131: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9132: 	    $request->print(&scantron_selectphase($request));
 9133:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9134:  	    $request->print(&scantron_do_warning($request));
 9135: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9136: 	    $request->print(&scantron_validate_file($request));
 9137: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9138: 	    $request->print(&scantron_process_students($request));
 9139:  	} elsif ($command eq 'scantronupload' && 
 9140:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9141: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9142:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9143:  	} elsif ($command eq 'scantronupload_save' &&
 9144:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9145: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9146:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9147:  	} elsif ($command eq 'scantron_download' &&
 9148: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9149:  	    $request->print(&scantron_download_scantron_data($request));
 9150:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9151:             $request->print(&checkscantron_results($request));     
 9152: 	} elsif ($command) {
 9153: 	    $request->print("Access Denied ($command)");
 9154: 	}
 9155:     }
 9156:     if ($ssi_error) {
 9157: 	&ssi_print_error($request);
 9158:     }
 9159:     $request->print(&Apache::loncommon::end_page());
 9160:     &reset_caches();
 9161:     return '';
 9162: }
 9163: 
 9164: 1;
 9165: 
 9166: __END__;

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