File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.528.2.6: download - view: text, annotated - select for diffs
Wed Dec 31 21:08:09 2008 UTC (15 years, 10 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.528: preferred, unified
- Backport 1.545.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.528.2.6 2008/12/31 21:08:09 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 virusses').'</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: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6221: <input type="hidden" name="command" value="scantron_process" />
 6222: ');
 6223: 
 6224:     } else {
 6225: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6226: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6227:     }
 6228:     if ($stop) {
 6229: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6230: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6231: 	    $r->print(' '.&mt('this error').' <br />');
 6232: 
 6233: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6234: 	} else {
 6235:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6236: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6237:             } else {
 6238:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6239:             }
 6240: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6241: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6242: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6243: 	}
 6244:     }
 6245:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6246:     return '';
 6247: }
 6248: 
 6249: 
 6250: =pod
 6251: 
 6252: =item scantron_remove_file
 6253: 
 6254:    Removes the requested bubble sheet data file, makes sure that
 6255:    scantron_original_<filename> is never removed
 6256: 
 6257: 
 6258: =cut
 6259: 
 6260: sub scantron_remove_file {
 6261:     my ($which)=@_;
 6262:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6263:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6264:     my $file='scantron_';
 6265:     if ($which eq 'corrected' || $which eq 'skipped') {
 6266: 	$file.=$which.'_';
 6267:     } else {
 6268: 	return 'refused';
 6269:     }
 6270:     $file.=$env{'form.scantron_selectfile'};
 6271:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6272: }
 6273: 
 6274: 
 6275: =pod
 6276: 
 6277: =item scantron_remove_scan_data
 6278: 
 6279:    Removes all scan_data correction for the requested bubble sheet
 6280:    data file.  (In the case that both the are doing skipped records we need
 6281:    to remember the old skipped lines for the time being so that element
 6282:    persists for a while.)
 6283: 
 6284: =cut
 6285: 
 6286: sub scantron_remove_scan_data {
 6287:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6288:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6289:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6290:     my @todelete;
 6291:     my $filename=$env{'form.scantron_selectfile'};
 6292:     foreach my $key (@keys) {
 6293: 	if ($key=~/^\Q$filename\E_/) {
 6294: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6295: 		$key=~/remember_skipping/) {
 6296: 		next;
 6297: 	    }
 6298: 	    push(@todelete,$key);
 6299: 	}
 6300:     }
 6301:     my $result;
 6302:     if (@todelete) {
 6303: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6304: 				       \@todelete,$cdom,$cname);
 6305:     } else {
 6306: 	$result = 'ok';
 6307:     }
 6308:     return $result;
 6309: }
 6310: 
 6311: 
 6312: =pod
 6313: 
 6314: =item scantron_getfile
 6315: 
 6316:     Fetches the requested bubble sheet data file (all 3 versions), and
 6317:     the scan_data hash
 6318:   
 6319:   Arguments:
 6320:     None
 6321: 
 6322:   Returns:
 6323:     2 hash references
 6324: 
 6325:      - first one has 
 6326:          orig      -
 6327:          corrected -
 6328:          skipped   -  each of which points to an array ref of the specified
 6329:                       file broken up into individual lines
 6330:          count     - number of scanlines
 6331:  
 6332:      - second is the scan_data hash possible keys are
 6333:        ($number refers to scanline numbered $number and thus the key affects
 6334:         only that scanline
 6335:         $bubline refers to the specific bubble line element and the aspects
 6336:         refers to that specific bubble line element)
 6337: 
 6338:        $number.user - username:domain to use
 6339:        $number.CODE_ignore_dup 
 6340:                     - ignore the duplicate CODE error 
 6341:        $number.useCODE
 6342:                     - use the CODE in the scanline as is
 6343:        $number.no_bubble.$bubline
 6344:                     - it is valid that there is no bubbled in bubble
 6345:                       at $number $bubline
 6346:        remember_skipping
 6347:                     - a frozen hash containing keys of $number and values
 6348:                       of either 
 6349:                         1 - we are on a 'do skipped records pass' and plan
 6350:                             on processing this line
 6351:                         2 - we are on a 'do skipped records pass' and this
 6352:                             scanline has been marked to skip yet again
 6353: 
 6354: =cut
 6355: 
 6356: sub scantron_getfile {
 6357:     #FIXME really would prefer a scantron directory
 6358:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6359:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6360:     my $lines;
 6361:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6362: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6363:     my %scanlines;
 6364:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6365:     my $temp=$scanlines{'orig'};
 6366:     $scanlines{'count'}=$#$temp;
 6367: 
 6368:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6369: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6370:     if ($lines eq '-1') {
 6371: 	$scanlines{'corrected'}=[];
 6372:     } else {
 6373: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6374:     }
 6375:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6376: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6377:     if ($lines eq '-1') {
 6378: 	$scanlines{'skipped'}=[];
 6379:     } else {
 6380: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6381:     }
 6382:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6383:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6384:     my %scan_data = @tmp;
 6385:     return (\%scanlines,\%scan_data);
 6386: }
 6387: 
 6388: =pod
 6389: 
 6390: =item lonnet_putfile
 6391: 
 6392:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6393: 
 6394:  Arguments:
 6395:    $contents - data to store
 6396:    $filename - filename to store $contents into
 6397: 
 6398:  Returns:
 6399:    result value from &Apache::lonnet::finishuserfileupload
 6400: 
 6401: =cut
 6402: 
 6403: sub lonnet_putfile {
 6404:     my ($contents,$filename)=@_;
 6405:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6406:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6407:     $env{'form.sillywaytopassafilearound'}=$contents;
 6408:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6409: 
 6410: }
 6411: 
 6412: =pod
 6413: 
 6414: =item scantron_putfile
 6415: 
 6416:     Stores the current version of the bubble sheet data files, and the
 6417:     scan_data hash. (Does not modify the original version only the
 6418:     corrected and skipped versions.
 6419: 
 6420:  Arguments:
 6421:     $scanlines - hash ref that looks like the first return value from
 6422:                  &scantron_getfile()
 6423:     $scan_data - hash ref that looks like the second return value from
 6424:                  &scantron_getfile()
 6425: 
 6426: =cut
 6427: 
 6428: sub scantron_putfile {
 6429:     my ($scanlines,$scan_data) = @_;
 6430:     #FIXME really would prefer a scantron directory
 6431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6433:     if ($scanlines) {
 6434: 	my $prefix='scantron_';
 6435: # no need to update orig, shouldn't change
 6436: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6437: #		    $env{'form.scantron_selectfile'});
 6438: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6439: 			$prefix.'corrected_'.
 6440: 			$env{'form.scantron_selectfile'});
 6441: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6442: 			$prefix.'skipped_'.
 6443: 			$env{'form.scantron_selectfile'});
 6444:     }
 6445:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6446: }
 6447: 
 6448: =pod
 6449: 
 6450: =item scantron_get_line
 6451: 
 6452:    Returns the correct version of the scanline
 6453: 
 6454:  Arguments:
 6455:     $scanlines - hash ref that looks like the first return value from
 6456:                  &scantron_getfile()
 6457:     $scan_data - hash ref that looks like the second return value from
 6458:                  &scantron_getfile()
 6459:     $i         - number of the requested line (starts at 0)
 6460: 
 6461:  Returns:
 6462:    A scanline, (either the original or the corrected one if it
 6463:    exists), or undef if the requested scanline should be
 6464:    skipped. (Either because it's an skipped scanline, or it's an
 6465:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6466:    pass.
 6467: 
 6468: =cut
 6469: 
 6470: sub scantron_get_line {
 6471:     my ($scanlines,$scan_data,$i)=@_;
 6472:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6473:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6474:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6475:     return $scanlines->{'orig'}[$i]; 
 6476: }
 6477: 
 6478: =pod
 6479: 
 6480: =item scantron_todo_count
 6481: 
 6482:     Counts the number of scanlines that need processing.
 6483: 
 6484:  Arguments:
 6485:     $scanlines - hash ref that looks like the first return value from
 6486:                  &scantron_getfile()
 6487:     $scan_data - hash ref that looks like the second return value from
 6488:                  &scantron_getfile()
 6489: 
 6490:  Returns:
 6491:     $count - number of scanlines to process
 6492: 
 6493: =cut
 6494: 
 6495: sub get_todo_count {
 6496:     my ($scanlines,$scan_data)=@_;
 6497:     my $count=0;
 6498:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6499: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6500: 	if ($line=~/^[\s\cz]*$/) { next; }
 6501: 	$count++;
 6502:     }
 6503:     return $count;
 6504: }
 6505: 
 6506: =pod
 6507: 
 6508: =item scantron_put_line
 6509: 
 6510:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6511:     data file.
 6512: 
 6513:  Arguments:
 6514:     $scanlines - hash ref that looks like the first return value from
 6515:                  &scantron_getfile()
 6516:     $scan_data - hash ref that looks like the second return value from
 6517:                  &scantron_getfile()
 6518:     $i         - line number to update
 6519:     $newline   - contents of the updated scanline
 6520:     $skip      - if true make the line for skipping and update the
 6521:                  'skipped' file
 6522: 
 6523: =cut
 6524: 
 6525: sub scantron_put_line {
 6526:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6527:     if ($skip) {
 6528: 	$scanlines->{'skipped'}[$i]=$newline;
 6529: 	&start_skipping($scan_data,$i);
 6530: 	return;
 6531:     }
 6532:     $scanlines->{'corrected'}[$i]=$newline;
 6533: }
 6534: 
 6535: =pod
 6536: 
 6537: =item scantron_clear_skip
 6538: 
 6539:    Remove a line from the 'skipped' file
 6540: 
 6541:  Arguments:
 6542:     $scanlines - hash ref that looks like the first return value from
 6543:                  &scantron_getfile()
 6544:     $scan_data - hash ref that looks like the second return value from
 6545:                  &scantron_getfile()
 6546:     $i         - line number to update
 6547: 
 6548: =cut
 6549: 
 6550: sub scantron_clear_skip {
 6551:     my ($scanlines,$scan_data,$i)=@_;
 6552:     if (exists($scanlines->{'skipped'}[$i])) {
 6553: 	undef($scanlines->{'skipped'}[$i]);
 6554: 	return 1;
 6555:     }
 6556:     return 0;
 6557: }
 6558: 
 6559: =pod
 6560: 
 6561: =item scantron_filter_not_exam
 6562: 
 6563:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6564:    filter out resources that are not marked as 'exam' mode
 6565: 
 6566: =cut
 6567: 
 6568: sub scantron_filter_not_exam {
 6569:     my ($curres)=@_;
 6570:     
 6571:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6572: 	# if the user has asked to not have either hidden
 6573: 	# or 'randomout' controlled resources to be graded
 6574: 	# don't include them
 6575: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6576: 	    && $curres->randomout) {
 6577: 	    return 0;
 6578: 	}
 6579: 	return 1;
 6580:     }
 6581:     return 0;
 6582: }
 6583: 
 6584: =pod
 6585: 
 6586: =item scantron_validate_sequence
 6587: 
 6588:     Validates the selected sequence, checking for resource that are
 6589:     not set to exam mode.
 6590: 
 6591: =cut
 6592: 
 6593: sub scantron_validate_sequence {
 6594:     my ($r,$currentphase) = @_;
 6595: 
 6596:     my $navmap=Apache::lonnavmaps::navmap->new();
 6597:     my (undef,undef,$sequence)=
 6598: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6599: 
 6600:     my $map=$navmap->getResourceByUrl($sequence);
 6601: 
 6602:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6603:                                     value="ignore" />');
 6604:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6605: 	my @resources=
 6606: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6607: 	if (@resources) {
 6608: 	    $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>");
 6609: 	    return (1,$currentphase);
 6610: 	}
 6611:     }
 6612: 
 6613:     return (0,$currentphase+1);
 6614: }
 6615: 
 6616: =pod
 6617: 
 6618: =item scantron_validate_ID
 6619: 
 6620:    Validates all scanlines in the selected file to not have any
 6621:    invalid or underspecified student IDs
 6622: 
 6623: =cut
 6624: 
 6625: sub scantron_validate_ID {
 6626:     my ($r,$currentphase) = @_;
 6627:     
 6628:     #get student info
 6629:     my $classlist=&Apache::loncoursedata::get_classlist();
 6630:     my %idmap=&username_to_idmap($classlist);
 6631: 
 6632:     #get scantron line setup
 6633:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6634:     my ($scanlines,$scan_data)=&scantron_getfile();
 6635:     
 6636:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6637: 
 6638:     my %found=('ids'=>{},'usernames'=>{});
 6639:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6640: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6641: 	if ($line=~/^[\s\cz]*$/) { next; }
 6642: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6643: 						 $scan_data);
 6644: 	my $id=$$scan_record{'scantron.ID'};
 6645: 	my $found;
 6646: 	foreach my $checkid (keys(%idmap)) {
 6647: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6648: 	}
 6649: 	if ($found) {
 6650: 	    my $username=$idmap{$found};
 6651: 	    if ($found{'ids'}{$found}) {
 6652: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6653: 					 $line,'duplicateID',$found);
 6654: 		return(1,$currentphase);
 6655: 	    } elsif ($found{'usernames'}{$username}) {
 6656: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6657: 					 $line,'duplicateID',$username);
 6658: 		return(1,$currentphase);
 6659: 	    }
 6660: 	    #FIXME store away line we previously saw the ID on to use above
 6661: 	    $found{'ids'}{$found}++;
 6662: 	    $found{'usernames'}{$username}++;
 6663: 	} else {
 6664: 	    if ($id =~ /^\s*$/) {
 6665: 		my $username=&scan_data($scan_data,"$i.user");
 6666: 		if (defined($username) && $found{'usernames'}{$username}) {
 6667: 		    &scantron_get_correction($r,$i,$scan_record,
 6668: 					     \%scantron_config,
 6669: 					     $line,'duplicateID',$username);
 6670: 		    return(1,$currentphase);
 6671: 		} elsif (!defined($username)) {
 6672: 		    &scantron_get_correction($r,$i,$scan_record,
 6673: 					     \%scantron_config,
 6674: 					     $line,'incorrectID');
 6675: 		    return(1,$currentphase);
 6676: 		}
 6677: 		$found{'usernames'}{$username}++;
 6678: 	    } else {
 6679: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6680: 					 $line,'incorrectID');
 6681: 		return(1,$currentphase);
 6682: 	    }
 6683: 	}
 6684:     }
 6685: 
 6686:     return (0,$currentphase+1);
 6687: }
 6688: 
 6689: =pod
 6690: 
 6691: =item scantron_get_correction
 6692: 
 6693:    Builds the interface screen to interact with the operator to fix a
 6694:    specific error condition in a specific scanline
 6695: 
 6696:  Arguments:
 6697:     $r           - Apache request object
 6698:     $i           - number of the current scanline
 6699:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6700:     $scan_config - hash ref as returned from &get_scantron_config()
 6701:     $line        - full contents of the current scanline
 6702:     $error       - error condition, valid values are
 6703:                    'incorrectCODE', 'duplicateCODE',
 6704:                    'doublebubble', 'missingbubble',
 6705:                    'duplicateID', 'incorrectID'
 6706:     $arg         - extra information needed
 6707:        For errors:
 6708:          - duplicateID   - paper number that this studentID was seen before on
 6709:          - duplicateCODE - array ref of the paper numbers this CODE was
 6710:                            seen on before
 6711:          - incorrectCODE - current incorrect CODE 
 6712:          - doublebubble  - array ref of the bubble lines that have double
 6713:                            bubble errors
 6714:          - missingbubble - array ref of the bubble lines that have missing
 6715:                            bubble errors
 6716: 
 6717: =cut
 6718: 
 6719: sub scantron_get_correction {
 6720:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6721: #FIXME in the case of a duplicated ID the previous line, probably need
 6722: #to show both the current line and the previous one and allow skipping
 6723: #the previous one or the current one
 6724: 
 6725:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6726: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6727: 			    " for PaperID <tt>[_1]</tt>",
 6728: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6729:     } else {
 6730: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6731: 			    " in scanline [_1] <pre>[_2]</pre>",
 6732: 			    $i,$line)."</p> \n");
 6733:     }
 6734:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6735: 			  "The name on the paper is [_2],[_3]",
 6736: 			  $$scan_record{'scantron.ID'},
 6737: 			  $$scan_record{'scantron.LastName'},
 6738: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6739: 
 6740:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6741:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6742:                            # Array populated for doublebubble or
 6743:     my @lines_to_correct;  # missingbubble errors to build javascript
 6744:                            # to validate radio button checking   
 6745: 
 6746:     if ($error =~ /ID$/) {
 6747: 	if ($error eq 'incorrectID') {
 6748: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6749: 		      "</p>\n");
 6750: 	} elsif ($error eq 'duplicateID') {
 6751: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6752: 	}
 6753: 	$r->print($message);
 6754: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6755: 	$r->print("\n<ul><li> ");
 6756: 	#FIXME it would be nice if this sent back the user ID and
 6757: 	#could do partial userID matches
 6758: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6759: 				       'scantron_username','scantron_domain'));
 6760: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6761: 	$r->print("\n@".
 6762: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6763: 
 6764: 	$r->print('</li>');
 6765:     } elsif ($error =~ /CODE$/) {
 6766: 	if ($error eq 'incorrectCODE') {
 6767: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6768: 	} elsif ($error eq 'duplicateCODE') {
 6769: 	    $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");
 6770: 	}
 6771: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6772: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6773: 	$r->print($message);
 6774: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6775: 	$r->print("\n<br /> ");
 6776: 	my $i=0;
 6777: 	if ($error eq 'incorrectCODE' 
 6778: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6779: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6780: 	    if ($closest > 0) {
 6781: 		foreach my $testcode (@{$closest}) {
 6782: 		    my $checked='';
 6783: 		    if (!$i) { $checked=' checked="checked" '; }
 6784: 		    $r->print("
 6785:    <label>
 6786:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6787:        ".&mt("Use the similar CODE [_1] instead.",
 6788: 	    "<b><tt>".$testcode."</tt></b>")."
 6789:     </label>
 6790:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6791: 		    $r->print("\n<br />");
 6792: 		    $i++;
 6793: 		}
 6794: 	    }
 6795: 	}
 6796: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6797: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6798: 	    $r->print("
 6799:     <label>
 6800:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6801:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6802: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6803:     </label>");
 6804: 	    $r->print("\n<br />");
 6805: 	}
 6806: 
 6807: 	$r->print(<<ENDSCRIPT);
 6808: <script type="text/javascript">
 6809: function change_radio(field) {
 6810:     var slct=document.scantronupload.scantron_CODE_resolution;
 6811:     var i;
 6812:     for (i=0;i<slct.length;i++) {
 6813:         if (slct[i].value==field) { slct[i].checked=true; }
 6814:     }
 6815: }
 6816: </script>
 6817: ENDSCRIPT
 6818: 	my $href="/adm/pickcode?".
 6819: 	   "form=".&escape("scantronupload").
 6820: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6821: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6822: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6823: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6824: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6825: 	    $r->print("
 6826:     <label>
 6827:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6828:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6829: 	     "<a target='_blank' href='$href'>","</a>")."
 6830:     </label> 
 6831:     ".&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')\" />"));
 6832: 	    $r->print("\n<br />");
 6833: 	}
 6834: 	$r->print("
 6835:     <label>
 6836:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6837:        ".&mt("Use [_1] as the CODE.",
 6838: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6839: 	$r->print("\n<br /><br />");
 6840:     } elsif ($error eq 'doublebubble') {
 6841: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6842: 
 6843: 	# The form field scantron_questions is acutally a list of line numbers.
 6844: 	# represented by this form so:
 6845: 
 6846: 	my $line_list = &questions_to_line_list($arg);
 6847: 
 6848: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6849: 		  $line_list.'" />');
 6850: 	$r->print($message);
 6851: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6852: 	foreach my $question (@{$arg}) {
 6853: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6854:                                                    $scan_record, $error);
 6855:             push(@lines_to_correct,@linenums);
 6856: 	}
 6857:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6858:     } elsif ($error eq 'missingbubble') {
 6859: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6860: 	$r->print($message);
 6861: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6862: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6863: 
 6864: 	# The form field scantron_questions is actually a list of line numbers not
 6865: 	# a list of question numbers. Therefore:
 6866: 	#
 6867: 	
 6868: 	my $line_list = &questions_to_line_list($arg);
 6869: 
 6870: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6871: 		  $line_list.'" />');
 6872: 	foreach my $question (@{$arg}) {
 6873: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6874:                                                    $scan_record, $error);
 6875:             push(@lines_to_correct,@linenums);
 6876: 	}
 6877:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6878:     } else {
 6879: 	$r->print("\n<ul>");
 6880:     }
 6881:     $r->print("\n</li></ul>");
 6882: }
 6883: 
 6884: sub verify_bubbles_checked {
 6885:     my (@ansnums) = @_;
 6886:     my $ansnumstr = join('","',@ansnums);
 6887:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6888:     my $output = (<<ENDSCRIPT);
 6889: <script type="text/javascript">
 6890: function verify_bubble_radio(form) {
 6891:     var ansnumArray = new Array ("$ansnumstr");
 6892:     var need_bubble_count = 0;
 6893:     for (var i=0; i<ansnumArray.length; i++) {
 6894:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6895:             var bubble_picked = 0; 
 6896:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6897:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6898:                     bubble_picked = 1;
 6899:                 }
 6900:             }
 6901:             if (bubble_picked == 0) {
 6902:                 need_bubble_count ++;
 6903:             }
 6904:         }
 6905:     }
 6906:     if (need_bubble_count) {
 6907:         alert("$warning");
 6908:         return;
 6909:     }
 6910:     form.submit(); 
 6911: }
 6912: </script>
 6913: ENDSCRIPT
 6914:     return $output;
 6915: }
 6916: 
 6917: =pod
 6918: 
 6919: =item  questions_to_line_list
 6920: 
 6921: Converts a list of questions into a string of comma separated
 6922: line numbers in the answer sheet used by the questions.  This is
 6923: used to fill in the scantron_questions form field.
 6924: 
 6925:   Arguments:
 6926:      questions    - Reference to an array of questions.
 6927: 
 6928: =cut
 6929: 
 6930: 
 6931: sub questions_to_line_list {
 6932:     my ($questions) = @_;
 6933:     my @lines;
 6934: 
 6935:     foreach my $item (@{$questions}) {
 6936:         my $question = $item;
 6937:         my ($first,$count,$last);
 6938:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6939:             $question = $1;
 6940:             my $subquestion = $2;
 6941:             $first = $first_bubble_line{$question-1} + 1;
 6942:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6943:             my $subcount = 1;
 6944:             while ($subcount<$subquestion) {
 6945:                 $first += $subans[$subcount-1];
 6946:                 $subcount ++;
 6947:             }
 6948:             $count = $subans[$subquestion-1];
 6949:         } else {
 6950: 	    $first   = $first_bubble_line{$question-1} + 1;
 6951: 	    $count   = $bubble_lines_per_response{$question-1};
 6952:         }
 6953:         $last = $first+$count-1;
 6954:         push(@lines, ($first..$last));
 6955:     }
 6956:     return join(',', @lines);
 6957: }
 6958: 
 6959: =pod 
 6960: 
 6961: =item prompt_for_corrections
 6962: 
 6963: Prompts for a potentially multiline correction to the
 6964: user's bubbling (factors out common code from scantron_get_correction
 6965: for multi and missing bubble cases).
 6966: 
 6967:  Arguments:
 6968:    $r           - Apache request object.
 6969:    $question    - The question number to prompt for.
 6970:    $scan_config - The scantron file configuration hash.
 6971:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6972:    $error       - Type of error
 6973: 
 6974:  Implicit inputs:
 6975:    %bubble_lines_per_response   - Starting line numbers for each question.
 6976:                                   Numbered from 0 (but question numbers are from
 6977:                                   1.
 6978:    %first_bubble_line           - Starting bubble line for each question.
 6979:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6980:                                   type problems render as separate sub-questions, 
 6981:                                   in exam mode. This hash contains a 
 6982:                                   comma-separated list of the lines per 
 6983:                                   sub-question.
 6984:    %responsetype_per_response   - essayresponse, formularesponse,
 6985:                                   stringresponse, imageresponse, reactionresponse,
 6986:                                   and organicresponse type problem parts can have
 6987:                                   multiple lines per response if the weight
 6988:                                   assigned exceeds 10.  In this case, only
 6989:                                   one bubble per line is permitted, but more 
 6990:                                   than one line might contain bubbles, e.g.
 6991:                                   bubbling of: line 1 - J, line 2 - J, 
 6992:                                   line 3 - B would assign 22 points.  
 6993: 
 6994: =cut
 6995: 
 6996: sub prompt_for_corrections {
 6997:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6998:     my ($current_line,$lines);
 6999:     my @linenums;
 7000:     my $questionnum = $question;
 7001:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7002:         $question = $1;
 7003:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7004:         my $subquestion = $2;
 7005:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7006:         my $subcount = 1;
 7007:         while ($subcount<$subquestion) {
 7008:             $current_line += $subans[$subcount-1];
 7009:             $subcount ++;
 7010:         }
 7011:         $lines = $subans[$subquestion-1];
 7012:     } else {
 7013:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7014:         $lines        = $bubble_lines_per_response{$question-1};
 7015:     }
 7016:     if ($lines > 1) {
 7017:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7018:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7019:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7020:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7021:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7022:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7023:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7024:             $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 />');
 7025:         } else {
 7026:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7027:         }
 7028:     }
 7029:     for (my $i =0; $i < $lines; $i++) {
 7030:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7031: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7032: 	        		  $questionnum,$error,split('', $selected));
 7033:         push(@linenums,$current_line);
 7034: 	$current_line++;
 7035:     }
 7036:     if ($lines > 1) {
 7037: 	$r->print("<hr /><br />");
 7038:     }
 7039:     return @linenums;
 7040: }
 7041: 
 7042: =pod
 7043: 
 7044: =item scantron_bubble_selector
 7045:   
 7046:    Generates the html radiobuttons to correct a single bubble line
 7047:    possibly showing the existing the selected bubbles if known
 7048: 
 7049:  Arguments:
 7050:     $r           - Apache request object
 7051:     $scan_config - hash from &get_scantron_config()
 7052:     $line        - Number of the line being displayed.
 7053:     $questionnum - Question number (may include subquestion)
 7054:     $error       - Type of error.
 7055:     @selected    - Array of bubbles picked on this line.
 7056: 
 7057: =cut
 7058: 
 7059: sub scantron_bubble_selector {
 7060:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7061:     my $max=$$scan_config{'Qlength'};
 7062: 
 7063:     my $scmode=$$scan_config{'Qon'};
 7064:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7065: 
 7066:     my @alphabet=('A'..'Z');
 7067:     $r->print(&Apache::loncommon::start_data_table().
 7068:               &Apache::loncommon::start_data_table_row());
 7069:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7070:     for (my $i=0;$i<$max+1;$i++) {
 7071: 	$r->print("\n".'<td align="center">');
 7072: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7073: 	else { $r->print('&nbsp;'); }
 7074: 	$r->print('</td>');
 7075:     }
 7076:     $r->print(&Apache::loncommon::end_data_table_row().
 7077:               &Apache::loncommon::start_data_table_row());
 7078:     for (my $i=0;$i<$max;$i++) {
 7079: 	$r->print("\n".
 7080: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7081: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7082:     }
 7083:     my $nobub_checked = ' ';
 7084:     if ($error eq 'missingbubble') {
 7085:         $nobub_checked = ' checked = "checked" ';
 7086:     }
 7087:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7088: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7089:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7090:               $line.'" value="'.$questionnum.'" /></td>');
 7091:     $r->print(&Apache::loncommon::end_data_table_row().
 7092:               &Apache::loncommon::end_data_table());
 7093: }
 7094: 
 7095: =pod
 7096: 
 7097: =item num_matches
 7098: 
 7099:    Counts the number of characters that are the same between the two arguments.
 7100: 
 7101:  Arguments:
 7102:    $orig - CODE from the scanline
 7103:    $code - CODE to match against
 7104: 
 7105:  Returns:
 7106:    $count - integer count of the number of same characters between the
 7107:             two arguments
 7108: 
 7109: =cut
 7110: 
 7111: sub num_matches {
 7112:     my ($orig,$code) = @_;
 7113:     my @code=split(//,$code);
 7114:     my @orig=split(//,$orig);
 7115:     my $same=0;
 7116:     for (my $i=0;$i<scalar(@code);$i++) {
 7117: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7118:     }
 7119:     return $same;
 7120: }
 7121: 
 7122: =pod
 7123: 
 7124: =item scantron_get_closely_matching_CODEs
 7125: 
 7126:    Cycles through all CODEs and finds the set that has the greatest
 7127:    number of same characters as the provided CODE
 7128: 
 7129:  Arguments:
 7130:    $allcodes - hash ref returned by &get_codes()
 7131:    $CODE     - CODE from the current scanline
 7132: 
 7133:  Returns:
 7134:    2 element list
 7135:     - first elements is number of how closely matching the best fit is 
 7136:       (5 means best set has 5 matching characters)
 7137:     - second element is an arrary ref containing the set of valid CODEs
 7138:       that best fit the passed in CODE
 7139: 
 7140: =cut
 7141: 
 7142: sub scantron_get_closely_matching_CODEs {
 7143:     my ($allcodes,$CODE)=@_;
 7144:     my @CODEs;
 7145:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7146: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7147:     }
 7148: 
 7149:     return ($#CODEs,$CODEs[-1]);
 7150: }
 7151: 
 7152: =pod
 7153: 
 7154: =item get_codes
 7155: 
 7156:    Builds a hash which has keys of all of the valid CODEs from the selected
 7157:    set of remembered CODEs.
 7158: 
 7159:  Arguments:
 7160:   $old_name - name of the set of remembered CODEs
 7161:   $cdom     - domain of the course
 7162:   $cnum     - internal course name
 7163: 
 7164:  Returns:
 7165:   %allcodes - keys are the valid CODEs, values are all 1
 7166: 
 7167: =cut
 7168: 
 7169: sub get_codes {
 7170:     my ($old_name, $cdom, $cnum) = @_;
 7171:     if (!$old_name) {
 7172: 	$old_name=$env{'form.scantron_CODElist'};
 7173:     }
 7174:     if (!$cdom) {
 7175: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7176:     }
 7177:     if (!$cnum) {
 7178: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7179:     }
 7180:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7181: 				    $cdom,$cnum);
 7182:     my %allcodes;
 7183:     if ($result{"type\0$old_name"} eq 'number') {
 7184: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7185:     } else {
 7186: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7187:     }
 7188:     return %allcodes;
 7189: }
 7190: 
 7191: =pod
 7192: 
 7193: =item scantron_validate_CODE
 7194: 
 7195:    Validates all scanlines in the selected file to not have any
 7196:    invalid or underspecified CODEs and that none of the codes are
 7197:    duplicated if this was requested.
 7198: 
 7199: =cut
 7200: 
 7201: sub scantron_validate_CODE {
 7202:     my ($r,$currentphase) = @_;
 7203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7204:     if ($scantron_config{'CODElocation'} &&
 7205: 	$scantron_config{'CODEstart'} &&
 7206: 	$scantron_config{'CODElength'}) {
 7207: 	if (!defined($env{'form.scantron_CODElist'})) {
 7208: 	    &FIXME_blow_up()
 7209: 	}
 7210:     } else {
 7211: 	return (0,$currentphase+1);
 7212:     }
 7213:     
 7214:     my %usedCODEs;
 7215: 
 7216:     my %allcodes=&get_codes();
 7217: 
 7218:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7219: 
 7220:     my ($scanlines,$scan_data)=&scantron_getfile();
 7221:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7222: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7223: 	if ($line=~/^[\s\cz]*$/) { next; }
 7224: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7225: 						 $scan_data);
 7226: 	my $CODE=$$scan_record{'scantron.CODE'};
 7227: 	my $error=0;
 7228: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7229: 	    &scantron_get_correction($r,$i,$scan_record,
 7230: 				     \%scantron_config,
 7231: 				     $line,'incorrectCODE',\%allcodes);
 7232: 	    return(1,$currentphase);
 7233: 	}
 7234: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7235: 	    && !$$scan_record{'scantron.useCODE'}) {
 7236: 	    &scantron_get_correction($r,$i,$scan_record,
 7237: 				     \%scantron_config,
 7238: 				     $line,'incorrectCODE',\%allcodes);
 7239: 	    return(1,$currentphase);
 7240: 	}
 7241: 	if (exists($usedCODEs{$CODE}) 
 7242: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7243: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7244: 	    &scantron_get_correction($r,$i,$scan_record,
 7245: 				     \%scantron_config,
 7246: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7247: 	    return(1,$currentphase);
 7248: 	}
 7249: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7250:     }
 7251:     return (0,$currentphase+1);
 7252: }
 7253: 
 7254: =pod
 7255: 
 7256: =item scantron_validate_doublebubble
 7257: 
 7258:    Validates all scanlines in the selected file to not have any
 7259:    bubble lines with multiple bubbles marked.
 7260: 
 7261: =cut
 7262: 
 7263: sub scantron_validate_doublebubble {
 7264:     my ($r,$currentphase) = @_;
 7265:     #get student info
 7266:     my $classlist=&Apache::loncoursedata::get_classlist();
 7267:     my %idmap=&username_to_idmap($classlist);
 7268: 
 7269:     #get scantron line setup
 7270:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7271:     my ($scanlines,$scan_data)=&scantron_getfile();
 7272:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7273: 
 7274:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7275: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7276: 	if ($line=~/^[\s\cz]*$/) { next; }
 7277: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7278: 						 $scan_data);
 7279: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7280: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7281: 				 'doublebubble',
 7282: 				 $$scan_record{'scantron.doubleerror'});
 7283:     	return (1,$currentphase);
 7284:     }
 7285:     return (0,$currentphase+1);
 7286: }
 7287: 
 7288: =pod
 7289: 
 7290: =item scantron_get_maxbubble
 7291: 
 7292:    Returns the maximum number of bubble lines that are expected to
 7293:    occur. Does this by walking the selected sequence rendering the
 7294:    resource and then checking &Apache::lonxml::get_problem_counter()
 7295:    for what the current value of the problem counter is.
 7296: 
 7297:    Caches the results to $env{'form.scantron_maxbubble'},
 7298:    $env{'form.scantron.bubble_lines.n'}, 
 7299:    $env{'form.scantron.first_bubble_line.n'} and
 7300:    $env{"form.scantron.sub_bubblelines.n"}
 7301:    which are the total number of bubble, lines, the number of bubble
 7302:    lines for response n and number of the first bubble line for response n,
 7303:    and a comma separated list of numbers of bubble lines for sub-questions
 7304:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7305: 
 7306: =cut
 7307: 
 7308: sub scantron_get_maxbubble {
 7309:     if (defined($env{'form.scantron_maxbubble'}) &&
 7310: 	$env{'form.scantron_maxbubble'}) {
 7311: 	&restore_bubble_lines();
 7312: 	return $env{'form.scantron_maxbubble'};
 7313:     }
 7314: 
 7315:     my (undef, undef, $sequence) =
 7316: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7317: 
 7318:     my $navmap=Apache::lonnavmaps::navmap->new();
 7319:     my $map=$navmap->getResourceByUrl($sequence);
 7320:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7321: 
 7322:     &Apache::lonxml::clear_problem_counter();
 7323: 
 7324:     my $uname       = $env{'form.student'};
 7325:     my $udom        = $env{'form.userdom'};
 7326:     my $cid         = $env{'request.course.id'};
 7327:     my $total_lines = 0;
 7328:     %bubble_lines_per_response = ();
 7329:     %first_bubble_line         = ();
 7330:     %subdivided_bubble_lines   = ();
 7331:     %responsetype_per_response = ();
 7332:   
 7333:     my $response_number = 0;
 7334:     my $bubble_line     = 0;
 7335:     foreach my $resource (@resources) {
 7336:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7337:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7338:             foreach my $part_id (@{$parts}) {
 7339: 
 7340:                 my $lines;
 7341: 
 7342: 	        # TODO - make this a persistent hash not an array.
 7343: 
 7344:                 # optionresponse, matchresponse and rankresponse type items 
 7345:                 # render as separate sub-questions in exam mode.
 7346:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7347:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7348:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7349:                     my ($numbub,$numshown);
 7350:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7351:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7352:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7353:                         }
 7354:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7355:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7356:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7357:                         }
 7358:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7359:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7360:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7361:                         }
 7362:                     }
 7363:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7364:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7365:                     }
 7366:                     my $bubbles_per_line = 10;
 7367:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7368:                     if (($numbub % $bubbles_per_line) != 0) {
 7369:                         $inner_bubble_lines++;
 7370:                     }
 7371:                     for (my $i=0; $i<$numshown; $i++) {
 7372:                         $subdivided_bubble_lines{$response_number} .= 
 7373:                             $inner_bubble_lines.',';
 7374:                     }
 7375:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7376:                     $lines = $numshown * $inner_bubble_lines;
 7377:                 } else {
 7378:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7379:                 } 
 7380: 
 7381:                 $first_bubble_line{$response_number} = $bubble_line;
 7382: 	        $bubble_lines_per_response{$response_number} = $lines;
 7383:                 $responsetype_per_response{$response_number} = 
 7384:                     $analysis->{$part_id.'.type'};
 7385: 	        $response_number++;
 7386: 
 7387: 	        $bubble_line +=  $lines;
 7388: 	        $total_lines +=  $lines;
 7389: 	    }
 7390:         }
 7391:     }
 7392:     &Apache::lonnet::delenv('scantron\.');
 7393: 
 7394:     &save_bubble_lines();
 7395:     $env{'form.scantron_maxbubble'} =
 7396: 	$total_lines;
 7397:     return $env{'form.scantron_maxbubble'};
 7398: }
 7399: 
 7400: sub scantron_partids_tograde {
 7401:     my ($resource,$cid,$uname,$udom) = @_;
 7402:     my (%analysis,@parts);
 7403: 
 7404:     if (ref($resource)) {
 7405:         my $symb = $resource->symb();
 7406:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7407:                                         ('symb' => $symb,
 7408:                                          'grade_target' => 'analyze',
 7409:                                          'grade_courseid' => $cid,
 7410:                                          'grade_domain' => $udom,
 7411:                                          'grade_username' => $uname));
 7412:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
 7413:         %analysis = &Apache::lonnet::str2hash($an);
 7414: 
 7415:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7416:             foreach my $part (@{$analysis{'parts'}}) {
 7417:                 my ($id,$respid) = split(/\./,$part);
 7418:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7419:                     push(@parts,$part);
 7420:                 }
 7421:             }
 7422:         }
 7423:     }
 7424:     return (\%analysis,\@parts);
 7425: }
 7426: 
 7427: =pod
 7428: 
 7429: =item scantron_validate_missingbubbles
 7430: 
 7431:    Validates all scanlines in the selected file to not have any
 7432:     answers that don't have bubbles that have not been verified
 7433:     to be bubble free.
 7434: 
 7435: =cut
 7436: 
 7437: sub scantron_validate_missingbubbles {
 7438:     my ($r,$currentphase) = @_;
 7439:     #get student info
 7440:     my $classlist=&Apache::loncoursedata::get_classlist();
 7441:     my %idmap=&username_to_idmap($classlist);
 7442: 
 7443:     #get scantron line setup
 7444:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7445:     my ($scanlines,$scan_data)=&scantron_getfile();
 7446:     my $max_bubble=&scantron_get_maxbubble();
 7447:     if (!$max_bubble) { $max_bubble=2**31; }
 7448:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7449: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7450: 	if ($line=~/^[\s\cz]*$/) { next; }
 7451: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7452: 						 $scan_data);
 7453: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7454: 	my @to_correct;
 7455: 	
 7456: 	# Probably here's where the error is...
 7457: 
 7458: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7459:             my $lastbubble;
 7460:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7461:                my $question = $1;
 7462:                my $subquestion = $2;
 7463:                if (!defined($first_bubble_line{$question -1})) { next; }
 7464:                my $first = $first_bubble_line{$question-1};
 7465:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7466:                my $subcount = 1;
 7467:                while ($subcount<$subquestion) {
 7468:                    $first += $subans[$subcount-1];
 7469:                    $subcount ++;
 7470:                }
 7471:                my $count = $subans[$subquestion-1];
 7472:                $lastbubble = $first + $count;
 7473:             } else {
 7474:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7475:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7476:             }
 7477:             if ($lastbubble > $max_bubble) { next; }
 7478: 	    push(@to_correct,$missing);
 7479: 	}
 7480: 	if (@to_correct) {
 7481: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7482: 				     $line,'missingbubble',\@to_correct);
 7483: 	    return (1,$currentphase);
 7484: 	}
 7485: 
 7486:     }
 7487:     return (0,$currentphase+1);
 7488: }
 7489: 
 7490: =pod
 7491: 
 7492: =item scantron_process_students
 7493: 
 7494:    Routine that does the actual grading of the bubble sheet information.
 7495: 
 7496:    The parsed scanline hash is added to %env 
 7497: 
 7498:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7499:    foreach resource , with the form data of
 7500: 
 7501: 	'submitted'     =>'scantron' 
 7502: 	'grade_target'  =>'grade',
 7503: 	'grade_username'=> username of student
 7504: 	'grade_domain'  => domain of student
 7505: 	'grade_courseid'=> of course
 7506: 	'grade_symb'    => symb of resource to grade
 7507: 
 7508:     This triggers a grading pass. The problem grading code takes care
 7509:     of converting the bubbled letter information (now in %env) into a
 7510:     valid submission.
 7511: 
 7512: =cut
 7513: 
 7514: sub scantron_process_students {
 7515:     my ($r) = @_;
 7516: 
 7517:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7518:     my ($symb)=&get_symb($r);
 7519:     if (!$symb) {
 7520: 	return '';
 7521:     }
 7522:     my $default_form_data=&defaultFormData($symb);
 7523: 
 7524:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7525:     my ($scanlines,$scan_data)=&scantron_getfile();
 7526:     my $classlist=&Apache::loncoursedata::get_classlist();
 7527:     my %idmap=&username_to_idmap($classlist);
 7528:     my $navmap=Apache::lonnavmaps::navmap->new();
 7529:     my $map=$navmap->getResourceByUrl($sequence);
 7530:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7531: 
 7532:     my ($uname,$udom,%partids_by_symb);
 7533:     foreach my $resource (@resources) {
 7534:         my $ressymb = $resource->symb();
 7535:         my ($analysis,$parts) =
 7536:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7537:         $partids_by_symb{$ressymb} = $parts;
 7538:     }
 7539: #    $r->print("geto ".scalar(@resources)."<br />");
 7540:     my $result= <<SCANTRONFORM;
 7541: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7542:   <input type="hidden" name="command" value="scantron_configphase" />
 7543:   $default_form_data
 7544: SCANTRONFORM
 7545:     $r->print($result);
 7546: 
 7547:     my @delayqueue;
 7548:     my (%completedstudents,,%scandata);
 7549:     
 7550:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7551:     my $count=&get_todo_count($scanlines,$scan_data);
 7552:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7553:  				    'Scantron Progress',$count,
 7554: 				    'inline',undef,'scantronupload');
 7555:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7556: 					  'Processing first student');
 7557:     $r->print('<br />');
 7558:     my $start=&Time::HiRes::time();
 7559:     my $i=-1;
 7560:     my $started;
 7561: 
 7562:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7563:     
 7564: 
 7565:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7566:     # the user and return.
 7567: 
 7568:     if ($ssi_error) {
 7569: 	$r->print("</form>");
 7570: 	&ssi_print_error($r);
 7571: 	$r->print(&show_grading_menu_form($symb));
 7572:         &Apache::lonnet::remove_lock($lock);
 7573: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7574:     }
 7575: 
 7576:     my %lettdig = &letter_to_digits();
 7577:     my $numletts = scalar(keys(%lettdig));
 7578: 
 7579:     while ($i<$scanlines->{'count'}) {
 7580:  	($uname,$udom)=('','');
 7581:  	$i++;
 7582:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7583:  	if ($line=~/^[\s\cz]*$/) { next; }
 7584: 	if ($started) {
 7585: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7586: 						     'last student');
 7587: 	}
 7588: 	$started=1;
 7589:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7590:  						 $scan_data);
 7591:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7592:  					      \%idmap,$i)) {
 7593:   	    &scantron_add_delay(\@delayqueue,$line,
 7594:  				'Unable to find a student that matches',1);
 7595:  	    next;
 7596:   	}
 7597:  	if (exists $completedstudents{$uname}) {
 7598:  	    &scantron_add_delay(\@delayqueue,$line,
 7599:  				'Student '.$uname.' has multiple sheets',2);
 7600:  	    next;
 7601:  	}
 7602:   	($uname,$udom)=split(/:/,$uname);
 7603: 
 7604: 	&Apache::lonxml::clear_problem_counter();
 7605:   	&Apache::lonnet::appenv($scan_record);
 7606: 
 7607: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7608: 	    &scantron_putfile($scanlines,$scan_data);
 7609: 	}
 7610: 
 7611:         my $scancode;
 7612:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7613:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7614:             $scancode = $scan_record->{'scantron.CODE'};
 7615:         } else {
 7616:             $scancode = '';
 7617:         }
 7618: 
 7619:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7620:                                    @resources) eq 'ssi_error') {
 7621:             $ssi_error = 0; # So end of handler error message does not trigger.
 7622:             $r->print("</form>");
 7623:             &ssi_print_error($r);
 7624:             $r->print(&show_grading_menu_form($symb));
 7625:             &Apache::lonnet::remove_lock($lock);
 7626:             return '';      # Why return ''?  Beats me.
 7627:         }
 7628: 
 7629: 	$completedstudents{$uname}={'line'=>$line};
 7630:         if ($env{'form.verifyrecord'}) {
 7631:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7632:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7633:             chomp($studentdata);
 7634:             $studentdata =~ s/\r$//;
 7635:             my $studentrecord = '';
 7636:             my $counter = -1;
 7637:             foreach my $resource (@resources) {
 7638:                 ($counter,my $recording) =
 7639:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7640:                                              $counter,$studentdata,\%partids_by_symb,
 7641:                                              \%scantron_config,\%lettdig,$numletts);
 7642:                 $studentrecord .= $recording;
 7643:             }
 7644:             if ($studentrecord ne $studentdata) {
 7645:                 $counter = -1;
 7646:                 $studentrecord = '';
 7647:                 foreach my $resource (@resources) {
 7648:                     ($counter,my $recording) =
 7649:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7650:                                                  $counter,$studentdata,\%partids_by_symb,
 7651:                                                  \%scantron_config,\%lettdig,$numletts);
 7652:                     $studentrecord .= $recording;
 7653:                 }
 7654:                 if ($studentrecord ne $studentdata) {
 7655:                     $r->print('<p><span class="LC_error">');
 7656:                     if ($scancode eq '') {
 7657:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7658:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7659:                     } else {
 7660:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7661:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7662:                     }
 7663:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7664:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7665:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7666:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7667:                               &Apache::loncommon::start_data_table_row().
 7668:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7669:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7670:                               &Apache::loncommon::end_data_table_row().
 7671:                               &Apache::loncommon::start_data_table_row().
 7672:                               '<td>Stored submissions</td>'.
 7673:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7674:                               &Apache::loncommon::end_data_table_row().
 7675:                               &Apache::loncommon::end_data_table().'</p>');
 7676:                 } else {
 7677:                     $r->print('<br /><span class="LC_warning">'.
 7678:                              &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 />'.
 7679:                              &mt("As a consequence, this user's submission history records two tries.").
 7680:                                  '</span><br />');
 7681:                 }
 7682:             }
 7683:         }
 7684: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7685:     } continue {
 7686: 	&Apache::lonxml::clear_problem_counter();
 7687: 	&Apache::lonnet::delenv('scantron\.');
 7688:     }
 7689:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7690:     &Apache::lonnet::remove_lock($lock);
 7691: #    my $lasttime = &Time::HiRes::time()-$start;
 7692: #    $r->print("<p>took $lasttime</p>");
 7693: 
 7694:     $r->print("</form>");
 7695:     $r->print(&show_grading_menu_form($symb));
 7696:     return '';
 7697: }
 7698: 
 7699: sub grade_student_bubbles {
 7700:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
 7701:     foreach my $resource (@resources) {
 7702:         my %form = ('submitted'     => 'scantron',
 7703:                     'grade_target'  => 'grade',
 7704:                     'grade_username'=> $uname,
 7705:                     'grade_domain'  => $udom,
 7706:                     'grade_courseid'=> $env{'request.course.id'},
 7707:                     'grade_symb'    => $resource->symb(),
 7708:                     'code'          => $scancode);
 7709:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7710:         return 'ssi_error' if ($ssi_error);
 7711:         last if (&Apache::loncommon::connection_aborted($r));
 7712:     }
 7713:     return;
 7714: }
 7715: 
 7716: =pod
 7717: 
 7718: =item scantron_upload_scantron_data
 7719: 
 7720:     Creates the screen for adding a new bubble sheet data file to a course.
 7721: 
 7722: =cut
 7723: 
 7724: sub scantron_upload_scantron_data {
 7725:     my ($r)=@_;
 7726:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7727:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7728: 							  'domainid',
 7729: 							  'coursename');
 7730:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7731: 						   'domainid');
 7732:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7733:     $r->print('
 7734: <script type="text/javascript" language="javascript">
 7735:     function checkUpload(formname) {
 7736: 	if (formname.upfile.value == "") {
 7737: 	    alert("Please use the browse button to select a file from your local directory.");
 7738: 	    return false;
 7739: 	}
 7740: 	formname.submit();
 7741:     }
 7742: </script>
 7743: 
 7744: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7745: '.$default_form_data.'
 7746: <table>
 7747: <tr><td>'.$select_link.'                             </td></tr>
 7748: <tr><td>'.&mt('Course ID:').'     </td>
 7749:     <td><input name="courseid"   type="text" />      </td></tr>
 7750: <tr><td>'.&mt('Course Name:').'   </td>
 7751:     <td><input name="coursename" type="text" />      </td></tr>
 7752: <tr><td>'.&mt('Domain:').'        </td>
 7753:     <td>'.$domsel.'                                  </td></tr>
 7754: <tr><td>'.&mt('File to upload:').'</td>
 7755:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7756: </table>
 7757: <input name="command" value="scantronupload_save" type="hidden" />
 7758: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7759: </form>
 7760: ');
 7761:     return '';
 7762: }
 7763: 
 7764: =pod
 7765: 
 7766: =item scantron_upload_scantron_data_save
 7767: 
 7768:    Adds a provided bubble information data file to the course if user
 7769:    has the correct privileges to do so.  
 7770: 
 7771: =cut
 7772: 
 7773: sub scantron_upload_scantron_data_save {
 7774:     my($r)=@_;
 7775:     my ($symb)=&get_symb($r,1);
 7776:     my $doanotherupload=
 7777: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7778: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7779: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7780: 	'</form>'."\n";
 7781:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7782: 	!&Apache::lonnet::allowed('usc',
 7783: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7784: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7785: 	if ($symb) {
 7786: 	    $r->print(&show_grading_menu_form($symb));
 7787: 	} else {
 7788: 	    $r->print($doanotherupload);
 7789: 	}
 7790: 	return '';
 7791:     }
 7792:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7793:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7794:     my $fname=$env{'form.upfile.filename'};
 7795:     #FIXME
 7796:     #copied from lonnet::userfileupload()
 7797:     #make that function able to target a specified course
 7798:     # Replace Windows backslashes by forward slashes
 7799:     $fname=~s/\\/\//g;
 7800:     # Get rid of everything but the actual filename
 7801:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7802:     # Replace spaces by underscores
 7803:     $fname=~s/\s+/\_/g;
 7804:     # Replace all other weird characters by nothing
 7805:     $fname=~s/[^\w\.\-]//g;
 7806:     # See if there is anything left
 7807:     unless ($fname) { return 'error: no uploaded file'; }
 7808:     my $uploadedfile=$fname;
 7809:     $fname='scantron_orig_'.$fname;
 7810:     if (length($env{'form.upfile'}) < 2) {
 7811: 	$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>"));
 7812:     } else {
 7813: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7814: 	if ($result =~ m|^/uploaded/|) {
 7815: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7816: 			  (length($env{'form.upfile'})-1),
 7817: 			  '<span class="LC_filename">'.$result."</span>"));
 7818: 	} else {
 7819: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7820: 			  $result,
 7821: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7822: 
 7823: 	}
 7824:     }
 7825:     if ($symb) {
 7826: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7827:     } else {
 7828: 	$r->print($doanotherupload);
 7829:     }
 7830:     return '';
 7831: }
 7832: 
 7833: =pod
 7834: 
 7835: =item valid_file
 7836: 
 7837:    Validates that the requested bubble data file exists in the course.
 7838: 
 7839: =cut
 7840: 
 7841: sub valid_file {
 7842:     my ($requested_file)=@_;
 7843:     foreach my $filename (sort(&scantron_filenames())) {
 7844: 	if ($requested_file eq $filename) { return 1; }
 7845:     }
 7846:     return 0;
 7847: }
 7848: 
 7849: =pod
 7850: 
 7851: =item scantron_download_scantron_data
 7852: 
 7853:    Shows a list of the three internal files (original, corrected,
 7854:    skipped) for a specific bubble sheet data file that exists in the
 7855:    course.
 7856: 
 7857: =cut
 7858: 
 7859: sub scantron_download_scantron_data {
 7860:     my ($r)=@_;
 7861:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7862:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7863:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7864:     my $file=$env{'form.scantron_selectfile'};
 7865:     if (! &valid_file($file)) {
 7866: 	$r->print('
 7867: 	<p>
 7868: 	    '.&mt('The requested file name was invalid.').'
 7869:         </p>
 7870: ');
 7871: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7872: 	return;
 7873:     }
 7874:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7875:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7876:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7877:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7878:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7879:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7880:     $r->print('
 7881:     <p>
 7882: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7883: 	      '<a href="'.$orig.'">','</a>').'
 7884:     </p>
 7885:     <p>
 7886: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7887: 	      '<a href="'.$corrected.'">','</a>').'
 7888:     </p>
 7889:     <p>
 7890: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7891: 	      '<a href="'.$skipped.'">','</a>').'
 7892:     </p>
 7893: ');
 7894:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7895:     return '';
 7896: }
 7897: 
 7898: sub checkscantron_results {
 7899:     my ($r) = @_;
 7900:     my ($symb)=&get_symb($r);
 7901:     if (!$symb) {return '';}
 7902:     my $grading_menu_button=&show_grading_menu_form($symb);
 7903:     my $cid = $env{'request.course.id'};
 7904:     my %lettdig = &letter_to_digits();
 7905:     my $numletts = scalar(keys(%lettdig));
 7906:     my $cnum = $env{'course.'.$cid.'.num'};
 7907:     my $cdom = $env{'course.'.$cid.'.domain'};
 7908:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7909:     my %record;
 7910:     my %scantron_config =
 7911:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7912:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7913:     my $classlist=&Apache::loncoursedata::get_classlist();
 7914:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7915:     my $navmap=Apache::lonnavmaps::navmap->new();
 7916:     my $map=$navmap->getResourceByUrl($sequence);
 7917:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7918:     my ($uname,$udom,%partids_by_symb);
 7919:     foreach my $resource (@resources) {
 7920:         my $ressymb = $resource->symb();
 7921:         my ($analysis,$parts) =
 7922:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7923:         $partids_by_symb{$ressymb} = $parts;
 7924:     }
 7925:     my (%scandata,%lastname,%bylast);
 7926:     $r->print('
 7927: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7928: 
 7929:     my @delayqueue;
 7930:     my %completedstudents;
 7931: 
 7932:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7933:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7934:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7935:                                     'inline',undef,'checkscantron');
 7936:     my ($username,$domain,$uname,$started);
 7937: 
 7938:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7939: 
 7940:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7941:                                           'Processing first student');
 7942:     my $start=&Time::HiRes::time();
 7943:     my $i=-1;
 7944: 
 7945:     while ($i<$scanlines->{'count'}) {
 7946:         ($username,$domain,$uname)=('','','');
 7947:         $i++;
 7948:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7949:         if ($line=~/^[\s\cz]*$/) { next; }
 7950:         if ($started) {
 7951:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7952:                                                      'last student');
 7953:         }
 7954:         $started=1;
 7955:         my $scan_record=
 7956:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7957:                                                      $scan_data);
 7958:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7959:                                                               \%idmap,$i)) {
 7960:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7961:                                 'Unable to find a student that matches',1);
 7962:             next;
 7963:         }
 7964:         if (exists $completedstudents{$uname}) {
 7965:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7966:                                 'Student '.$uname.' has multiple sheets',2);
 7967:             next;
 7968:         }
 7969:         my $pid = $scan_record->{'scantron.ID'};
 7970:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7971:         push(@{$bylast{$lastname{$pid}}},$pid);
 7972:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7973:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7974:         chomp($scandata{$pid});
 7975:         $scandata{$pid} =~ s/\r$//;
 7976:         ($username,$domain)=split(/:/,$uname);
 7977:         my $counter = -1;
 7978:         foreach my $resource (@resources) {
 7979:             ($counter,my $recording) =
 7980:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7981:                                          $scandata{$pid},\%partids_by_symb,
 7982:                                          \%scantron_config,\%lettdig,$numletts);
 7983:             $record{$pid} .= $recording;
 7984:         }
 7985:     }
 7986:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7987:     $r->print('<br />');
 7988:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 7989:     $passed = 0;
 7990:     $failed = 0;
 7991:     $numstudents = 0;
 7992:     foreach my $last (sort(keys(%bylast))) {
 7993:         if (ref($bylast{$last}) eq 'ARRAY') {
 7994:             foreach my $pid (sort(@{$bylast{$last}})) {
 7995:                 my $showscandata = $scandata{$pid};
 7996:                 my $showrecord = $record{$pid};
 7997:                 $showscandata =~ s/\s/&nbsp;/g;
 7998:                 $showrecord =~ s/\s/&nbsp;/g;
 7999:                 if ($scandata{$pid} eq $record{$pid}) {
 8000:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8001:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8002: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8003: '</tr>'."\n".
 8004: '<tr class="'.$css_class.'">'."\n".
 8005: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8006:                     $passed ++;
 8007:                 } else {
 8008:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8009:                     $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".
 8010: '</tr>'."\n".
 8011: '<tr class="'.$css_class.'">'."\n".
 8012: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8013: '</tr>'."\n";
 8014:                     $failed ++;
 8015:                 }
 8016:                 $numstudents ++;
 8017:             }
 8018:         }
 8019:     }
 8020:     $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>');
 8021:     $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>');
 8022:     if ($passed) {
 8023:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8024:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8025:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8026:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8027:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8028:                  $okstudents."\n".
 8029:                  &Apache::loncommon::end_data_table().'<br />');
 8030:     }
 8031:     if ($failed) {
 8032:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8033:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8034:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8035:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8036:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8037:                  $badstudents."\n".
 8038:                  &Apache::loncommon::end_data_table()).'<br />'.
 8039:                  &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.');  
 8040:     }
 8041:     $r->print('</form><br />'.$grading_menu_button);
 8042:     return;
 8043: }
 8044: 
 8045: sub verify_scantron_grading {
 8046:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
 8047:         $scantron_config,$lettdig,$numletts) = @_;
 8048:     my ($record,%expected,%startpos);
 8049:     return ($counter,$record) if (!ref($resource));
 8050:     return ($counter,$record) if (!$resource->is_problem());
 8051:     my $symb = $resource->symb();
 8052:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
 8053:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
 8054:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8055:         $counter ++;
 8056:         $expected{$part_id} = 0;
 8057:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8058:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8059:             foreach my $item (@sub_lines) {
 8060:                 $expected{$part_id} += $item;
 8061:             }
 8062:         } else {
 8063:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8064:         }
 8065:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8066:     }
 8067:     if ($symb) {
 8068:         my %recorded;
 8069:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8070:         if ($returnhash{'version'}) {
 8071:             my %lasthash=();
 8072:             my $version;
 8073:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8074:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8075:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8076:                 }
 8077:             }
 8078:             foreach my $key (keys(%lasthash)) {
 8079:                 if ($key =~ /\.scantron$/) {
 8080:                     my $value = &unescape($lasthash{$key});
 8081:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8082:                     if ($value eq '') {
 8083:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8084:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8085:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8086:                             }
 8087:                         }
 8088:                     } else {
 8089:                         my @tocheck;
 8090:                         my @items = split(//,$value);
 8091:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8092:                             ($scantron_config->{'Qon'} eq 'number')) {
 8093:                             if (@items < $expected{$part_id}) {
 8094:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8095:                                 my @singles = split(//,$fragment);
 8096:                                 foreach my $pos (@singles) {
 8097:                                     if ($pos eq ' ') {
 8098:                                         push(@tocheck,$pos);
 8099:                                     } else {
 8100:                                         my $next = shift(@items);
 8101:                                         push(@tocheck,$next);
 8102:                                     }
 8103:                                 }
 8104:                             } else {
 8105:                                 @tocheck = @items;
 8106:                             }
 8107:                             foreach my $letter (@tocheck) {
 8108:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8109:                                     if ($letter !~ /^[A-J]$/) {
 8110:                                         $letter = $scantron_config->{'Qoff'};
 8111:                                     }
 8112:                                     $recorded{$part_id} .= $letter;
 8113:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8114:                                     my $digit;
 8115:                                     if ($letter !~ /^[A-J]$/) {
 8116:                                         $digit = $scantron_config->{'Qoff'};
 8117:                                     } else {
 8118:                                         $digit = $lettdig->{$letter};
 8119:                                     }
 8120:                                     $recorded{$part_id} .= $digit;
 8121:                                 }
 8122:                             }
 8123:                         } else {
 8124:                             @tocheck = @items;
 8125:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8126:                                 my $curr_sub = shift(@tocheck);
 8127:                                 my $digit;
 8128:                                 if ($curr_sub =~ /^[A-J]$/) {
 8129:                                     $digit = $lettdig->{$curr_sub}-1;
 8130:                                 }
 8131:                                 if ($curr_sub eq 'J') {
 8132:                                     $digit += scalar($numletts);
 8133:                                 }
 8134:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8135:                                     if ($j == $digit) {
 8136:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8137:                                     } else {
 8138:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8139:                                     }
 8140:                                 }
 8141:                             }
 8142:                         }
 8143:                     }
 8144:                 }
 8145:             }
 8146:         }
 8147:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8148:             if ($recorded{$part_id} eq '') {
 8149:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8150:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8151:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8152:                     }
 8153:                 }
 8154:             }
 8155:             $record .= $recorded{$part_id};
 8156:         }
 8157:     }
 8158:     return ($counter,$record);
 8159: }
 8160: 
 8161: sub letter_to_digits {
 8162:     my %lettdig = (
 8163:                     A => 1,
 8164:                     B => 2,
 8165:                     C => 3,
 8166:                     D => 4,
 8167:                     E => 5,
 8168:                     F => 6,
 8169:                     G => 7,
 8170:                     H => 8,
 8171:                     I => 9,
 8172:                     J => 0,
 8173:                   );
 8174:     return %lettdig;
 8175: }
 8176: 
 8177: =pod
 8178: 
 8179: =back
 8180: 
 8181: =cut
 8182: 
 8183: #-------- end of section for handling grading scantron forms -------
 8184: #
 8185: #-------------------------------------------------------------------
 8186: 
 8187: #-------------------------- Menu interface -------------------------
 8188: #
 8189: #--- Show a Grading Menu button - Calls the next routine ---
 8190: sub show_grading_menu_form {
 8191:     my ($symb)=@_;
 8192:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8194: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8195: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8196: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8197: 	'</form>'."\n";
 8198:     return $result;
 8199: }
 8200: 
 8201: # -- Retrieve choices for grading form
 8202: sub savedState {
 8203:     my %savedState = ();
 8204:     if ($env{'form.saveState'}) {
 8205: 	foreach (split(/:/,$env{'form.saveState'})) {
 8206: 	    my ($key,$value) = split(/=/,$_,2);
 8207: 	    $savedState{$key} = $value;
 8208: 	}
 8209:     }
 8210:     return \%savedState;
 8211: }
 8212: 
 8213: sub grading_menu {
 8214:     my ($request) = @_;
 8215:     my ($symb)=&get_symb($request);
 8216:     if (!$symb) {return '';}
 8217:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8218:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8219: 
 8220:     $request->print($table);
 8221:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8222:                   'handgrade'=>$hdgrade,
 8223:                   'probTitle'=>$probTitle,
 8224:                   'command'=>'submit_options',
 8225:                   'saveState'=>"",
 8226:                   'gradingMenu'=>1,
 8227:                   'showgrading'=>"yes");
 8228:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8229:     my @menu = ({ url => $url,
 8230:                      name => &mt('Manual Grading/View Submissions'),
 8231:                      short_description => 
 8232:     &mt('Start the process of hand grading submissions.'),
 8233:                  });
 8234:     $fields{'command'} = 'csvform';
 8235:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8236:     push(@menu, { url => $url,
 8237:                    name => &mt('Upload Scores'),
 8238:                    short_description => 
 8239:             &mt('Specify a file containing the class scores for current resource.')});
 8240:     $fields{'command'} = 'processclicker';
 8241:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8242:     push(@menu, { url => $url,
 8243:                    name => &mt('Process Clicker'),
 8244:                    short_description => 
 8245:             &mt('Specify a file containing the clicker information for this resource.')});
 8246:     $fields{'command'} = 'scantron_selectphase';
 8247:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8248:     push(@menu, { url => $url,
 8249:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8250:                    short_description => 
 8251:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8252:     $fields{'command'} = 'verify';
 8253:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8254:     push(@menu, { url => "",
 8255:                    name => &mt('Verify Receipt'),
 8256:                    short_description => 
 8257:             &mt('')});
 8258:     #
 8259:     # Create the menu
 8260:     my $Str;
 8261:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8262:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8263:     $Str .= '<input type="hidden" name="command" value="" />'.
 8264:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8265: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8266: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8267: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8268: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8269: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8270: 
 8271:     foreach my $menudata (@menu) {
 8272:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8273:             $Str .='    <h3><a '.
 8274:                 $menudata->{'jscript'}.
 8275:                 ' href="'.
 8276:                 $menudata->{'url'}.'" >'.
 8277:                 $menudata->{'name'}."</a></h3>\n";
 8278:         } else {
 8279:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8280:                 $menudata->{'jscript'}.
 8281:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8282:                 ' /> '.
 8283: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8284:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8285:         }
 8286:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8287:             "\n";
 8288:     }
 8289:     $Str .="</form>\n";
 8290:     $request->print(<<GRADINGMENUJS);
 8291: <script type="text/javascript" language="javascript">
 8292:     function checkChoice(formname,val,cmdx) {
 8293: 	if (val <= 2) {
 8294: 	    var cmd = radioSelection(formname.radioChoice);
 8295: 	    var cmdsave = cmd;
 8296: 	} else {
 8297: 	    cmd = cmdx;
 8298: 	    cmdsave = 'submission';
 8299: 	}
 8300: 	formname.command.value = cmd;
 8301: 	if (val < 5) formname.submit();
 8302: 	if (val == 5) {
 8303: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8304: 	        return false;
 8305: 	    } else {
 8306: 	        formname.submit();
 8307: 	    }
 8308: 	}
 8309:     }
 8310: 
 8311:     function checkReceiptNo(formname,nospace) {
 8312: 	var receiptNo = formname.receipt.value;
 8313: 	var checkOpt = false;
 8314: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8315: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8316: 	if (checkOpt) {
 8317: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8318: 	    formname.receipt.value = "";
 8319: 	    formname.receipt.focus();
 8320: 	    return false;
 8321: 	}
 8322: 	return true;
 8323:     }
 8324: </script>
 8325: GRADINGMENUJS
 8326:     &commonJSfunctions($request);
 8327:     return $Str;    
 8328: }
 8329: 
 8330: 
 8331: #--- Displays the submissions first page -------
 8332: sub submit_options {
 8333:     my ($request) = @_;
 8334:     my ($symb)=&get_symb($request);
 8335:     if (!$symb) {return '';}
 8336:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8337: 
 8338:     $request->print(<<GRADINGMENUJS);
 8339: <script type="text/javascript" language="javascript">
 8340:     function checkChoice(formname,val,cmdx) {
 8341: 	if (val <= 2) {
 8342: 	    var cmd = radioSelection(formname.radioChoice);
 8343: 	    var cmdsave = cmd;
 8344: 	} else {
 8345: 	    cmd = cmdx;
 8346: 	    cmdsave = 'submission';
 8347: 	}
 8348: 	formname.command.value = cmd;
 8349: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8350: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8351: 	if (val < 5) formname.submit();
 8352: 	if (val == 5) {
 8353: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8354: 	    formname.submit();
 8355: 	}
 8356: 	if (val < 7) formname.submit();
 8357:     }
 8358: 
 8359:     function checkReceiptNo(formname,nospace) {
 8360: 	var receiptNo = formname.receipt.value;
 8361: 	var checkOpt = false;
 8362: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8363: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8364: 	if (checkOpt) {
 8365: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8366: 	    formname.receipt.value = "";
 8367: 	    formname.receipt.focus();
 8368: 	    return false;
 8369: 	}
 8370: 	return true;
 8371:     }
 8372: </script>
 8373: GRADINGMENUJS
 8374:     &commonJSfunctions($request);
 8375:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8376:     my $result;
 8377:     my (undef,$sections) = &getclasslist('all','0');
 8378:     my $savedState = &savedState();
 8379:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8380:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8381:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8382:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8383: 
 8384:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8385: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8386: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8387: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8388: 	'<input type="hidden" name="command"     value="" />'."\n".
 8389: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8390: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8391: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8392: 
 8393:     $result.='
 8394:     <div class="LC_grade_select_mode">
 8395:       <div class="LC_grade_select_mode_current">
 8396:         <h2>
 8397:           '.&mt('Grade Current Resource').'
 8398:         </h2>
 8399:         <div class="LC_grade_select_mode_body">
 8400:           <div class="LC_grades_resource_info">
 8401:            '.$table.'
 8402:           </div>
 8403:           <div class="LC_grade_select_mode_selector">
 8404:              <div class="LC_grade_select_mode_selector_header">
 8405:                 '.&mt('Sections').'
 8406:              </div>
 8407:              <div class="LC_grade_select_mode_selector_body">
 8408: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8409:     if (ref($sections)) {
 8410: 	foreach my $section (sort(@$sections)) {
 8411: 	    $result.='<option value="'.$section.'" '.
 8412: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8413: 	}
 8414:     }
 8415:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8416:     $result.='
 8417:              </div>
 8418:           </div>
 8419:           <div class="LC_grade_select_mode_selector">
 8420:              <div class="LC_grade_select_mode_selector_header">
 8421:                 '.&mt('Groups').'
 8422:              </div>
 8423:              <div class="LC_grade_select_mode_selector_body">
 8424:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8425:              </div>
 8426:           </div>
 8427:           <div class="LC_grade_select_mode_selector">
 8428:              <div class="LC_grade_select_mode_selector_header">
 8429:                 '.&mt('Access Status').'
 8430:              </div>
 8431:              <div class="LC_grade_select_mode_selector_body">
 8432:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8433:              </div>
 8434:           </div>
 8435:           <div class="LC_grade_select_mode_selector">
 8436:              <div class="LC_grade_select_mode_selector_header">
 8437:                 '.&mt('Submission Status').'
 8438:              </div>
 8439:              <div class="LC_grade_select_mode_selector_body">
 8440:                <select name="submitonly" size="5">
 8441: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8442: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8443: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8444: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8445:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8446:                </select>
 8447:              </div>
 8448:           </div>
 8449:           <div class="LC_grade_select_mode_type_body">
 8450:             <div class="LC_grade_select_mode_type">
 8451:               <label>
 8452:                 <input type="radio" name="radioChoice" value="submission" '.
 8453:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8454:              &mt('Select individual students to grade and view submissions.').'
 8455: 	      </label> 
 8456:             </div>
 8457:             <div class="LC_grade_select_mode_type">
 8458: 	      <label>
 8459:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8460:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8461:                     &mt('Grade all selected students in a grading table.').'
 8462:               </label>
 8463:             </div>
 8464:             <div class="LC_grade_select_mode_type">
 8465: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8466:             </div>
 8467:           </div>
 8468:         </div>
 8469:       </div>
 8470:       <div class="LC_grade_select_mode_page">
 8471:         <h2>
 8472:          '.&mt('Grade Complete Folder for One Student').'
 8473:         </h2>
 8474:         <div class="LC_grades_select_mode_body">
 8475:           <div class="LC_grade_select_mode_type_body">
 8476:             <div class="LC_grade_select_mode_type">
 8477:               <label>
 8478:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8479: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8480:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8481:               </label>
 8482:             </div>
 8483:             <div class="LC_grade_select_mode_type">
 8484: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8485:             </div>
 8486:           </div>
 8487:         </div>
 8488:       </div>
 8489:     </div>
 8490:   </form>';
 8491:     $result .= &show_grading_menu_form($symb);
 8492:     return $result;
 8493: }
 8494: 
 8495: sub reset_perm {
 8496:     undef(%perm);
 8497: }
 8498: 
 8499: sub init_perm {
 8500:     &reset_perm();
 8501:     foreach my $test_perm ('vgr','mgr','opa') {
 8502: 
 8503: 	my $scope = $env{'request.course.id'};
 8504: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8505: 
 8506: 	    $scope .= '/'.$env{'request.course.sec'};
 8507: 	    if ( $perm{$test_perm}=
 8508: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8509: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8510: 	    } else {
 8511: 		delete($perm{$test_perm});
 8512: 	    }
 8513: 	}
 8514:     }
 8515: }
 8516: 
 8517: sub gather_clicker_ids {
 8518:     my %clicker_ids;
 8519: 
 8520:     my $classlist = &Apache::loncoursedata::get_classlist();
 8521: 
 8522:     # Set up a couple variables.
 8523:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8524:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8525:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8526: 
 8527:     foreach my $student (keys(%$classlist)) {
 8528:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8529:         my $username = $classlist->{$student}->[$username_idx];
 8530:         my $domain   = $classlist->{$student}->[$domain_idx];
 8531:         my $clickers =
 8532: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8533:         foreach my $id (split(/\,/,$clickers)) {
 8534:             $id=~s/^[\#0]+//;
 8535:             $id=~s/[\-\:]//g;
 8536:             if (exists($clicker_ids{$id})) {
 8537: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8538:             } else {
 8539: 		$clicker_ids{$id}=$username.':'.$domain;
 8540:             }
 8541:         }
 8542:     }
 8543:     return %clicker_ids;
 8544: }
 8545: 
 8546: sub gather_adv_clicker_ids {
 8547:     my %clicker_ids;
 8548:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8550:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8551:     foreach my $element (sort(keys(%coursepersonnel))) {
 8552:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8553:             my ($puname,$pudom)=split(/\:/,$person);
 8554:             my $clickers =
 8555: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8556:             foreach my $id (split(/\,/,$clickers)) {
 8557: 		$id=~s/^[\#0]+//;
 8558:                 $id=~s/[\-\:]//g;
 8559: 		if (exists($clicker_ids{$id})) {
 8560: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8561: 		} else {
 8562: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8563: 		}
 8564:             }
 8565:         }
 8566:     }
 8567:     return %clicker_ids;
 8568: }
 8569: 
 8570: sub clicker_grading_parameters {
 8571:     return ('gradingmechanism' => 'scalar',
 8572:             'upfiletype' => 'scalar',
 8573:             'specificid' => 'scalar',
 8574:             'pcorrect' => 'scalar',
 8575:             'pincorrect' => 'scalar');
 8576: }
 8577: 
 8578: sub process_clicker {
 8579:     my ($r)=@_;
 8580:     my ($symb)=&get_symb($r);
 8581:     if (!$symb) {return '';}
 8582:     my $result=&checkforfile_js();
 8583:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8584:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8585:     $result.=$table;
 8586:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8587:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8588:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8589:         '.</b></td></tr>'."\n";
 8590:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8591: # Attempt to restore parameters from last session, set defaults if not present
 8592:     my %Saveable_Parameters=&clicker_grading_parameters();
 8593:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8594:                                                  \%Saveable_Parameters);
 8595:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8596:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8597:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8598:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8599: 
 8600:     my %checked;
 8601:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8602:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8603:           $checked{$gradingmechanism}="checked='checked'";
 8604:        }
 8605:     }
 8606: 
 8607:     my $upload=&mt("Upload File");
 8608:     my $type=&mt("Type");
 8609:     my $attendance=&mt("Award points just for participation");
 8610:     my $personnel=&mt("Correctness determined from response by course personnel");
 8611:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8612:     my $given=&mt("Correctness determined from given list of answers").' '.
 8613:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8614:     my $pcorrect=&mt("Percentage points for correct solution");
 8615:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8616:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8617: 						   ('iclicker' => 'i>clicker',
 8618:                                                     'interwrite' => 'interwrite PRS'));
 8619:     $symb = &Apache::lonenc::check_encrypt($symb);
 8620:     $result.=<<ENDUPFORM;
 8621: <script type="text/javascript">
 8622: function sanitycheck() {
 8623: // Accept only integer percentages
 8624:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8625:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8626: // Find out grading choice
 8627:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8628:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8629:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8630:       }
 8631:    }
 8632: // By default, new choice equals user selection
 8633:    newgradingchoice=gradingchoice;
 8634: // Not good to give more points for false answers than correct ones
 8635:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8636:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8637:    }
 8638: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8639:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8640:       document.forms.gradesupload.pcorrect.value=100;
 8641:       document.forms.gradesupload.pincorrect.value=100;
 8642:    }
 8643: // If the values are different, cannot be attendance only
 8644:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8645:        (gradingchoice=='attendance')) {
 8646:        newgradingchoice='personnel';
 8647:    }
 8648: // Change grading choice to new one
 8649:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8650:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8651:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8652:       } else {
 8653:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8654:       }
 8655:    }
 8656: // Remember the old state
 8657:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8658: }
 8659: </script>
 8660: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8661: <input type="hidden" name="symb" value="$symb" />
 8662: <input type="hidden" name="command" value="processclickerfile" />
 8663: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8664: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8665: <input type="file" name="upfile" size="50" />
 8666: <br /><label>$type: $selectform</label>
 8667: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8668: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8669: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8670: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8671: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8672: <br />&nbsp;&nbsp;&nbsp;
 8673: <input type="text" name="givenanswer" size="50" />
 8674: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8675: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8676: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8677: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8678: </form>
 8679: ENDUPFORM
 8680:     $result.='</td></tr></table>'."\n".
 8681:              '</td></tr></table><br /><br />'."\n";
 8682:     $result.=&show_grading_menu_form($symb);
 8683:     return $result;
 8684: }
 8685: 
 8686: sub process_clicker_file {
 8687:     my ($r)=@_;
 8688:     my ($symb)=&get_symb($r);
 8689:     if (!$symb) {return '';}
 8690: 
 8691:     my %Saveable_Parameters=&clicker_grading_parameters();
 8692:     &Apache::loncommon::store_course_settings('grades_clicker',
 8693:                                               \%Saveable_Parameters);
 8694: 
 8695:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8696:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8697: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8698: 	return $result.&show_grading_menu_form($symb);
 8699:     }
 8700:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8701:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8702:         return $result.&show_grading_menu_form($symb);
 8703:     }
 8704:     my $foundgiven=0;
 8705:     if ($env{'form.gradingmechanism'} eq 'given') {
 8706:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8707:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8708:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8709:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8710:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8711:         $foundgiven=$#answers+1;
 8712:     }
 8713:     my %clicker_ids=&gather_clicker_ids();
 8714:     my %correct_ids;
 8715:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8716: 	%correct_ids=&gather_adv_clicker_ids();
 8717:     }
 8718:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8719: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8720: 	   $correct_id=~tr/a-z/A-Z/;
 8721: 	   $correct_id=~s/\s//gs;
 8722: 	   $correct_id=~s/^[\#0]+//;
 8723:            $correct_id=~s/[\-\:]//g;
 8724:            if ($correct_id) {
 8725: 	      $correct_ids{$correct_id}='specified';
 8726:            }
 8727:         }
 8728:     }
 8729:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8730: 	$result.=&mt('Score based on attendance only');
 8731:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8732:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8733:     } else {
 8734: 	my $number=0;
 8735: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8736: 	foreach my $id (sort(keys(%correct_ids))) {
 8737: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8738: 	    if ($correct_ids{$id} eq 'specified') {
 8739: 		$result.=&mt('specified');
 8740: 	    } else {
 8741: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8742: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8743: 	    }
 8744: 	    $number++;
 8745: 	}
 8746:         $result.="</p>\n";
 8747: 	if ($number==0) {
 8748: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8749: 	    return $result.&show_grading_menu_form($symb);
 8750: 	}
 8751:     }
 8752:     if (length($env{'form.upfile'}) < 2) {
 8753:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8754: 		     '<span class="LC_error">',
 8755: 		     '</span>',
 8756: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8757:         return $result.&show_grading_menu_form($symb);
 8758:     }
 8759: 
 8760: # Were able to get all the info needed, now analyze the file
 8761: 
 8762:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8763:     $symb = &Apache::lonenc::check_encrypt($symb);
 8764:     my $heading=&mt('Scanning clicker file');
 8765:     $result.=(<<ENDHEADER);
 8766: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8767: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8768: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8769: <form method="post" action="/adm/grades" name="clickeranalysis">
 8770: <input type="hidden" name="symb" value="$symb" />
 8771: <input type="hidden" name="command" value="assignclickergrades" />
 8772: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8773: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8774: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8775: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8776: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8777: ENDHEADER
 8778:     if ($env{'form.gradingmechanism'} eq 'given') {
 8779:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8780:     } 
 8781:     my %responses;
 8782:     my @questiontitles;
 8783:     my $errormsg='';
 8784:     my $number=0;
 8785:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8786: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8787:     }
 8788:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8789:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8790:     }
 8791:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8792:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8793:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8794:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8795:              '<br />';
 8796:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8797:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8798:        return $result.&show_grading_menu_form($symb);
 8799:     } 
 8800: # Remember Question Titles
 8801: # FIXME: Possibly need delimiter other than ":"
 8802:     for (my $i=0;$i<$number;$i++) {
 8803:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8804:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8805:     }
 8806:     my $correct_count=0;
 8807:     my $student_count=0;
 8808:     my $unknown_count=0;
 8809: # Match answers with usernames
 8810: # FIXME: Possibly need delimiter other than ":"
 8811:     foreach my $id (keys(%responses)) {
 8812:        if ($correct_ids{$id}) {
 8813:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8814:           $correct_count++;
 8815:        } elsif ($clicker_ids{$id}) {
 8816:           if ($clicker_ids{$id}=~/\,/) {
 8817: # More than one user with the same clicker!
 8818:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8819:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8820:                            "<select name='multi".$id."'>";
 8821:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8822:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8823:              }
 8824:              $result.='</select>';
 8825:              $unknown_count++;
 8826:           } else {
 8827: # Good: found one and only one user with the right clicker
 8828:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8829:              $student_count++;
 8830:           }
 8831:        } else {
 8832:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8833:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8834:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8835:                    "\n".&mt("Domain").": ".
 8836:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8837:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8838:           $unknown_count++;
 8839:        }
 8840:     }
 8841:     $result.='<hr />'.
 8842:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8843:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8844:        if ($correct_count==0) {
 8845:           $errormsg.="Found no correct answers answers for grading!";
 8846:        } elsif ($correct_count>1) {
 8847:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8848:        }
 8849:     }
 8850:     if ($number<1) {
 8851:        $errormsg.="Found no questions.";
 8852:     }
 8853:     if ($errormsg) {
 8854:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8855:     } else {
 8856:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8857:     }
 8858:     $result.='</form></td></tr></table>'."\n".
 8859:              '</td></tr></table><br /><br />'."\n";
 8860:     return $result.&show_grading_menu_form($symb);
 8861: }
 8862: 
 8863: sub iclicker_eval {
 8864:     my ($questiontitles,$responses)=@_;
 8865:     my $number=0;
 8866:     my $errormsg='';
 8867:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8868:         my %components=&Apache::loncommon::record_sep($line);
 8869:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8870: 	if ($entries[0] eq 'Question') {
 8871: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8872: 		$$questiontitles[$number]=$entries[$i];
 8873: 		$number++;
 8874: 	    }
 8875: 	}
 8876: 	if ($entries[0]=~/^\#/) {
 8877: 	    my $id=$entries[0];
 8878: 	    my @idresponses;
 8879: 	    $id=~s/^[\#0]+//;
 8880: 	    for (my $i=0;$i<$number;$i++) {
 8881: 		my $idx=3+$i*6;
 8882: 		push(@idresponses,$entries[$idx]);
 8883: 	    }
 8884: 	    $$responses{$id}=join(',',@idresponses);
 8885: 	}
 8886:     }
 8887:     return ($errormsg,$number);
 8888: }
 8889: 
 8890: sub interwrite_eval {
 8891:     my ($questiontitles,$responses)=@_;
 8892:     my $number=0;
 8893:     my $errormsg='';
 8894:     my $skipline=1;
 8895:     my $questionnumber=0;
 8896:     my %idresponses=();
 8897:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8898:         my %components=&Apache::loncommon::record_sep($line);
 8899:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8900:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8901:         if ($entries[1] eq 'Response') { $skipline=1; }
 8902:         next if $skipline;
 8903:         if ($entries[0]!=$questionnumber) {
 8904:            $questionnumber=$entries[0];
 8905:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8906:            $number++;
 8907:         }
 8908:         my $id=$entries[4];
 8909:         $id=~s/^[\#0]+//;
 8910:         $id=~s/^v\d*\://i;
 8911:         $id=~s/[\-\:]//g;
 8912:         $idresponses{$id}[$number]=$entries[6];
 8913:     }
 8914:     foreach my $id (keys(%idresponses)) {
 8915:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8916:        $$responses{$id}=~s/^\s*\,//;
 8917:     }
 8918:     return ($errormsg,$number);
 8919: }
 8920: 
 8921: sub assign_clicker_grades {
 8922:     my ($r)=@_;
 8923:     my ($symb)=&get_symb($r);
 8924:     if (!$symb) {return '';}
 8925: # See which part we are saving to
 8926:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8927: # FIXME: This should probably look for the first handgradeable part
 8928:     my $part=$$partlist[0];
 8929: # Start screen output
 8930:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8931: 
 8932:     my $heading=&mt('Assigning grades based on clicker file');
 8933:     $result.=(<<ENDHEADER);
 8934: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8935: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8936: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8937: ENDHEADER
 8938: # Get correct result
 8939: # FIXME: Possibly need delimiter other than ":"
 8940:     my @correct=();
 8941:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8942:     my $number=$env{'form.number'};
 8943:     if ($gradingmechanism ne 'attendance') {
 8944:        foreach my $key (keys(%env)) {
 8945:           if ($key=~/^form\.correct\:/) {
 8946:              my @input=split(/\,/,$env{$key});
 8947:              for (my $i=0;$i<=$#input;$i++) {
 8948:                  if (($correct[$i]) && ($input[$i]) &&
 8949:                      ($correct[$i] ne $input[$i])) {
 8950:                     $result.='<br /><span class="LC_warning">'.
 8951:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8952:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8953:                  } elsif ($input[$i]) {
 8954:                     $correct[$i]=$input[$i];
 8955:                  }
 8956:              }
 8957:           }
 8958:        }
 8959:        for (my $i=0;$i<$number;$i++) {
 8960:           if (!$correct[$i]) {
 8961:              $result.='<br /><span class="LC_error">'.
 8962:                       &mt('No correct result given for question "[_1]"!',
 8963:                           $env{'form.question:'.$i}).'</span>';
 8964:           }
 8965:        }
 8966:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8967:     }
 8968: # Start grading
 8969:     my $pcorrect=$env{'form.pcorrect'};
 8970:     my $pincorrect=$env{'form.pincorrect'};
 8971:     my $storecount=0;
 8972:     foreach my $key (keys(%env)) {
 8973:        my $user='';
 8974:        if ($key=~/^form\.student\:(.*)$/) {
 8975:           $user=$1;
 8976:        }
 8977:        if ($key=~/^form\.unknown\:(.*)$/) {
 8978:           my $id=$1;
 8979:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8980:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8981:           } elsif ($env{'form.multi'.$id}) {
 8982:              $user=$env{'form.multi'.$id};
 8983:           }
 8984:        }
 8985:        if ($user) { 
 8986:           my @answer=split(/\,/,$env{$key});
 8987:           my $sum=0;
 8988:           my $realnumber=$number;
 8989:           for (my $i=0;$i<$number;$i++) {
 8990:              if ($answer[$i]) {
 8991:                 if ($gradingmechanism eq 'attendance') {
 8992:                    $sum+=$pcorrect;
 8993:                 } elsif ($answer[$i] eq '*') {
 8994:                    $sum+=$pcorrect;
 8995:                 } elsif ($answer[$i] eq '-') {
 8996:                    $realnumber--;
 8997:                 } else {
 8998:                    if ($answer[$i] eq $correct[$i]) {
 8999:                       $sum+=$pcorrect;
 9000:                    } else {
 9001:                       $sum+=$pincorrect;
 9002:                    }
 9003:                 }
 9004:              }
 9005:           }
 9006:           my $ave=$sum/(100*$realnumber);
 9007: # Store
 9008:           my ($username,$domain)=split(/\:/,$user);
 9009:           my %grades=();
 9010:           $grades{"resource.$part.solved"}='correct_by_override';
 9011:           $grades{"resource.$part.awarded"}=$ave;
 9012:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9013:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9014:                                                  $env{'request.course.id'},
 9015:                                                  $domain,$username);
 9016:           if ($returncode ne 'ok') {
 9017:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9018:           } else {
 9019:              $storecount++;
 9020:           }
 9021:        }
 9022:     }
 9023: # We are done
 9024:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 9025:              '</td></tr></table>'."\n".
 9026:              '</td></tr></table><br /><br />'."\n";
 9027:     return $result.&show_grading_menu_form($symb);
 9028: }
 9029: 
 9030: sub handler {
 9031:     my $request=$_[0];
 9032:     &reset_caches();
 9033:     if ($env{'browser.mathml'}) {
 9034: 	&Apache::loncommon::content_type($request,'text/xml');
 9035:     } else {
 9036: 	&Apache::loncommon::content_type($request,'text/html');
 9037:     }
 9038:     $request->send_http_header;
 9039:     return '' if $request->header_only;
 9040:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9041:     my $symb=&get_symb($request,1);
 9042:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9043:     my $command=$commands[0];
 9044: 
 9045:     if ($#commands > 0) {
 9046: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9047:     }
 9048: 
 9049:     $ssi_error = 0;
 9050:     $request->print(&Apache::loncommon::start_page('Grading'));
 9051:     if ($symb eq '' && $command eq '') {
 9052: 	if ($env{'user.adv'}) {
 9053: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9054: 		($env{'form.codethree'})) {
 9055: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9056: 		    $env{'form.codethree'};
 9057: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9058: 		    &Apache::lonnet::checkin($token);
 9059: 		if ($tsymb) {
 9060: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9061: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9062: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9063: 					  ('grade_username' => $tuname,
 9064: 					   'grade_domain' => $tudom,
 9065: 					   'grade_courseid' => $tcrsid,
 9066: 					   'grade_symb' => $tsymb)));
 9067: 		    } else {
 9068: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9069: 		    }
 9070: 		} else {
 9071: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9072: 		}
 9073: 	    } else {
 9074: 		$request->print(&Apache::lonxml::tokeninputfield());
 9075: 	    }
 9076: 	}
 9077:     } else {
 9078: 	&init_perm();
 9079: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9080: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9081: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9082: 	    &pickStudentPage($request);
 9083: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9084: 	    &displayPage($request);
 9085: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9086: 	    &updateGradeByPage($request);
 9087: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9088: 	    &processGroup($request);
 9089: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9090: 	    $request->print(&grading_menu($request));
 9091: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9092: 	    $request->print(&submit_options($request));
 9093: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9094: 	    $request->print(&viewgrades($request));
 9095: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9096: 	    $request->print(&processHandGrade($request));
 9097: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9098: 	    $request->print(&editgrades($request));
 9099: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9100: 	    $request->print(&verifyreceipt($request));
 9101:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9102:             $request->print(&process_clicker($request));
 9103:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9104:             $request->print(&process_clicker_file($request));
 9105:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9106:             $request->print(&assign_clicker_grades($request));
 9107: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9108: 	    $request->print(&upcsvScores_form($request));
 9109: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9110: 	    $request->print(&csvupload($request));
 9111: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9112: 	    $request->print(&csvuploadmap($request));
 9113: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9114: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9115: 		$request->print(&csvuploadoptions($request));
 9116: 	    } else {
 9117: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9118: 		    $env{'form.upfile_associate'} = 'reverse';
 9119: 		} else {
 9120: 		    $env{'form.upfile_associate'} = 'forward';
 9121: 		}
 9122: 		$request->print(&csvuploadmap($request));
 9123: 	    }
 9124: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9125: 	    $request->print(&csvuploadassign($request));
 9126: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9127: 	    $request->print(&scantron_selectphase($request));
 9128:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9129:  	    $request->print(&scantron_do_warning($request));
 9130: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9131: 	    $request->print(&scantron_validate_file($request));
 9132: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9133: 	    $request->print(&scantron_process_students($request));
 9134:  	} elsif ($command eq 'scantronupload' && 
 9135:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9136: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9137:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9138:  	} elsif ($command eq 'scantronupload_save' &&
 9139:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9140: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9141:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9142:  	} elsif ($command eq 'scantron_download' &&
 9143: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9144:  	    $request->print(&scantron_download_scantron_data($request));
 9145:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9146:             $request->print(&checkscantron_results($request));     
 9147: 	} elsif ($command) {
 9148: 	    $request->print("Access Denied ($command)");
 9149: 	}
 9150:     }
 9151:     if ($ssi_error) {
 9152: 	&ssi_print_error($request);
 9153:     }
 9154:     $request->print(&Apache::loncommon::end_page());
 9155:     &reset_caches();
 9156:     return '';
 9157: }
 9158: 
 9159: 1;
 9160: 
 9161: __END__;

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