File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.520: download - view: text, annotated - select for diffs
Wed May 14 16:36:31 2008 UTC (15 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Session lock while scantron grading

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.520 2008/05/14 16:36:31 www 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)=@_;
  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: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  295: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  296: 	return $analyze_cache{$key} = \%analyze;
  297:     }
  298: 
  299:     sub get_order {
  300: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  301: 	my $analyze = &get_analyze($symb,$uname,$udom);
  302: 	return $analyze->{"$partid.$respid.shown"};
  303:     }
  304: 
  305:     sub get_radiobutton_correct_foil {
  306: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  307: 	my $analyze = &get_analyze($symb,$uname,$udom);
  308: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  309: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  310: 		return $foil;
  311: 	    }
  312: 	}
  313:     }
  314: }
  315: 
  316: #--- Clean response type for display
  317: #--- Currently filters option/rank/radiobutton/match/essay/Task
  318: #        response types only.
  319: sub cleanRecord {
  320:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  321: 	$uname,$udom) = @_;
  322:     my $grayFont = '<span class="LC_internal_info">';
  323:     if ($response =~ /^(option|rank)$/) {
  324: 	my %answer=&Apache::lonnet::str2hash($answer);
  325: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  326: 	my ($toprow,$bottomrow);
  327: 	foreach my $foil (@$order) {
  328: 	    if ($grading{$foil} == 1) {
  329: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  330: 	    } else {
  331: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  332: 	    }
  333: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  334: 	}
  335: 	return '<blockquote><table border="1">'.
  336: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  337: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  338: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  339:     } elsif ($response eq 'match') {
  340: 	my %answer=&Apache::lonnet::str2hash($answer);
  341: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  342: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  343: 	my ($toprow,$middlerow,$bottomrow);
  344: 	foreach my $foil (@$order) {
  345: 	    my $item=shift(@items);
  346: 	    if ($grading{$foil} == 1) {
  347: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  348: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  349: 	    } else {
  350: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  351: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  352: 	    }
  353: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  354: 	}
  355: 	return '<blockquote><table border="1">'.
  356: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  357: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  358: 	    $middlerow.'</tr>'.
  359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  360: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  361:     } elsif ($response eq 'radiobutton') {
  362: 	my %answer=&Apache::lonnet::str2hash($answer);
  363: 	my ($toprow,$bottomrow);
  364: 	my $correct = 
  365: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  366: 	foreach my $foil (@$order) {
  367: 	    if (exists($answer{$foil})) {
  368: 		if ($foil eq $correct) {
  369: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  370: 		} else {
  371: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  372: 		}
  373: 	    } else {
  374: 		$toprow.='<td>'.&mt('false').'</td>';
  375: 	    }
  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  377: 	}
  378: 	return '<blockquote><table border="1">'.
  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  381: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  382:     } elsif ($response eq 'essay') {
  383: 	if (! exists ($env{'form.'.$symb})) {
  384: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  385: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  386: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  387: 
  388: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  389: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  390: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  391: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  392: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  393: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  394: 	}
  395: 	$answer =~ s-\n-<br />-g;
  396: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  397:     } elsif ( $response eq 'organic') {
  398: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  399: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  400: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  401: 	return $result;
  402:     } elsif ( $response eq 'Task') {
  403: 	if ( $answer eq 'SUBMITTED') {
  404: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  405: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  406: 	    return $result;
  407: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  408: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  409: 			       keys(%{$record}));
  410: 	    return join('<br />',($version,@matches));
  411: 			       
  412: 			       
  413: 	} else {
  414: 	    my $result =
  415: 		'<p>'
  416: 		.&mt('Overall result: [_1]',
  417: 		     $record->{$version."resource.$respid.$partid.status"})
  418: 		.'</p>';
  419: 	    
  420: 	    $result .= '<ul>';
  421: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  422: 			     keys(%{$record}));
  423: 	    foreach my $grade (sort(@grade)) {
  424: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  425: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  426: 				     $dim, $record->{$grade}).
  427: 			  '</li>';
  428: 	    }
  429: 	    $result.='</ul>';
  430: 	    return $result;
  431: 	}
  432:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  433: 	$answer = 
  434: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  435: 							      $answer);
  436:     }
  437:     return $answer;
  438: }
  439: 
  440: #-- A couple of common js functions
  441: sub commonJSfunctions {
  442:     my $request = shift;
  443:     $request->print(<<COMMONJSFUNCTIONS);
  444: <script type="text/javascript" language="javascript">
  445:     function radioSelection(radioButton) {
  446: 	var selection=null;
  447: 	if (radioButton.length > 1) {
  448: 	    for (var i=0; i<radioButton.length; i++) {
  449: 		if (radioButton[i].checked) {
  450: 		    return radioButton[i].value;
  451: 		}
  452: 	    }
  453: 	} else {
  454: 	    if (radioButton.checked) return radioButton.value;
  455: 	}
  456: 	return selection;
  457:     }
  458: 
  459:     function pullDownSelection(selectOne) {
  460: 	var selection="";
  461: 	if (selectOne.length > 1) {
  462: 	    for (var i=0; i<selectOne.length; i++) {
  463: 		if (selectOne[i].selected) {
  464: 		    return selectOne[i].value;
  465: 		}
  466: 	    }
  467: 	} else {
  468:             // only one value it must be the selected one
  469: 	    return selectOne.value;
  470: 	}
  471:     }
  472: </script>
  473: COMMONJSFUNCTIONS
  474: }
  475: 
  476: #--- Dumps the class list with usernames,list of sections,
  477: #--- section, ids and fullnames for each user.
  478: sub getclasslist {
  479:     my ($getsec,$filterlist,$getgroup) = @_;
  480:     my @getsec;
  481:     my @getgroup;
  482:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  483:     if (!ref($getsec)) {
  484: 	if ($getsec ne '' && $getsec ne 'all') {
  485: 	    @getsec=($getsec);
  486: 	}
  487:     } else {
  488: 	@getsec=@{$getsec};
  489:     }
  490:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  491:     if (!ref($getgroup)) {
  492: 	if ($getgroup ne '' && $getgroup ne 'all') {
  493: 	    @getgroup=($getgroup);
  494: 	}
  495:     } else {
  496: 	@getgroup=@{$getgroup};
  497:     }
  498:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  499: 
  500:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  501:     # Bail out if we were unable to get the classlist
  502:     return if (! defined($classlist));
  503:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  504:     #
  505:     my %sections;
  506:     my %fullnames;
  507:     foreach my $student (keys(%$classlist)) {
  508:         my $end      = 
  509:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  510:         my $start    = 
  511:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  512:         my $id       = 
  513:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  514:         my $section  = 
  515:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  516:         my $fullname = 
  517:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  518:         my $status   = 
  519:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  520:         my $group   = 
  521:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  522: 	# filter students according to status selected
  523: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  524: 	    if (!($stu_status =~ $status)) {
  525: 		delete($classlist->{$student});
  526: 		next;
  527: 	    }
  528: 	}
  529: 	# filter students according to groups selected
  530: 	my @stu_groups = split(/,/,$group);
  531: 	if (@getgroup) {
  532: 	    my $exclude = 1;
  533: 	    foreach my $grp (@getgroup) {
  534: 	        foreach my $stu_group (@stu_groups) {
  535: 	            if ($stu_group eq $grp) {
  536: 	                $exclude = 0;
  537:     	            } 
  538: 	        }
  539:     	        if (($grp eq 'none') && !$group) {
  540:         	        $exclude = 0;
  541:         	}
  542: 	    }
  543: 	    if ($exclude) {
  544: 	        delete($classlist->{$student});
  545: 	    }
  546: 	}
  547: 	$section = ($section ne '' ? $section : 'none');
  548: 	if (&canview($section)) {
  549: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  550: 		$sections{$section}++;
  551: 		if ($classlist->{$student}) {
  552: 		    $fullnames{$student}=$fullname;
  553: 		}
  554: 	    } else {
  555: 		delete($classlist->{$student});
  556: 	    }
  557: 	} else {
  558: 	    delete($classlist->{$student});
  559: 	}
  560:     }
  561:     my %seen = ();
  562:     my @sections = sort(keys(%sections));
  563:     return ($classlist,\@sections,\%fullnames);
  564: }
  565: 
  566: sub canmodify {
  567:     my ($sec)=@_;
  568:     if ($perm{'mgr'}) {
  569: 	if (!defined($perm{'mgr_section'})) {
  570: 	    # can modify whole class
  571: 	    return 1;
  572: 	} else {
  573: 	    if ($sec eq $perm{'mgr_section'}) {
  574: 		#can modify the requested section
  575: 		return 1;
  576: 	    } else {
  577: 		# can't modify the request section
  578: 		return 0;
  579: 	    }
  580: 	}
  581:     }
  582:     #can't modify
  583:     return 0;
  584: }
  585: 
  586: sub canview {
  587:     my ($sec)=@_;
  588:     if ($perm{'vgr'}) {
  589: 	if (!defined($perm{'vgr_section'})) {
  590: 	    # can modify whole class
  591: 	    return 1;
  592: 	} else {
  593: 	    if ($sec eq $perm{'vgr_section'}) {
  594: 		#can modify the requested section
  595: 		return 1;
  596: 	    } else {
  597: 		# can't modify the request section
  598: 		return 0;
  599: 	    }
  600: 	}
  601:     }
  602:     #can't modify
  603:     return 0;
  604: }
  605: 
  606: #--- Retrieve the grade status of a student for all the parts
  607: sub student_gradeStatus {
  608:     my ($symb,$udom,$uname,$partlist) = @_;
  609:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  610:     my %partstatus = ();
  611:     foreach (@$partlist) {
  612: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  613: 	$status              = 'nothing' if ($status eq '');
  614: 	$partstatus{$_}      = $status;
  615: 	my $subkey           = "resource.$_.submitted_by";
  616: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  617:     }
  618:     return %partstatus;
  619: }
  620: 
  621: # hidden form and javascript that calls the form
  622: # Use by verifyscript and viewgrades
  623: # Shows a student's view of problem and submission
  624: sub jscriptNform {
  625:     my ($symb) = @_;
  626:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  627:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  628: 	'    function viewOneStudent(user,domain) {'."\n".
  629: 	'	document.onestudent.student.value = user;'."\n".
  630: 	'	document.onestudent.userdom.value = domain;'."\n".
  631: 	'	document.onestudent.submit();'."\n".
  632: 	'    }'."\n".
  633: 	'</script>'."\n";
  634:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  635: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  636: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  637: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  638: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  639: 	'<input type="hidden" name="command" value="submission" />'."\n".
  640: 	'<input type="hidden" name="student" value="" />'."\n".
  641: 	'<input type="hidden" name="userdom" value="" />'."\n".
  642: 	'</form>'."\n";
  643:     return $jscript;
  644: }
  645: 
  646: 
  647: 
  648: # Given the score (as a number [0-1] and the weight) what is the final
  649: # point value? This function will round to the nearest tenth, third,
  650: # or quarter if one of those is within the tolerance of .00001.
  651: sub compute_points {
  652:     my ($score, $weight) = @_;
  653:     
  654:     my $tolerance = .00001;
  655:     my $points = $score * $weight;
  656: 
  657:     # Check for nearness to 1/x.
  658:     my $check_for_nearness = sub {
  659:         my ($factor) = @_;
  660:         my $num = ($points * $factor) + $tolerance;
  661:         my $floored_num = floor($num);
  662:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  663:             return $floored_num / $factor;
  664:         }
  665:         return $points;
  666:     };
  667: 
  668:     $points = $check_for_nearness->(10);
  669:     $points = $check_for_nearness->(3);
  670:     $points = $check_for_nearness->(4);
  671:     
  672:     return $points;
  673: }
  674: 
  675: #------------------ End of general use routines --------------------
  676: 
  677: #
  678: # Find most similar essay
  679: #
  680: 
  681: sub most_similar {
  682:     my ($uname,$udom,$uessay,$old_essays)=@_;
  683: 
  684: # ignore spaces and punctuation
  685: 
  686:     $uessay=~s/\W+/ /gs;
  687: 
  688: # ignore empty submissions (occuring when only files are sent)
  689: 
  690:     unless ($uessay=~/\w+/) { return ''; }
  691: 
  692: # these will be returned. Do not care if not at least 50 percent similar
  693:     my $limit=0.6;
  694:     my $sname='';
  695:     my $sdom='';
  696:     my $scrsid='';
  697:     my $sessay='';
  698: # go through all essays ...
  699:     foreach my $tkey (keys(%$old_essays)) {
  700: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  701: # ... except the same student
  702:         next if (($tname eq $uname) && ($tdom eq $udom));
  703: 	my $tessay=$old_essays->{$tkey};
  704: 	$tessay=~s/\W+/ /gs;
  705: # String similarity gives up if not even limit
  706: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  707: # Found one
  708: 	if ($tsimilar>$limit) {
  709: 	    $limit=$tsimilar;
  710: 	    $sname=$tname;
  711: 	    $sdom=$tdom;
  712: 	    $scrsid=$tcrsid;
  713: 	    $sessay=$old_essays->{$tkey};
  714: 	}
  715:     }
  716:     if ($limit>0.6) {
  717:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  718:     } else {
  719:        return ('','','','',0);
  720:     }
  721: }
  722: 
  723: #-------------------------------------------------------------------
  724: 
  725: #------------------------------------ Receipt Verification Routines
  726: #
  727: #--- Check whether a receipt number is valid.---
  728: sub verifyreceipt {
  729:     my $request  = shift;
  730: 
  731:     my $courseid = $env{'request.course.id'};
  732:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  733: 	$env{'form.receipt'};
  734:     $receipt     =~ s/[^\-\d]//g;
  735:     my ($symb)   = &get_symb($request);
  736: 
  737:     my $title.=
  738: 	'<h3><span class="LC_info">'.
  739: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  740: 	'</span></h3>'."\n".
  741: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  742: 	'</h4>'."\n";
  743: 
  744:     my ($string,$contents,$matches) = ('','',0);
  745:     my (undef,undef,$fullname) = &getclasslist('all','0');
  746:     
  747:     my $receiptparts=0;
  748:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  749: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  750:     my $parts=['0'];
  751:     if ($receiptparts) { ($parts)=&response_type($symb); }
  752:     
  753:     my $header = 
  754: 	&Apache::loncommon::start_data_table().
  755: 	&Apache::loncommon::start_data_table_header_row().
  756: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  757: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  758: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  759:     if ($receiptparts) {
  760: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  761:     }
  762:     $header.=
  763: 	&Apache::loncommon::end_data_table_header_row();
  764: 
  765:     foreach (sort 
  766: 	     {
  767: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  768: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  769: 		 }
  770: 		 return $a cmp $b;
  771: 	     } (keys(%$fullname))) {
  772: 	my ($uname,$udom)=split(/\:/);
  773: 	foreach my $part (@$parts) {
  774: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  775: 		$contents.=
  776: 		    &Apache::loncommon::start_data_table_row().
  777: 		    '<td>&nbsp;'."\n".
  778: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  779: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  780: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  781: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  782: 		if ($receiptparts) {
  783: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  784: 		}
  785: 		$contents.= 
  786: 		    &Apache::loncommon::end_data_table_row()."\n";
  787: 		
  788: 		$matches++;
  789: 	    }
  790: 	}
  791:     }
  792:     if ($matches == 0) {
  793: 	$string = $title.&mt('No match found for the above receipt.');
  794:     } else {
  795: 	$string = &jscriptNform($symb).$title.
  796: 	    '<p>'.
  797: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  798: 	    '</p>'.
  799: 	    $header.
  800: 	    $contents.
  801: 	    &Apache::loncommon::end_data_table()."\n";
  802:     }
  803:     return $string.&show_grading_menu_form($symb);
  804: }
  805: 
  806: #--- This is called by a number of programs.
  807: #--- Called from the Grading Menu - View/Grade an individual student
  808: #--- Also called directly when one clicks on the subm button 
  809: #    on the problem page.
  810: sub listStudents {
  811:     my ($request) = shift;
  812: 
  813:     my ($symb) = &get_symb($request);
  814:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  815:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  816:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  817:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  818:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  819:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  820:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  821: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  822: 
  823:     my $result='<h3><span class="LC_info">&nbsp;'.
  824: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  825: 	.'</span></h3>';
  826: 
  827:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  828: 
  829:     my %lt = ( 'multiple' =>
  830: 	       "Please select a student or group of students before clicking on the Next button.",
  831: 	       'single'   =>
  832: 	       "Please select the student before clicking on the Next button.",
  833: 	       );
  834:     %lt = &Apache::lonlocal::texthash(%lt);
  835:     $request->print(<<LISTJAVASCRIPT);
  836: <script type="text/javascript" language="javascript">
  837:     function checkSelect(checkBox) {
  838: 	var ctr=0;
  839: 	var sense="";
  840: 	if (checkBox.length > 1) {
  841: 	    for (var i=0; i<checkBox.length; i++) {
  842: 		if (checkBox[i].checked) {
  843: 		    ctr++;
  844: 		}
  845: 	    }
  846: 	    sense = '$lt{'multiple'}';
  847: 	} else {
  848: 	    if (checkBox.checked) {
  849: 		ctr = 1;
  850: 	    }
  851: 	    sense = '$lt{'single'}';
  852: 	}
  853: 	if (ctr == 0) {
  854: 	    alert(sense);
  855: 	    return false;
  856: 	}
  857: 	document.gradesub.submit();
  858:     }
  859: 
  860:     function reLoadList(formname) {
  861: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  862: 	formname.command.value = 'submission';
  863: 	formname.submit();
  864:     }
  865: </script>
  866: LISTJAVASCRIPT
  867: 
  868:     &commonJSfunctions($request);
  869:     $request->print($result);
  870: 
  871:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  872:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  873:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  874: 	"\n".$table;
  875: 	
  876:     $gradeTable .= 
  877: 	'&nbsp;'.
  878: 	&mt('<b>View Problem Text: </b>[_1]',
  879: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  880: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  881: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
  882:     $gradeTable .= 
  883: 	'&nbsp;'.
  884: 	&mt('<b>View Answer: </b>[_1]',
  885: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  886: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  887: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
  888: 
  889:     my $submission_options;
  890:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  891: 	$submission_options.=
  892: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  893:     }
  894:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  895:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  896:     $env{'form.Status'} = $saveStatus;
  897:     $submission_options.=
  898: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  899: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  900: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  901: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  902:     $gradeTable .= 
  903: 	'&nbsp;'.
  904: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
  905: 
  906:     $gradeTable .= 
  907:         '&nbsp;'.
  908: 	&mt('<b>Grading Increments:</b> [_1]',
  909: 	    '<select name="increment">'.
  910: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  911: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  912: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  913: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  914: 	    '</select>');
  915:     
  916:     $gradeTable .= 
  917:         &build_section_inputs().
  918: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  919: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  920: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  921: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  922: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  923: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  924: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  925: 
  926:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  927: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  928:     } else {
  929: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  930: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  931:     }
  932: 
  933:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  934: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
  935: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  936: 
  937: # checkall buttons
  938:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  939:     $gradeTable.='<input type="button" '."\n".
  940: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  941: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
  942:     $gradeTable.=&check_buttons();
  943:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  944:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  945:     $gradeTable.= &Apache::loncommon::start_data_table().
  946: 	&Apache::loncommon::start_data_table_header_row();
  947:     my $loop = 0;
  948:     while ($loop < 2) {
  949: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  950: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  951: 	if ($env{'form.showgrading'} eq 'yes' 
  952: 	    && $submitonly ne 'queued'
  953: 	    && $submitonly ne 'all') {
  954: 	    foreach my $part (sort(@$partlist)) {
  955: 		my $display_part=
  956: 		    &get_display_part((split(/_/,$part))[0],$symb);
  957: 		$gradeTable.=
  958: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  959: 	    }
  960: 	} elsif ($submitonly eq 'queued') {
  961: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  962: 	}
  963: 	$loop++;
  964: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  965:     }
  966:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  967: 
  968:     my $ctr = 0;
  969:     foreach my $student (sort 
  970: 			 {
  971: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  972: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  973: 			     }
  974: 			     return $a cmp $b;
  975: 			 }
  976: 			 (keys(%$fullname))) {
  977: 	my ($uname,$udom) = split(/:/,$student);
  978: 
  979: 	my %status = ();
  980: 
  981: 	if ($submitonly eq 'queued') {
  982: 	    my %queue_status = 
  983: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  984: 							$udom,$uname);
  985: 	    next if (!defined($queue_status{'gradingqueue'}));
  986: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  987: 	}
  988: 
  989: 	if ($env{'form.showgrading'} eq 'yes' 
  990: 	    && $submitonly ne 'queued'
  991: 	    && $submitonly ne 'all') {
  992: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  993: 	    my $submitted = 0;
  994: 	    my $graded = 0;
  995: 	    my $incorrect = 0;
  996: 	    foreach (keys(%status)) {
  997: 		$submitted = 1 if ($status{$_} ne 'nothing');
  998: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  999: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1000: 		
 1001: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1002: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1003: 		    $submitted = 0;
 1004: 		    my ($part)=split(/\./,$partid);
 1005: 		    $gradeTable.='<input type="hidden" name="'.
 1006: 			$student.':'.$part.':submitted_by" value="'.
 1007: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1008: 		}
 1009: 	    }
 1010: 	    
 1011: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1012: 				     $submitonly eq 'incorrect' ||
 1013: 				     $submitonly eq 'graded'));
 1014: 	    next if (!$graded && ($submitonly eq 'graded'));
 1015: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1016: 	}
 1017: 
 1018: 	$ctr++;
 1019: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1020:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1021: 	if ( $perm{'vgr'} eq 'F' ) {
 1022: 	    if ($ctr%2 ==1) {
 1023: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1024: 	    }
 1025: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1026:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1027:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1028: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1029: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1030: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1031: 
 1032: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1033: 		foreach (sort keys(%status)) {
 1034: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1035: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1036: 		}
 1037: 	    }
 1038: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1039: 	    if ($ctr%2 ==0) {
 1040: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1041: 	    }
 1042: 	}
 1043:     }
 1044:     if ($ctr%2 ==1) {
 1045: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1046: 	    if ($env{'form.showgrading'} eq 'yes' 
 1047: 		&& $submitonly ne 'queued'
 1048: 		&& $submitonly ne 'all') {
 1049: 		foreach (@$partlist) {
 1050: 		    $gradeTable.='<td>&nbsp;</td>';
 1051: 		}
 1052: 	    } elsif ($submitonly eq 'queued') {
 1053: 		$gradeTable.='<td>&nbsp;</td>';
 1054: 	    }
 1055: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1056:     }
 1057: 
 1058:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1059: 	'<input type="button" '.
 1060: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1061: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1062:     if ($ctr == 0) {
 1063: 	my $num_students=(scalar(keys(%$fullname)));
 1064: 	if ($num_students eq 0) {
 1065: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1066: 	} else {
 1067: 	    my $submissions='submissions';
 1068: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1069: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1070: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1072: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1073: 		    $num_students).
 1074: 		'</span><br />';
 1075: 	}
 1076:     } elsif ($ctr == 1) {
 1077: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1078:     }
 1079:     $gradeTable.=&show_grading_menu_form($symb);
 1080:     $request->print($gradeTable);
 1081:     return '';
 1082: }
 1083: 
 1084: #---- Called from the listStudents routine
 1085: 
 1086: sub check_script {
 1087:     my ($form, $type)=@_;
 1088:     my $chkallscript='<script type="text/javascript">
 1089:     function checkall() {
 1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1091:             ele = document.forms.'.$form.'.elements[i];
 1092:             if (ele.name == "'.$type.'") {
 1093:             document.forms.'.$form.'.elements[i].checked=true;
 1094:                                        }
 1095:         }
 1096:     }
 1097: 
 1098:     function checksec() {
 1099:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1100:             ele = document.forms.'.$form.'.elements[i];
 1101:            string = document.forms.'.$form.'.chksec.value;
 1102:            if
 1103:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1104:               document.forms.'.$form.'.elements[i].checked=true;
 1105:             }
 1106:         }
 1107:     }
 1108: 
 1109: 
 1110:     function uncheckall() {
 1111:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1112:             ele = document.forms.'.$form.'.elements[i];
 1113:             if (ele.name == "'.$type.'") {
 1114:             document.forms.'.$form.'.elements[i].checked=false;
 1115:                                        }
 1116:         }
 1117:     }
 1118: 
 1119: </script>'."\n";
 1120:     return $chkallscript;
 1121: }
 1122: 
 1123: sub check_buttons {
 1124:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1125:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1126:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1127:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1128:     return $buttons;
 1129: }
 1130: 
 1131: #     Displays the submissions for one student or a group of students
 1132: sub processGroup {
 1133:     my ($request)  = shift;
 1134:     my $ctr        = 0;
 1135:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1136:     my $total      = scalar(@stuchecked)-1;
 1137: 
 1138:     foreach my $student (@stuchecked) {
 1139: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1140: 	$env{'form.student'}        = $uname;
 1141: 	$env{'form.userdom'}        = $udom;
 1142: 	$env{'form.fullname'}       = $fullname;
 1143: 	&submission($request,$ctr,$total);
 1144: 	$ctr++;
 1145:     }
 1146:     return '';
 1147: }
 1148: 
 1149: #------------------------------------------------------------------------------------
 1150: #
 1151: #-------------------------- Next few routines handles grading by student, essentially
 1152: #                           handles essay response type problem/part
 1153: #
 1154: #--- Javascript to handle the submission page functionality ---
 1155: sub sub_page_js {
 1156:     my $request = shift;
 1157:     $request->print(<<SUBJAVASCRIPT);
 1158: <script type="text/javascript" language="javascript">
 1159:     function updateRadio(formname,id,weight) {
 1160: 	var gradeBox = formname["GD_BOX"+id];
 1161: 	var radioButton = formname["RADVAL"+id];
 1162: 	var oldpts = formname["oldpts"+id].value;
 1163: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1164: 	gradeBox.value = pts;
 1165: 	var resetbox = false;
 1166: 	if (isNaN(pts) || pts < 0) {
 1167: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1168: 	    for (var i=0; i<radioButton.length; i++) {
 1169: 		if (radioButton[i].checked) {
 1170: 		    gradeBox.value = i;
 1171: 		    resetbox = true;
 1172: 		}
 1173: 	    }
 1174: 	    if (!resetbox) {
 1175: 		formtextbox.value = "";
 1176: 	    }
 1177: 	    return;
 1178: 	}
 1179: 
 1180: 	if (pts > weight) {
 1181: 	    var resp = confirm("You entered a value ("+pts+
 1182: 			       ") greater than the weight for the part. Accept?");
 1183: 	    if (resp == false) {
 1184: 		gradeBox.value = oldpts;
 1185: 		return;
 1186: 	    }
 1187: 	}
 1188: 
 1189: 	for (var i=0; i<radioButton.length; i++) {
 1190: 	    radioButton[i].checked=false;
 1191: 	    if (pts == i && pts != "") {
 1192: 		radioButton[i].checked=true;
 1193: 	    }
 1194: 	}
 1195: 	updateSelect(formname,id);
 1196: 	formname["stores"+id].value = "0";
 1197:     }
 1198: 
 1199:     function writeBox(formname,id,pts) {
 1200: 	var gradeBox = formname["GD_BOX"+id];
 1201: 	if (checkSolved(formname,id) == 'update') {
 1202: 	    gradeBox.value = pts;
 1203: 	} else {
 1204: 	    var oldpts = formname["oldpts"+id].value;
 1205: 	    gradeBox.value = oldpts;
 1206: 	    var radioButton = formname["RADVAL"+id];
 1207: 	    for (var i=0; i<radioButton.length; i++) {
 1208: 		radioButton[i].checked=false;
 1209: 		if (i == oldpts) {
 1210: 		    radioButton[i].checked=true;
 1211: 		}
 1212: 	    }
 1213: 	}
 1214: 	formname["stores"+id].value = "0";
 1215: 	updateSelect(formname,id);
 1216: 	return;
 1217:     }
 1218: 
 1219:     function clearRadBox(formname,id) {
 1220: 	if (checkSolved(formname,id) == 'noupdate') {
 1221: 	    updateSelect(formname,id);
 1222: 	    return;
 1223: 	}
 1224: 	gradeSelect = formname["GD_SEL"+id];
 1225: 	for (var i=0; i<gradeSelect.length; i++) {
 1226: 	    if (gradeSelect[i].selected) {
 1227: 		var selectx=i;
 1228: 	    }
 1229: 	}
 1230: 	var stores = formname["stores"+id];
 1231: 	if (selectx == stores.value) { return };
 1232: 	var gradeBox = formname["GD_BOX"+id];
 1233: 	gradeBox.value = "";
 1234: 	var radioButton = formname["RADVAL"+id];
 1235: 	for (var i=0; i<radioButton.length; i++) {
 1236: 	    radioButton[i].checked=false;
 1237: 	}
 1238: 	stores.value = selectx;
 1239:     }
 1240: 
 1241:     function checkSolved(formname,id) {
 1242: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1243: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1244: 	    if (!reply) {return "noupdate";}
 1245: 	    formname.overRideScore.value = 'yes';
 1246: 	}
 1247: 	return "update";
 1248:     }
 1249: 
 1250:     function updateSelect(formname,id) {
 1251: 	formname["GD_SEL"+id][0].selected = true;
 1252: 	return;
 1253:     }
 1254: 
 1255: //=========== Check that a point is assigned for all the parts  ============
 1256:     function checksubmit(formname,val,total,parttot) {
 1257: 	formname.gradeOpt.value = val;
 1258: 	if (val == "Save & Next") {
 1259: 	    for (i=0;i<=total;i++) {
 1260: 		for (j=0;j<parttot;j++) {
 1261: 		    var partid = formname["partid"+i+"_"+j].value;
 1262: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1263: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1264: 			if (points == "") {
 1265: 			    var name = formname["name"+i].value;
 1266: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1267: 			    var resp = confirm("You did not assign a score for "+studentID+
 1268: 					       ", part "+partid+". Continue?");
 1269: 			    if (resp == false) {
 1270: 				formname["GD_BOX"+i+"_"+partid].focus();
 1271: 				return false;
 1272: 			    }
 1273: 			}
 1274: 		    }
 1275: 		    
 1276: 		}
 1277: 	    }
 1278: 	    
 1279: 	}
 1280: 	if (val == "Grade Student") {
 1281: 	    formname.showgrading.value = "yes";
 1282: 	    if (formname.Status.value == "") {
 1283: 		formname.Status.value = "Active";
 1284: 	    }
 1285: 	    formname.studentNo.value = total;
 1286: 	}
 1287: 	formname.submit();
 1288:     }
 1289: 
 1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1291:     function checkSubmitPage(formname,total) {
 1292: 	noscore = new Array(100);
 1293: 	var ptr = 0;
 1294: 	for (i=1;i<total;i++) {
 1295: 	    var partid = formname["q_"+i].value;
 1296: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1297: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1298: 		var status = formname["solved"+i+"_"+partid].value;
 1299: 		if (points == "" && status != "correct_by_student") {
 1300: 		    noscore[ptr] = i;
 1301: 		    ptr++;
 1302: 		}
 1303: 	    }
 1304: 	}
 1305: 	if (ptr != 0) {
 1306: 	    var sense = ptr == 1 ? ": " : "s: ";
 1307: 	    var prolist = "";
 1308: 	    if (ptr == 1) {
 1309: 		prolist = noscore[0];
 1310: 	    } else {
 1311: 		var i = 0;
 1312: 		while (i < ptr-1) {
 1313: 		    prolist += noscore[i]+", ";
 1314: 		    i++;
 1315: 		}
 1316: 		prolist += "and "+noscore[i];
 1317: 	    }
 1318: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1319: 	    if (resp == false) {
 1320: 		return false;
 1321: 	    }
 1322: 	}
 1323: 
 1324: 	formname.submit();
 1325:     }
 1326: </script>
 1327: SUBJAVASCRIPT
 1328: }
 1329: 
 1330: #--- javascript for essay type problem --
 1331: sub sub_page_kw_js {
 1332:     my $request = shift;
 1333:     my $iconpath = $request->dir_config('lonIconsURL');
 1334:     &commonJSfunctions($request);
 1335: 
 1336:     my $inner_js_msg_central=<<INNERJS;
 1337:     <script text="text/javascript">
 1338:     function checkInput() {
 1339:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1340:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1341:       var usrctr = document.msgcenter.usrctr.value;
 1342:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1343:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1344: 
 1345:       var msgchk = "";
 1346:       if (document.msgcenter.subchk.checked) {
 1347:          msgchk = "msgsub,";
 1348:       }
 1349:       var includemsg = 0;
 1350:       for (var i=1; i<=nmsg; i++) {
 1351:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1352:           var frmmsg = document.msgcenter["msg"+i];
 1353:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1354:           var showflg = opener.document.SCORE["shownOnce"+i];
 1355:           showflg.value = "1";
 1356:           var chkbox = document.msgcenter["msgn"+i];
 1357:           if (chkbox.checked) {
 1358:              msgchk += "savemsg"+i+",";
 1359:              includemsg = 1;
 1360:           }
 1361:       }
 1362:       if (document.msgcenter.newmsgchk.checked) {
 1363:          msgchk += "newmsg"+usrctr;
 1364:          includemsg = 1;
 1365:       }
 1366:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1367:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1368:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1369:       includemsg.value = msgchk;
 1370: 
 1371:       self.close()
 1372: 
 1373:     }
 1374:     </script>
 1375: INNERJS
 1376: 
 1377:     my $inner_js_highlight_central=<<INNERJS;
 1378:  <script type="text/javascript">
 1379:     function updateChoice(flag) {
 1380:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1381:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1382:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1383:       opener.document.SCORE.refresh.value = "on";
 1384:       if (opener.document.SCORE.keywords.value!=""){
 1385:          opener.document.SCORE.submit();
 1386:       }
 1387:       self.close()
 1388:     }
 1389: </script>
 1390: INNERJS
 1391: 
 1392:     my $start_page_msg_central = 
 1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1394: 				       {'js_ready'  => 1,
 1395: 					'only_body' => 1,
 1396: 					'bgcolor'   =>'#FFFFFF',});
 1397:     my $end_page_msg_central = 
 1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1399: 
 1400: 
 1401:     my $start_page_highlight_central = 
 1402:         &Apache::loncommon::start_page('Highlight Central',
 1403: 				       $inner_js_highlight_central,
 1404: 				       {'js_ready'  => 1,
 1405: 					'only_body' => 1,
 1406: 					'bgcolor'   =>'#FFFFFF',});
 1407:     my $end_page_highlight_central = 
 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1409: 
 1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1411:     $docopen=~s/^document\.//;
 1412:     $request->print(<<SUBJAVASCRIPT);
 1413: <script type="text/javascript" language="javascript">
 1414: 
 1415: //===================== Show list of keywords ====================
 1416:   function keywords(formname) {
 1417:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1418:     if (nret==null) return;
 1419:     formname.keywords.value = nret;
 1420: 
 1421:     if (formname.keywords.value != "") {
 1422: 	formname.refresh.value = "on";
 1423: 	formname.submit();
 1424:     }
 1425:     return;
 1426:   }
 1427: 
 1428: //===================== Script to view submitted by ==================
 1429:   function viewSubmitter(submitter) {
 1430:     document.SCORE.refresh.value = "on";
 1431:     document.SCORE.NCT.value = "1";
 1432:     document.SCORE.unamedom0.value = submitter;
 1433:     document.SCORE.submit();
 1434:     return;
 1435:   }
 1436: 
 1437: //===================== Script to add keyword(s) ==================
 1438:   function getSel() {
 1439:     if (document.getSelection) txt = document.getSelection();
 1440:     else if (document.selection) txt = document.selection.createRange().text;
 1441:     else return;
 1442:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1443:     if (cleantxt=="") {
 1444: 	alert("Please select a word or group of words from document and then click this link.");
 1445: 	return;
 1446:     }
 1447:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1448:     if (nret==null) return;
 1449:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1450:     if (document.SCORE.keywords.value != "") {
 1451: 	document.SCORE.refresh.value = "on";
 1452: 	document.SCORE.submit();
 1453:     }
 1454:     return;
 1455:   }
 1456: 
 1457: //====================== Script for composing message ==============
 1458:    // preload images
 1459:    img1 = new Image();
 1460:    img1.src = "$iconpath/mailbkgrd.gif";
 1461:    img2 = new Image();
 1462:    img2.src = "$iconpath/mailto.gif";
 1463: 
 1464:   function msgCenter(msgform,usrctr,fullname) {
 1465:     var Nmsg  = msgform.savemsgN.value;
 1466:     savedMsgHeader(Nmsg,usrctr,fullname);
 1467:     var subject = msgform.msgsub.value;
 1468:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1469:     re = /msgsub/;
 1470:     var shwsel = "";
 1471:     if (re.test(msgchk)) { shwsel = "checked" }
 1472:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1473:     displaySubject(checkEntities(subject),shwsel);
 1474:     for (var i=1; i<=Nmsg; i++) {
 1475: 	var testmsg = "savemsg"+i+",";
 1476: 	re = new RegExp(testmsg,"g");
 1477: 	shwsel = "";
 1478: 	if (re.test(msgchk)) { shwsel = "checked" }
 1479: 	var message = document.SCORE["savemsg"+i].value;
 1480: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1481: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1482: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1483:     }
 1484:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1485:     shwsel = "";
 1486:     re = /newmsg/;
 1487:     if (re.test(msgchk)) { shwsel = "checked" }
 1488:     newMsg(newmsg,shwsel);
 1489:     msgTail(); 
 1490:     return;
 1491:   }
 1492: 
 1493:   function checkEntities(strx) {
 1494:     if (strx.length == 0) return strx;
 1495:     var orgStr = ["&", "<", ">", '"']; 
 1496:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1497:     var counter = 0;
 1498:     while (counter < 4) {
 1499: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1500: 	counter++;
 1501:     }
 1502:     return strx;
 1503:   }
 1504: 
 1505:   function strReplace(strx, orgStr, newStr) {
 1506:     return strx.split(orgStr).join(newStr);
 1507:   }
 1508: 
 1509:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1510:     var height = 70*Nmsg+250;
 1511:     var scrollbar = "no";
 1512:     if (height > 600) {
 1513: 	height = 600;
 1514: 	scrollbar = "yes";
 1515:     }
 1516:     var xpos = (screen.width-600)/2;
 1517:     xpos = (xpos < 0) ? '0' : xpos;
 1518:     var ypos = (screen.height-height)/2-30;
 1519:     ypos = (ypos < 0) ? '0' : ypos;
 1520: 
 1521:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1522:     pWin.focus();
 1523:     pDoc = pWin.document;
 1524:     pDoc.$docopen;
 1525:     pDoc.write('$start_page_msg_central');
 1526: 
 1527:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1528:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1529:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1530: 
 1531:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1532:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1533:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1534: }
 1535:     function displaySubject(msg,shwsel) {
 1536:     pDoc = pWin.document;
 1537:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1538:     pDoc.write("<td>Subject<\\/td>");
 1539:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1540:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1541: }
 1542: 
 1543:   function displaySavedMsg(ctr,msg,shwsel) {
 1544:     pDoc = pWin.document;
 1545:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1546:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1547:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1548:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1549: }
 1550: 
 1551:   function newMsg(newmsg,shwsel) {
 1552:     pDoc = pWin.document;
 1553:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1554:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1555:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1556:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1557: }
 1558: 
 1559:   function msgTail() {
 1560:     pDoc = pWin.document;
 1561:     pDoc.write("<\\/table>");
 1562:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1563:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1564:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1565:     pDoc.write("<\\/form>");
 1566:     pDoc.write('$end_page_msg_central');
 1567:     pDoc.close();
 1568: }
 1569: 
 1570: //====================== Script for keyword highlight options ==============
 1571:   function kwhighlight() {
 1572:     var kwclr    = document.SCORE.kwclr.value;
 1573:     var kwsize   = document.SCORE.kwsize.value;
 1574:     var kwstyle  = document.SCORE.kwstyle.value;
 1575:     var redsel = "";
 1576:     var grnsel = "";
 1577:     var blusel = "";
 1578:     if (kwclr=="red")   {var redsel="checked"};
 1579:     if (kwclr=="green") {var grnsel="checked"};
 1580:     if (kwclr=="blue")  {var blusel="checked"};
 1581:     var sznsel = "";
 1582:     var sz1sel = "";
 1583:     var sz2sel = "";
 1584:     if (kwsize=="0")  {var sznsel="checked"};
 1585:     if (kwsize=="+1") {var sz1sel="checked"};
 1586:     if (kwsize=="+2") {var sz2sel="checked"};
 1587:     var synsel = "";
 1588:     var syisel = "";
 1589:     var sybsel = "";
 1590:     if (kwstyle=="")    {var synsel="checked"};
 1591:     if (kwstyle=="<i>") {var syisel="checked"};
 1592:     if (kwstyle=="<b>") {var sybsel="checked"};
 1593:     highlightCentral();
 1594:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1595:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1596:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1597:     highlightend();
 1598:     return;
 1599:   }
 1600: 
 1601:   function highlightCentral() {
 1602: //    if (window.hwdWin) window.hwdWin.close();
 1603:     var xpos = (screen.width-400)/2;
 1604:     xpos = (xpos < 0) ? '0' : xpos;
 1605:     var ypos = (screen.height-330)/2-30;
 1606:     ypos = (ypos < 0) ? '0' : ypos;
 1607: 
 1608:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1609:     hwdWin.focus();
 1610:     var hDoc = hwdWin.document;
 1611:     hDoc.$docopen;
 1612:     hDoc.write('$start_page_highlight_central');
 1613:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1614:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1615: 
 1616:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1617:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1618:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1619:   }
 1620: 
 1621:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1622:     var hDoc = hwdWin.document;
 1623:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1624:     hDoc.write("<td align=\\"left\\">");
 1625:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1626:     hDoc.write("<td align=\\"left\\">");
 1627:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1628:     hDoc.write("<td align=\\"left\\">");
 1629:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1630:     hDoc.write("<\\/tr>");
 1631:   }
 1632: 
 1633:   function highlightend() { 
 1634:     var hDoc = hwdWin.document;
 1635:     hDoc.write("<\\/table>");
 1636:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1637:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1638:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1639:     hDoc.write("<\\/form>");
 1640:     hDoc.write('$end_page_highlight_central');
 1641:     hDoc.close();
 1642:   }
 1643: 
 1644: </script>
 1645: SUBJAVASCRIPT
 1646: }
 1647: 
 1648: sub get_increment {
 1649:     my $increment = $env{'form.increment'};
 1650:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1651:         $increment != .1) {
 1652:         $increment = 1;
 1653:     }
 1654:     return $increment;
 1655: }
 1656: 
 1657: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1658: sub gradeBox {
 1659:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1660:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1661: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1662:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1663:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1664:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1665:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1666:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1667: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1668:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1669:     my $display_part= &get_display_part($partid,$symb);
 1670:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1671: 				       [$partid]);
 1672:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1673:     if ($last_resets{$partid}) {
 1674:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1675:     }
 1676:     $result.='<table border="0"><tr>';
 1677:     my $ctr = 0;
 1678:     my $thisweight = 0;
 1679:     my $increment = &get_increment();
 1680: 
 1681:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1682:     while ($thisweight<=$wgt) {
 1683: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1684: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1685: 	    $thisweight.')" value="'.$thisweight.'" '.
 1686: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1687: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1688:         $thisweight += $increment;
 1689: 	$ctr++;
 1690:     }
 1691:     $radio.='</tr></table>';
 1692: 
 1693:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1694: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1695: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1696: 	$wgt.')" /></td>'."\n";
 1697:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1698: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1699: 	' </td><td>'."\n";
 1700:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1701: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1702:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1703: 	$line.='<option></option>'.
 1704: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1705:     } else {
 1706: 	$line.='<option selected="selected"></option>'.
 1707: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1708:     }
 1709:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1710: 
 1711: 
 1712:     $result .= 
 1713: 	&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);
 1714: 
 1715:     
 1716:     $result.='</tr></table>'."\n";
 1717:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1718: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1719: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1720: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1721:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1722:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1723:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1724:         $aggtries.'" />'."\n";
 1725:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1726:     return $result;
 1727: }
 1728: 
 1729: sub handback_box {
 1730:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1731:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1732:     my (@respids);
 1733:      my @part_response_id = &flatten_responseType($responseType);
 1734:     foreach my $part_response_id (@part_response_id) {
 1735:     	my ($part,$resp) = @{ $part_response_id };
 1736:         if ($part eq $partid) {
 1737:             push(@respids,$resp);
 1738:         }
 1739:     }
 1740:     my $result;
 1741:     foreach my $respid (@respids) {
 1742: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1743: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1744: 	next if (!@$files);
 1745: 	my $file_counter = 1;
 1746: 	foreach my $file (@$files) {
 1747: 	    if ($file =~ /\/portfolio\//) {
 1748:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1749:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1750:     	        $file_disp = "$name.$ext";
 1751:     	        $file = $file_path.$file_disp;
 1752:     	        $result.=&mt('Return commented version of [_1] to student.',
 1753:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1754:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1755:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1756:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1757:     	        $file_counter++;
 1758: 	    }
 1759: 	}
 1760:     }
 1761:     return $result;    
 1762: }
 1763: 
 1764: sub show_problem {
 1765:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1766:     my $rendered;
 1767:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1768:     &Apache::lonxml::remember_problem_counter();
 1769:     if ($mode eq 'both' or $mode eq 'text') {
 1770: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1771: 						       $env{'request.course.id'},
 1772: 						       undef,\%form);
 1773:     }
 1774:     if ($removeform) {
 1775: 	$rendered=~s|<form(.*?)>||g;
 1776: 	$rendered=~s|</form>||g;
 1777: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1778:     }
 1779:     my $companswer;
 1780:     if ($mode eq 'both' or $mode eq 'answer') {
 1781: 	&Apache::lonxml::restore_problem_counter();
 1782: 	$companswer=
 1783: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1784: 						    $env{'request.course.id'},
 1785: 						    %form);
 1786:     }
 1787:     if ($removeform) {
 1788: 	$companswer=~s|<form(.*?)>||g;
 1789: 	$companswer=~s|</form>||g;
 1790: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1791:     }
 1792:     $rendered=
 1793: 	'<div class="LC_grade_show_problem_header">'.
 1794: 	&mt('View of the problem').
 1795: 	'</div><div class="LC_grade_show_problem_problem">'.
 1796: 	$rendered.
 1797: 	'</div>';
 1798:     $companswer=
 1799: 	'<div class="LC_grade_show_problem_header">'.
 1800: 	&mt('Correct answer').
 1801: 	'</div><div class="LC_grade_show_problem_problem">'.
 1802: 	$companswer.
 1803: 	'</div>';
 1804:     my $result;
 1805:     if ($mode eq 'both') {
 1806: 	$result=$rendered.$companswer;
 1807:     } elsif ($mode eq 'text') {
 1808: 	$result=$rendered;
 1809:     } elsif ($mode eq 'answer') {
 1810: 	$result=$companswer;
 1811:     }
 1812:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1813:     return $result;
 1814: }
 1815: 
 1816: sub files_exist {
 1817:     my ($r, $symb) = @_;
 1818:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1819: 
 1820:     foreach my $student (@students) {
 1821:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1822:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1823: 					      $udom,$uname);
 1824:         my ($string,$timestamp)= &get_last_submission(\%record);
 1825:         foreach my $submission (@$string) {
 1826:             my ($partid,$respid) =
 1827: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1828:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1829: 					   \%record);
 1830:             return 1 if (@$files);
 1831:         }
 1832:     }
 1833:     return 0;
 1834: }
 1835: 
 1836: sub download_all_link {
 1837:     my ($r,$symb) = @_;
 1838:     my $all_students = 
 1839: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1840: 
 1841:     my $parts =
 1842: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1843: 
 1844:     my $identifier = &Apache::loncommon::get_cgi_id();
 1845:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1846:                              'cgi.'.$identifier.'.symb' => $symb,
 1847:                              'cgi.'.$identifier.'.parts' => $parts,});
 1848:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1849: 	      &mt('Download All Submitted Documents').'</a>');
 1850:     return
 1851: }
 1852: 
 1853: sub build_section_inputs {
 1854:     my $section_inputs;
 1855:     if ($env{'form.section'} eq '') {
 1856:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1857:     } else {
 1858:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1859:         foreach my $section (@sections) {
 1860:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1861:         }
 1862:     }
 1863:     return $section_inputs;
 1864: }
 1865: 
 1866: # --------------------------- show submissions of a student, option to grade 
 1867: sub submission {
 1868:     my ($request,$counter,$total) = @_;
 1869:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1870:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1871:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1872:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1873:     my $symb = &get_symb($request); 
 1874:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1875: 
 1876:     if (!&canview($usec)) {
 1877: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1878: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1879: 			$env{'request.course.id'}.')</span>');
 1880: 	$request->print(&show_grading_menu_form($symb));
 1881: 	return;
 1882:     }
 1883: 
 1884:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1885:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1886:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1887:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1888:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1889: 	'" src="'.$request->dir_config('lonIconsURL').
 1890: 	'/check.gif" height="16" border="0" />';
 1891: 
 1892:     my %old_essays;
 1893:     # header info
 1894:     if ($counter == 0) {
 1895: 	&sub_page_js($request);
 1896: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1897: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1898: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1899: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1900: 	    &download_all_link($request, $symb);
 1901: 	}
 1902: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1903: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1904: 
 1905: 	# option to display problem, only once else it cause problems 
 1906:         # with the form later since the problem has a form.
 1907: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1908: 	    my $mode;
 1909: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1910: 		$mode='both';
 1911: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1912: 		$mode='text';
 1913: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1914: 		$mode='answer';
 1915: 	    }
 1916: 	    &Apache::lonxml::clear_problem_counter();
 1917: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1918: 	}
 1919: 
 1920: 	# kwclr is the only variable that is guaranteed to be non blank 
 1921:         # if this subroutine has been called once.
 1922: 	my %keyhash = ();
 1923: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1924: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1925: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1926: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1927: 
 1928: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1929: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1930: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1931: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1932: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1933: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1934: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1935: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1936: 	}
 1937: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1938: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1939: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1940: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1941: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1942: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1943: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1944: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1945: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1946: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1947: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1948: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1949: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1950: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1951: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1952: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1953: 			&build_section_inputs().
 1954: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1955: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1956: 			'<input type="hidden" name="NCT"'.
 1957: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1958: 	if ($env{'form.handgrade'} eq 'yes') {
 1959: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1960: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1961: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1963: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1965: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1966: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1967: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1968: 	    }
 1969: 	}
 1970: 	
 1971: 	my ($cts,$prnmsg) = (1,'');
 1972: 	while ($cts <= $env{'form.savemsgN'}) {
 1973: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1974: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1975: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1976: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1977: 		'" />'."\n".
 1978: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1979: 	    $cts++;
 1980: 	}
 1981: 	$request->print($prnmsg);
 1982: 
 1983: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1984: #
 1985: # Print out the keyword options line
 1986: #
 1987: 	    $request->print(<<KEYWORDS);
 1988: &nbsp;<b>Keyword Options:</b>&nbsp;
 1989: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1990: <a href="#" onMouseDown="javascript:getSel(); return false"
 1991:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1992: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1993: KEYWORDS
 1994: #
 1995: # Load the other essays for similarity check
 1996: #
 1997:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1998: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1999: 	    $apath=&escape($apath);
 2000: 	    $apath=~s/\W/\_/gs;
 2001: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2002:         }
 2003:     }
 2004: 
 2005: # This is where output for one specific student would start
 2006:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2007:     $request->print("\n\n".
 2008:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2009: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2010: 		    '<div class="LC_grade_show_user_body">'."\n");
 2011: 
 2012:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2013: 	my $mode;
 2014: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2015: 	    $mode='both';
 2016: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2017: 	    $mode='text';
 2018: 	} elsif ($env{'form.vAns'} eq 'all') {
 2019: 	    $mode='answer';
 2020: 	}
 2021: 	&Apache::lonxml::clear_problem_counter();
 2022: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2023:     }
 2024: 
 2025:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2026:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2027: 
 2028:     # Display student info
 2029:     $request->print(($counter == 0 ? '' : '<br />'));
 2030:     my $result='<div class="LC_grade_submissions">';
 2031:     
 2032:     $result.='<div class="LC_grade_submissions_header">';
 2033:     $result.= &mt('Submissions');
 2034:     $result.='<input type="hidden" name="name'.$counter.
 2035: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2036:     if ($env{'form.handgrade'} eq 'no') {
 2037: 	$result.='<span class="LC_grade_check_note">'.
 2038: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2039: 
 2040:     }
 2041: 
 2042: 
 2043: 
 2044:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2045:     my $fullname;
 2046:     my $col_fullnames = [];
 2047:     if ($env{'form.handgrade'} eq 'yes') {
 2048: 	(my $sub_result,$fullname,$col_fullnames)=
 2049: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2050: 				 $counter);
 2051: 	$result.=$sub_result;
 2052:     }
 2053:     $request->print($result."\n");
 2054:     $request->print('</div>'."\n");
 2055:     # print student answer/submission
 2056:     # Options are (1) Handgaded submission only
 2057:     #             (2) Last submission, includes submission that is not handgraded 
 2058:     #                  (for multi-response type part)
 2059:     #             (3) Last submission plus the parts info
 2060:     #             (4) The whole record for this student
 2061:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2062: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2063: 	
 2064: 	my $lastsubonly;
 2065: 
 2066: 	if ($$timestamp eq '') {
 2067: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2068: 	} else {
 2069: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2070: 
 2071: 	    my %seenparts;
 2072: 	    my @part_response_id = &flatten_responseType($responseType);
 2073: 	    foreach my $part (@part_response_id) {
 2074: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2075: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2076: 
 2077: 		my ($partid,$respid) = @{ $part };
 2078: 		my $display_part=&get_display_part($partid,$symb);
 2079: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2080: 		    if (exists($seenparts{$partid})) { next; }
 2081: 		    $seenparts{$partid}=1;
 2082: 		    my $submitby='<b>Part:</b> '.$display_part.
 2083: 			' <b>Collaborative submission by:</b> '.
 2084: 			'<a href="javascript:viewSubmitter(\''.
 2085: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2086: 			'\');" target="_self">'.
 2087: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2088: 		    $request->print($submitby);
 2089: 		    next;
 2090: 		}
 2091: 		my $responsetype = $responseType->{$partid}->{$respid};
 2092: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2093: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2094: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2095: 			' )</span>&nbsp; &nbsp;'.
 2096: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2097: 		    next;
 2098: 		}
 2099: 		foreach my $submission (@$string) {
 2100: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2101: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2102: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2103: 		    # Similarity check
 2104: 		    my $similar='';
 2105: 		    if($env{'form.checkPlag'}){
 2106: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2107: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2108: 			if ($osim) {
 2109: 			    $osim=int($osim*100.0);
 2110: 			    my %old_course_desc = 
 2111: 				&Apache::lonnet::coursedescription($ocrsid,
 2112: 								   {'one_time' => 1});
 2113: 
 2114: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2115: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2116: 				    $osim,
 2117: 				    &Apache::loncommon::plainname($oname,$odom),
 2118: 				    $oname,$odom,
 2119: 				    $old_course_desc{'description'},
 2120: 				    $old_course_desc{'num'},
 2121: 				    $old_course_desc{'domain'}).
 2122: 				'</span></h3><blockquote><i>'.
 2123: 				&keywords_highlight($oessay).
 2124: 				'</i></blockquote><hr />';
 2125: 			}
 2126: 		    }
 2127: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2128: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2129: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2130: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2131: 			my $display_part=&get_display_part($partid,$symb);
 2132: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2133: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2134: 			    ' )</span>&nbsp; &nbsp;';
 2135: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2136: 			if (@$files) {
 2137: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
 2138: 			    my $file_counter = 0;
 2139: 			    foreach my $file (@$files) {
 2140: 			        $file_counter++;
 2141: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2142: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2143: 			    }
 2144: 			    $lastsubonly.='<br />';
 2145: 			}
 2146: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2147: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2148: 					 $respid,\%record,$order);
 2149: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2150: 			$lastsubonly.='</div>';
 2151: 		    }
 2152: 		}
 2153: 	    }
 2154: 	    $lastsubonly.='</div>'."\n";
 2155: 	}
 2156: 	$request->print($lastsubonly);
 2157:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2158: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2159: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2160:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2161: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2162: 								 $env{'request.course.id'},
 2163: 								 $last,'.submission',
 2164: 								 'Apache::grades::keywords_highlight'));
 2165:     }
 2166: 
 2167:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2168: 	.$udom.'" />'."\n");
 2169:     # return if view submission with no grading option
 2170:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2171: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2172: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2173: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2174: 	$toGrade.='</div>'."\n";
 2175: 	if (($env{'form.command'} eq 'submission') || 
 2176: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2177: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2178: 	}
 2179: 	$request->print($toGrade);
 2180: 	return;
 2181:     } else {
 2182: 	$request->print('</div>'."\n");
 2183:     }
 2184: 
 2185:     # essay grading message center
 2186:     if ($env{'form.handgrade'} eq 'yes') {
 2187: 	my $result='<div class="LC_grade_message_center">';
 2188:     
 2189: 	$result.='<div class="LC_grade_message_center_header">'.
 2190: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2191: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2192: 	my $msgfor = $givenn.' '.$lastname;
 2193: 	if (scalar(@$col_fullnames) > 0) {
 2194: 	    my $lastone = pop(@$col_fullnames);
 2195: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2196: 	}
 2197: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2198: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2199: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2200: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2201: 	    ',\''.$msgfor.'\');" target="_self">'.
 2202: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2203: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2204: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2205: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2206: 	    '<br />&nbsp;('.
 2207: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2208: 	$result.='</div></div>';
 2209: 	$request->print($result);
 2210:     }
 2211: 
 2212:     my %seen = ();
 2213:     my @partlist;
 2214:     my @gradePartRespid;
 2215:     my @part_response_id = &flatten_responseType($responseType);
 2216:     $request->print('<div class="LC_grade_assign">'.
 2217: 		    
 2218: 		    '<div class="LC_grade_assign_header">'.
 2219: 		    &mt('Assign Grades').'</div>'.
 2220: 		    '<div class="LC_grade_assign_body">');
 2221:     foreach my $part_response_id (@part_response_id) {
 2222:     	my ($partid,$respid) = @{ $part_response_id };
 2223: 	my $part_resp = join('_',@{ $part_response_id });
 2224: 	next if ($seen{$partid} > 0);
 2225: 	$seen{$partid}++;
 2226: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2227: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2228: 	push @partlist,$partid;
 2229: 	push @gradePartRespid,$partid.'.'.$respid;
 2230: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2231:     }
 2232:     $request->print('</div></div>');
 2233: 
 2234:     $request->print('<div class="LC_grade_info_links">');
 2235:     if ($perm{'vgr'}) {
 2236: 	$request->print(
 2237: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2238: 						   $uname,$udom,'check'));
 2239:     }
 2240:     if ($perm{'opa'}) {
 2241: 	$request->print(
 2242: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2243: 					 $uname,$udom,$symb,'check'));
 2244:     }
 2245:     $request->print('</div>');
 2246: 
 2247:     $result='<input type="hidden" name="partlist'.$counter.
 2248: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2249:     $result.='<input type="hidden" name="gradePartRespid'.
 2250: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2251:     my $ctr = 0;
 2252:     while ($ctr < scalar(@partlist)) {
 2253: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2254: 	    $partlist[$ctr].'" />'."\n";
 2255: 	$ctr++;
 2256:     }
 2257:     $request->print($result.''."\n");
 2258: 
 2259: # Done with printing info for one student
 2260: 
 2261:     $request->print('</div>');#LC_grade_show_user_body
 2262:     $request->print('</div>');#LC_grade_show_user
 2263: 
 2264: 
 2265:     # print end of form
 2266:     if ($counter == $total) {
 2267: 	my $endform='<table border="0"><tr><td>'."\n";
 2268: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2269: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2270: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2271: 	my $ntstu ='<select name="NTSTU">'.
 2272: 	    '<option>1</option><option>2</option>'.
 2273: 	    '<option>3</option><option>5</option>'.
 2274: 	    '<option>7</option><option>10</option></select>'."\n";
 2275: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2276: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2277: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2278: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2279: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2280: 	    '<input type="button" value="'.&mt('Next').'" '.
 2281: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2282: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2283:         $endform.="<input type='hidden' value='".&get_increment().
 2284:             "' name='increment' />";
 2285: 	$endform.='</td></tr></table></form>';
 2286: 	$endform.=&show_grading_menu_form($symb);
 2287: 	$request->print($endform);
 2288:     }
 2289:     return '';
 2290: }
 2291: 
 2292: sub check_collaborators {
 2293:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2294:     my ($result,@col_fullnames);
 2295:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2296:     foreach my $part (keys(%$handgrade)) {
 2297: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2298: 					'.maxcollaborators',
 2299: 					$symb,$udom,$uname);
 2300: 	next if ($ncol <= 0);
 2301: 	$part =~ s/\_/\./g;
 2302: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2303: 	my (@good_collaborators, @bad_collaborators);
 2304: 	foreach my $possible_collaborator
 2305: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2306: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2307: 	    next if ($possible_collaborator eq '');
 2308: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2309: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2310: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2311: 	    # Doing this grep allows 'fuzzy' specification
 2312: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2313: 			       keys(%$classlist));
 2314: 	    if (! scalar(@matches)) {
 2315: 		push(@bad_collaborators, $possible_collaborator);
 2316: 	    } else {
 2317: 		push(@good_collaborators, @matches);
 2318: 	    }
 2319: 	}
 2320: 	if (scalar(@good_collaborators) != 0) {
 2321: 	    $result.='<br />'.&mt('Collaborators: ');
 2322: 	    foreach my $name (@good_collaborators) {
 2323: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2324: 		push(@col_fullnames, $givenn.' '.$lastname);
 2325: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2326: 	    }
 2327: 	    $result.='<br />'."\n";
 2328: 	    my ($part)=split(/\./,$part);
 2329: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2330: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2331: 		"\n";
 2332: 	}
 2333: 	if (scalar(@bad_collaborators) > 0) {
 2334: 	    $result.='<div class="LC_warning">';
 2335: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2336: 	    $result .= '</div>';
 2337: 	}         
 2338: 	if (scalar(@bad_collaborators > $ncol)) {
 2339: 	    $result .= '<div class="LC_warning">';
 2340: 	    $result .= &mt('This student has submitted too many '.
 2341: 		'collaborators.  Maximum is [_1].',$ncol);
 2342: 	    $result .= '</div>';
 2343: 	}
 2344:     }
 2345:     return ($result,$fullname,\@col_fullnames);
 2346: }
 2347: 
 2348: #--- Retrieve the last submission for all the parts
 2349: sub get_last_submission {
 2350:     my ($returnhash)=@_;
 2351:     my (@string,$timestamp);
 2352:     if ($$returnhash{'version'}) {
 2353: 	my %lasthash=();
 2354: 	my ($version);
 2355: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2356: 	    foreach my $key (sort(split(/\:/,
 2357: 					$$returnhash{$version.':keys'}))) {
 2358: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2359: 		$timestamp = 
 2360: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2361: 	    }
 2362: 	}
 2363: 	foreach my $key (keys(%lasthash)) {
 2364: 	    next if ($key !~ /\.submission$/);
 2365: 
 2366: 	    my ($partid,$foo) = split(/submission$/,$key);
 2367: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2368: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2369: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2370: 	}
 2371:     }
 2372:     if (!@string) {
 2373: 	$string[0] =
 2374: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2375:     }
 2376:     return (\@string,\$timestamp);
 2377: }
 2378: 
 2379: #--- High light keywords, with style choosen by user.
 2380: sub keywords_highlight {
 2381:     my $string    = shift;
 2382:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2383:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2384:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2385:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2386:     foreach my $keyword (@keylist) {
 2387: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2388:     }
 2389:     return $string;
 2390: }
 2391: 
 2392: #--- Called from submission routine
 2393: sub processHandGrade {
 2394:     my ($request) = shift;
 2395:     my $symb   = &get_symb($request);
 2396:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2397:     my $button = $env{'form.gradeOpt'};
 2398:     my $ngrade = $env{'form.NCT'};
 2399:     my $ntstu  = $env{'form.NTSTU'};
 2400:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2401:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2402: 
 2403:     if ($button eq 'Save & Next') {
 2404: 	my $ctr = 0;
 2405: 	while ($ctr < $ngrade) {
 2406: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2407: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2408: 	    if ($errorflag eq 'no_score') {
 2409: 		$ctr++;
 2410: 		next;
 2411: 	    }
 2412: 	    if ($errorflag eq 'not_allowed') {
 2413: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2414: 		$ctr++;
 2415: 		next;
 2416: 	    }
 2417: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2418: 	    my ($subject,$message,$msgstatus) = ('','','');
 2419: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2420:             my ($feedurl,$showsymb) =
 2421: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2422: 	    my $messagetail;
 2423: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2424: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2425: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2426: 		$subject.=' ['.$restitle.']';
 2427: 		my (@msgnum) = split(/,/,$includemsg);
 2428: 		foreach (@msgnum) {
 2429: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2430: 		}
 2431: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2432: 		if ($env{'form.withgrades'.$ctr}) {
 2433: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2434: 		    $messagetail = " for <a href=\"".
 2435: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2436: 		}
 2437: 		$msgstatus = 
 2438:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2439: 						     $message.$messagetail,
 2440:                                                      undef,$feedurl,undef,
 2441:                                                      undef,undef,$showsymb,
 2442:                                                      $restitle);
 2443: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2444: 				$msgstatus);
 2445: 	    }
 2446: 	    if ($env{'form.collaborator'.$ctr}) {
 2447: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2448: 		foreach my $collabstr (@collabstrs) {
 2449: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2450: 		    foreach my $collaborator (@collaborators) {
 2451: 			my ($errorflag,$pts,$wgt) = 
 2452: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2453: 					   $env{'form.unamedom'.$ctr},$part);
 2454: 			if ($errorflag eq 'not_allowed') {
 2455: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2456: 			    next;
 2457: 			} elsif ($message ne '') {
 2458: 			    my ($baseurl,$showsymb) = 
 2459: 				&get_feedurl_and_symb($symb,$collaborator,
 2460: 						      $udom);
 2461: 			    if ($env{'form.withgrades'.$ctr}) {
 2462: 				$messagetail = " for <a href=\"".
 2463:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2464: 			    }
 2465: 			    $msgstatus = 
 2466: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2467: 			}
 2468: 		    }
 2469: 		}
 2470: 	    }
 2471: 	    $ctr++;
 2472: 	}
 2473:     }
 2474: 
 2475:     if ($env{'form.handgrade'} eq 'yes') {
 2476: 	# Keywords sorted in alphabatical order
 2477: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2478: 	my %keyhash = ();
 2479: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2480: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2481: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2482: 	$env{'form.keywords'} = join(' ',@keywords);
 2483: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2484: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2485: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2486: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2487: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2488: 
 2489: 	# message center - Order of message gets changed. Blank line is eliminated.
 2490: 	# New messages are saved in env for the next student.
 2491: 	# All messages are saved in nohist_handgrade.db
 2492: 	my ($ctr,$idx) = (1,1);
 2493: 	while ($ctr <= $env{'form.savemsgN'}) {
 2494: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2495: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2496: 		$idx++;
 2497: 	    }
 2498: 	    $ctr++;
 2499: 	}
 2500: 	$ctr = 0;
 2501: 	while ($ctr < $ngrade) {
 2502: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2503: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2504: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2505: 		$idx++;
 2506: 	    }
 2507: 	    $ctr++;
 2508: 	}
 2509: 	$env{'form.savemsgN'} = --$idx;
 2510: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2511: 	my $putresult = &Apache::lonnet::put
 2512: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2513:     }
 2514:     # Called by Save & Refresh from Highlight Attribute Window
 2515:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2516:     if ($env{'form.refresh'} eq 'on') {
 2517: 	my ($ctr,$total) = (0,0);
 2518: 	while ($ctr < $ngrade) {
 2519: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2520: 	    $ctr++;
 2521: 	}
 2522: 	$env{'form.NTSTU'}=$ngrade;
 2523: 	$ctr = 0;
 2524: 	while ($ctr < $total) {
 2525: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2526: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2527: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2528: 	    &submission($request,$ctr,$total-1);
 2529: 	    $ctr++;
 2530: 	}
 2531: 	return '';
 2532:     }
 2533: 
 2534: # Go directly to grade student - from submission or link from chart page
 2535:     if ($button eq 'Grade Student') {
 2536: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2537: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2538: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2539: 	$env{'form.fullname'} = $$fullname{$processUser};
 2540: 	&submission($request,0,0);
 2541: 	return '';
 2542:     }
 2543: 
 2544:     # Get the next/previous one or group of students
 2545:     my $firststu = $env{'form.unamedom0'};
 2546:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2547:     my $ctr = 2;
 2548:     while ($laststu eq '') {
 2549: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2550: 	$ctr++;
 2551: 	$laststu = $firststu if ($ctr > $ngrade);
 2552:     }
 2553: 
 2554:     my (@parsedlist,@nextlist);
 2555:     my ($nextflg) = 0;
 2556:     foreach (sort 
 2557: 	     {
 2558: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2559: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2560: 		 }
 2561: 		 return $a cmp $b;
 2562: 	     } (keys(%$fullname))) {
 2563: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2564: 	    push @parsedlist,$_;
 2565: 	}
 2566: 	$nextflg = 1 if ($_ eq $laststu);
 2567: 	if ($button eq 'Previous') {
 2568: 	    last if ($_ eq $firststu);
 2569: 	    push @parsedlist,$_;
 2570: 	}
 2571:     }
 2572:     $ctr = 0;
 2573:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2574:     my ($partlist) = &response_type($symb);
 2575:     foreach my $student (@parsedlist) {
 2576: 	my $submitonly=$env{'form.submitonly'};
 2577: 	my ($uname,$udom) = split(/:/,$student);
 2578: 	
 2579: 	if ($submitonly eq 'queued') {
 2580: 	    my %queue_status = 
 2581: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2582: 							$udom,$uname);
 2583: 	    next if (!defined($queue_status{'gradingqueue'}));
 2584: 	}
 2585: 
 2586: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2587: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2588: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2589: 	    my $submitted = 0;
 2590: 	    my $ungraded = 0;
 2591: 	    my $incorrect = 0;
 2592: 	    foreach (keys(%status)) {
 2593: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2594: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2595: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2596: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2597: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2598: 		    $submitted = 0;
 2599: 		}
 2600: 	    }
 2601: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2602: 				     $submitonly eq 'incorrect' ||
 2603: 				     $submitonly eq 'graded'));
 2604: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2605: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2606: 	}
 2607: 	push @nextlist,$student if ($ctr < $ntstu);
 2608: 	last if ($ctr == $ntstu);
 2609: 	$ctr++;
 2610:     }
 2611: 
 2612:     $ctr = 0;
 2613:     my $total = scalar(@nextlist)-1;
 2614: 
 2615:     foreach (sort @nextlist) {
 2616: 	my ($uname,$udom,$submitter) = split(/:/);
 2617: 	$env{'form.student'}  = $uname;
 2618: 	$env{'form.userdom'}  = $udom;
 2619: 	$env{'form.fullname'} = $$fullname{$_};
 2620: 	&submission($request,$ctr,$total);
 2621: 	$ctr++;
 2622:     }
 2623:     if ($total < 0) {
 2624: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2625: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2626: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2627: 	$the_end.=&show_grading_menu_form($symb);
 2628: 	$request->print($the_end);
 2629:     }
 2630:     return '';
 2631: }
 2632: 
 2633: #---- Save the score and award for each student, if changed
 2634: sub saveHandGrade {
 2635:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2636:     my @version_parts;
 2637:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2638: 					   $env{'request.course.id'});
 2639:     if (!&canmodify($usec)) { return('not_allowed'); }
 2640:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2641:     my @parts_graded;
 2642:     my %newrecord  = ();
 2643:     my ($pts,$wgt) = ('','');
 2644:     my %aggregate = ();
 2645:     my $aggregateflag = 0;
 2646:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2647:     foreach my $new_part (@parts) {
 2648: 	#collaborator ($submi may vary for different parts
 2649: 	if ($submitter && $new_part ne $part) { next; }
 2650: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2651: 	if ($dropMenu eq 'excused') {
 2652: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2653: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2654: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2655: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2656: 		}
 2657: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2658: 	    }
 2659: 	} elsif ($dropMenu eq 'reset status'
 2660: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2661: 	    foreach my $key (keys (%record)) {
 2662: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2663: 	    }
 2664: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2665: 		"$env{'user.name'}:$env{'user.domain'}";
 2666:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2667: 
 2668:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2669: 					       [$new_part]);
 2670:             my $aggtries =$totaltries;
 2671:             if ($last_resets{$new_part}) {
 2672:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2673: 					   $new_part);
 2674:             }
 2675: 
 2676:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2677:             if ($aggtries > 0) {
 2678:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2679:                 $aggregateflag = 1;
 2680:             }
 2681: 	} elsif ($dropMenu eq '') {
 2682: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2683: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2684: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2685: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2686: 		next;
 2687: 	    }
 2688: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2689: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2690: 	    my $partial= $pts/$wgt;
 2691: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2692: 		#do not update score for part if not changed.
 2693:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2694: 		next;
 2695: 	    } else {
 2696: 	        push @parts_graded, $new_part;
 2697: 	    }
 2698: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2699: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2700: 	    }
 2701: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2702: 	    if ($partial == 0) {
 2703: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2704: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2705: 		}
 2706: 	    } else {
 2707: 		if ($record{$reckey} ne 'correct_by_override') {
 2708: 		    $newrecord{$reckey} = 'correct_by_override';
 2709: 		}
 2710: 	    }	    
 2711: 	    if ($submitter && 
 2712: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2713: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2714: 	    }
 2715: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2716: 		"$env{'user.name'}:$env{'user.domain'}";
 2717: 	}
 2718: 	# unless problem has been graded, set flag to version the submitted files
 2719: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2720: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2721: 	        $dropMenu eq 'reset status')
 2722: 	   {
 2723: 	    push (@version_parts,$new_part);
 2724: 	}
 2725:     }
 2726:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2727:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2728: 
 2729:     if (%newrecord) {
 2730:         if (@version_parts) {
 2731:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2732:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2733: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2734: 	    foreach my $new_part (@version_parts) {
 2735: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2736: 				$new_part,\%newrecord);
 2737: 	    }
 2738:         }
 2739: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2740: 				$env{'request.course.id'},$domain,$stuname);
 2741: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2742: 				     $cdom,$cnum,$domain,$stuname);
 2743:     }
 2744:     if ($aggregateflag) {
 2745:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2746: 			      $cdom,$cnum);
 2747:     }
 2748:     return ('',$pts,$wgt);
 2749: }
 2750: 
 2751: sub check_and_remove_from_queue {
 2752:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2753:     my @ungraded_parts;
 2754:     foreach my $part (@{$parts}) {
 2755: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2756: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2757: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2758: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2759: 		) {
 2760: 	    push(@ungraded_parts, $part);
 2761: 	}
 2762:     }
 2763:     if ( !@ungraded_parts ) {
 2764: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2765: 					       $cnum,$domain,$stuname);
 2766:     }
 2767: }
 2768: 
 2769: sub handback_files {
 2770:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2771:     my $portfolio_root = '/userfiles/portfolio';
 2772:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2773: 
 2774:     my @part_response_id = &flatten_responseType($responseType);
 2775:     foreach my $part_response_id (@part_response_id) {
 2776:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2777: 	my $part_resp = join('_',@{ $part_response_id });
 2778:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2779:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2780:                 my $file_counter = 1;
 2781: 		my $file_msg;
 2782:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2783:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2784:                     my ($directory,$answer_file) = 
 2785:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2786:                     my ($answer_name,$answer_ver,$answer_ext) =
 2787: 		        &file_name_version_ext($answer_file);
 2788: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2789:                     my $getpropath = 1;
 2790: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2791: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2792:                     # fix file name
 2793:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2794:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2795:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2796:             	                                $save_file_name);
 2797:                     if ($result !~ m|^/uploaded/|) {
 2798:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2799:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2800:                     } else {
 2801:                         # mark the file as read only
 2802:                         my @files = ($save_file_name);
 2803:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2804:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2805: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2806: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2807: 			}
 2808:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2809: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2810: 
 2811:                     }
 2812:                     $request->print("<br />".$fname." will be the uploaded file name");
 2813:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2814:                     $file_counter++;
 2815:                 }
 2816: 		my $subject = "File Handed Back by Instructor ";
 2817: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2818: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2819: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2820: 		$message .= " and can be found in your portfolio space.";
 2821: 		my ($feedurl,$showsymb) = 
 2822: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2823:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2824: 		my $msgstatus = 
 2825:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2826: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2827:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2828:             }
 2829:         }
 2830:     return;
 2831: }
 2832: 
 2833: sub get_feedurl_and_symb {
 2834:     my ($symb,$uname,$udom) = @_;
 2835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2836:     $url = &Apache::lonnet::clutter($url);
 2837:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2838: 					$symb,$udom,$uname);
 2839:     if ($encrypturl =~ /^yes$/i) {
 2840: 	&Apache::lonenc::encrypted(\$url,1);
 2841: 	&Apache::lonenc::encrypted(\$symb,1);
 2842:     }
 2843:     return ($url,$symb);
 2844: }
 2845: 
 2846: sub get_submitted_files {
 2847:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2848:     my @files;
 2849:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2850:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2851:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2852:     	    push(@files,$file_url.$file);
 2853:         }
 2854:     }
 2855:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2856:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2857:     }
 2858:     return (\@files);
 2859: }
 2860: 
 2861: # ----------- Provides number of tries since last reset.
 2862: sub get_num_tries {
 2863:     my ($record,$last_reset,$part) = @_;
 2864:     my $timestamp = '';
 2865:     my $num_tries = 0;
 2866:     if ($$record{'version'}) {
 2867:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2868:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2869:                 $timestamp = $$record{$version.':timestamp'};
 2870:                 if ($timestamp > $last_reset) {
 2871:                     $num_tries ++;
 2872:                 } else {
 2873:                     last;
 2874:                 }
 2875:             }
 2876:         }
 2877:     }
 2878:     return $num_tries;
 2879: }
 2880: 
 2881: # ----------- Determine decrements required in aggregate totals 
 2882: sub decrement_aggs {
 2883:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2884:     my %decrement = (
 2885:                         attempts => 0,
 2886:                         users => 0,
 2887:                         correct => 0
 2888:                     );
 2889:     $decrement{'attempts'} = $aggtries;
 2890:     if ($solvedstatus =~ /^correct/) {
 2891:         $decrement{'correct'} = 1;
 2892:     }
 2893:     if ($aggtries == $totaltries) {
 2894:         $decrement{'users'} = 1;
 2895:     }
 2896:     foreach my $type (keys (%decrement)) {
 2897:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2898:     }
 2899:     return;
 2900: }
 2901: 
 2902: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2903: sub get_last_resets {
 2904:     my ($symb,$courseid,$partids) =@_;
 2905:     my %last_resets;
 2906:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2907:     my $cname = $env{'course.'.$courseid.'.num'};
 2908:     my @keys;
 2909:     foreach my $part (@{$partids}) {
 2910: 	push(@keys,"$symb\0$part\0resettime");
 2911:     }
 2912:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2913: 				     $cdom,$cname);
 2914:     foreach my $part (@{$partids}) {
 2915: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2916:     }
 2917:     return %last_resets;
 2918: }
 2919: 
 2920: # ----------- Handles creating versions for portfolio files as answers
 2921: sub version_portfiles {
 2922:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2923:     my $version_parts = join('|',@$v_flag);
 2924:     my @returned_keys;
 2925:     my $parts = join('|', @$parts_graded);
 2926:     my $portfolio_root = '/userfiles/portfolio';
 2927:     foreach my $key (keys(%$record)) {
 2928:         my $new_portfiles;
 2929:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2930:             my @versioned_portfiles;
 2931:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2932:             foreach my $file (@portfiles) {
 2933:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2934:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2935: 		my ($answer_name,$answer_ver,$answer_ext) =
 2936: 		    &file_name_version_ext($answer_file);
 2937:                 my $getpropath = 1;    
 2938:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2939:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2940:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2941:                 if ($new_answer ne 'problem getting file') {
 2942:                     push(@versioned_portfiles, $directory.$new_answer);
 2943:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2944:                         [$directory.$new_answer],
 2945:                         [$symb,$env{'request.course.id'},'graded']);
 2946:                 }
 2947:             }
 2948:             $$record{$key} = join(',',@versioned_portfiles);
 2949:             push(@returned_keys,$key);
 2950:         }
 2951:     } 
 2952:     return (@returned_keys);   
 2953: }
 2954: 
 2955: sub get_next_version {
 2956:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2957:     my $version;
 2958:     foreach my $row (@$dir_list) {
 2959:         my ($file) = split(/\&/,$row,2);
 2960:         my ($file_name,$file_version,$file_ext) =
 2961: 	    &file_name_version_ext($file);
 2962:         if (($file_name eq $answer_name) && 
 2963: 	    ($file_ext eq $answer_ext)) {
 2964:                 # gets here if filename and extension match, regardless of version
 2965:                 if ($file_version ne '') {
 2966:                 # a versioned file is found  so save it for later
 2967:                 if ($file_version > $version) {
 2968: 		    $version = $file_version;
 2969: 	        }
 2970:             }
 2971:         }
 2972:     } 
 2973:     $version ++;
 2974:     return($version);
 2975: }
 2976: 
 2977: sub version_selected_portfile {
 2978:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2979:     my ($answer_name,$answer_ver,$answer_ext) =
 2980:         &file_name_version_ext($file_name);
 2981:     my $new_answer;
 2982:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2983:     if($env{'form.copy'} eq '-1') {
 2984:         $new_answer = 'problem getting file';
 2985:     } else {
 2986:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2987:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2988:                             $stu_name,$domain,'copy',
 2989: 		        '/portfolio'.$directory.$new_answer);
 2990:     }    
 2991:     return ($new_answer);
 2992: }
 2993: 
 2994: sub file_name_version_ext {
 2995:     my ($file)=@_;
 2996:     my @file_parts = split(/\./, $file);
 2997:     my ($name,$version,$ext);
 2998:     if (@file_parts > 1) {
 2999: 	$ext=pop(@file_parts);
 3000: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3001: 	    $version=pop(@file_parts);
 3002: 	}
 3003: 	$name=join('.',@file_parts);
 3004:     } else {
 3005: 	$name=join('.',@file_parts);
 3006:     }
 3007:     return($name,$version,$ext);
 3008: }
 3009: 
 3010: #--------------------------------------------------------------------------------------
 3011: #
 3012: #-------------------------- Next few routines handles grading by section or whole class
 3013: #
 3014: #--- Javascript to handle grading by section or whole class
 3015: sub viewgrades_js {
 3016:     my ($request) = shift;
 3017: 
 3018:     $request->print(<<VIEWJAVASCRIPT);
 3019: <script type="text/javascript" language="javascript">
 3020:    function writePoint(partid,weight,point) {
 3021: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3022: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3023: 	if (point == "textval") {
 3024: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3025: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3026: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3027: 		var resetbox = false;
 3028: 		for (var i=0; i<radioButton.length; i++) {
 3029: 		    if (radioButton[i].checked) {
 3030: 			textbox.value = i;
 3031: 			resetbox = true;
 3032: 		    }
 3033: 		}
 3034: 		if (!resetbox) {
 3035: 		    textbox.value = "";
 3036: 		}
 3037: 		return;
 3038: 	    }
 3039: 	    if (parseFloat(point) > parseFloat(weight)) {
 3040: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3041: 				   ") greater than the weight for the part. Accept?");
 3042: 		if (resp == false) {
 3043: 		    textbox.value = "";
 3044: 		    return;
 3045: 		}
 3046: 	    }
 3047: 	    for (var i=0; i<radioButton.length; i++) {
 3048: 		radioButton[i].checked=false;
 3049: 		if (parseFloat(point) == i) {
 3050: 		    radioButton[i].checked=true;
 3051: 		}
 3052: 	    }
 3053: 
 3054: 	} else {
 3055: 	    textbox.value = parseFloat(point);
 3056: 	}
 3057: 	for (i=0;i<document.classgrade.total.value;i++) {
 3058: 	    var user = document.classgrade["ctr"+i].value;
 3059: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3060: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3061: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3062: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3063: 	    if (saveval != "correct") {
 3064: 		scorename.value = point;
 3065: 		if (selname[0].selected != true) {
 3066: 		    selname[0].selected = true;
 3067: 		}
 3068: 	    }
 3069: 	}
 3070: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3071:     }
 3072: 
 3073:     function writeRadText(partid,weight) {
 3074: 	var selval   = document.classgrade["SELVAL_"+partid];
 3075: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3076:         var override = document.classgrade["FORCE_"+partid].checked;
 3077: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3078: 	if (selval[1].selected || selval[2].selected) {
 3079: 	    for (var i=0; i<radioButton.length; i++) {
 3080: 		radioButton[i].checked=false;
 3081: 
 3082: 	    }
 3083: 	    textbox.value = "";
 3084: 
 3085: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3086: 		var user = document.classgrade["ctr"+i].value;
 3087: 		user = user.replace(new RegExp(':', 'g'),"_");
 3088: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3089: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3090: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3091: 		if ((saveval != "correct") || override) {
 3092: 		    scorename.value = "";
 3093: 		    if (selval[1].selected) {
 3094: 			selname[1].selected = true;
 3095: 		    } else {
 3096: 			selname[2].selected = true;
 3097: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3098: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3099: 		    }
 3100: 		}
 3101: 	    }
 3102: 	} else {
 3103: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3104: 		var user = document.classgrade["ctr"+i].value;
 3105: 		user = user.replace(new RegExp(':', 'g'),"_");
 3106: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3107: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3108: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3109: 		if ((saveval != "correct") || override) {
 3110: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3111: 		    selname[0].selected = true;
 3112: 		}
 3113: 	    }
 3114: 	}	    
 3115:     }
 3116: 
 3117:     function changeSelect(partid,user) {
 3118: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3119: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3120: 	var point  = textbox.value;
 3121: 	var weight = document.classgrade["weight_"+partid].value;
 3122: 
 3123: 	if (isNaN(point) || parseFloat(point) < 0) {
 3124: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3125: 	    textbox.value = "";
 3126: 	    return;
 3127: 	}
 3128: 	if (parseFloat(point) > parseFloat(weight)) {
 3129: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3130: 			       ") greater than the weight of the part. Accept?");
 3131: 	    if (resp == false) {
 3132: 		textbox.value = "";
 3133: 		return;
 3134: 	    }
 3135: 	}
 3136: 	selval[0].selected = true;
 3137:     }
 3138: 
 3139:     function changeOneScore(partid,user) {
 3140: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3141: 	if (selval[1].selected || selval[2].selected) {
 3142: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3143: 	    if (selval[2].selected) {
 3144: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3145: 	    }
 3146:         }
 3147:     }
 3148: 
 3149:     function resetEntry(numpart) {
 3150: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3151: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3152: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3153: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3154: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3155: 	    for (var i=0; i<radioButton.length; i++) {
 3156: 		radioButton[i].checked=false;
 3157: 
 3158: 	    }
 3159: 	    textbox.value = "";
 3160: 	    selval[0].selected = true;
 3161: 
 3162: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3163: 		var user = document.classgrade["ctr"+i].value;
 3164: 		user = user.replace(new RegExp(':', 'g'),"_");
 3165: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3166: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3167: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3168: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3169: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3170: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3171: 		if (saveselval == "excused") {
 3172: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3173: 		} else {
 3174: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3175: 		}
 3176: 	    }
 3177: 	}
 3178:     }
 3179: 
 3180: </script>
 3181: VIEWJAVASCRIPT
 3182: }
 3183: 
 3184: #--- show scores for a section or whole class w/ option to change/update a score
 3185: sub viewgrades {
 3186:     my ($request) = shift;
 3187:     &viewgrades_js($request);
 3188: 
 3189:     my ($symb) = &get_symb($request);
 3190:     #need to make sure we have the correct data for later EXT calls, 
 3191:     #thus invalidate the cache
 3192:     &Apache::lonnet::devalidatecourseresdata(
 3193:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3194:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3195:     &Apache::lonnet::clear_EXT_cache_status();
 3196: 
 3197:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3198:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3199: 
 3200:     #view individual student submission form - called using Javascript viewOneStudent
 3201:     $result.=&jscriptNform($symb);
 3202: 
 3203:     #beginning of class grading form
 3204:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3205:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3206: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3207: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3208: 	&build_section_inputs().
 3209: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3210: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3211: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3212: 
 3213:     my $sectionClass;
 3214:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3215:     if ($env{'form.section'} eq 'all') {
 3216: 	$sectionClass='Class';
 3217:     } elsif ($env{'form.section'} eq 'none') {
 3218: 	$sectionClass='Students in no Section';
 3219:     } else {
 3220: 	$sectionClass='Students in Section(s) [_1]';
 3221:     }
 3222:     $result.=
 3223: 	'<h3>'.
 3224: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3225:     $result.= &Apache::loncommon::start_data_table();
 3226:     #radio buttons/text box for assigning points for a section or class.
 3227:     #handles different parts of a problem
 3228:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3229:     my %weight = ();
 3230:     my $ctsparts = 0;
 3231:     my %seen = ();
 3232:     my @part_response_id = &flatten_responseType($responseType);
 3233:     foreach my $part_response_id (@part_response_id) {
 3234:     	my ($partid,$respid) = @{ $part_response_id };
 3235: 	my $part_resp = join('_',@{ $part_response_id });
 3236: 	next if $seen{$partid};
 3237: 	$seen{$partid}++;
 3238: 	my $handgrade=$$handgrade{$part_resp};
 3239: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3240: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3241: 
 3242: 	my $display_part=&get_display_part($partid,$symb);
 3243: 	my $radio.='<table border="0"><tr>';  
 3244: 	my $ctr = 0;
 3245: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3246: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3247: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3248: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3249: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3250: 	    $ctr++;
 3251: 	}
 3252: 	$radio.='</tr></table>';
 3253: 	my $line = '<input type="text" name="TEXTVAL_'.
 3254: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3255: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3256: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3257: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3258: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3259: 		$weight{$partid}.')"> '.
 3260: 	    '<option selected="selected"> </option>'.
 3261: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3262: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3263: 	    '</select></td>'.
 3264:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3265: 	$line.='<input type="hidden" name="partid_'.
 3266: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3267: 	$line.='<input type="hidden" name="weight_'.
 3268: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3269: 
 3270: 	$result.=
 3271: 	    &Apache::loncommon::start_data_table_row()."\n".
 3272: 	    &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).
 3273: 	    &Apache::loncommon::end_data_table_row()."\n";
 3274: 	$ctsparts++;
 3275:     }
 3276:     $result.=&Apache::loncommon::end_data_table()."\n".
 3277: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3278:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3279: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3280: 
 3281:     #table listing all the students in a section/class
 3282:     #header of table
 3283:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3284: 			 $section_display).'</h3>';
 3285:     $result.= &Apache::loncommon::start_data_table().
 3286: 	&Apache::loncommon::start_data_table_header_row().
 3287: 	'<th>'.&mt('No.').'</th>'.
 3288: 	'<th>'.&nameUserString('header')."</th>\n";
 3289:     my (@parts) = sort(&getpartlist($symb));
 3290:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3291:     my @partids = ();
 3292:     foreach my $part (@parts) {
 3293: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3294: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3295: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3296: 	my ($partid) = &split_part_type($part);
 3297:         push(@partids, $partid);
 3298: 	my $display_part=&get_display_part($partid,$symb);
 3299: 	if ($display =~ /^Partial Credit Factor/) {
 3300: 	    $result.='<th>'.
 3301: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3302: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3303: 	    next;
 3304: 	    
 3305: 	} else {
 3306: 	    if ($display =~ /Problem Status/) {
 3307: 		my $grade_status_mt = &mt('Grade Status');
 3308: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3309: 	    }
 3310: 	    my $part_mt = &mt('Part:');
 3311: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3312: 	}
 3313: 
 3314: 	$result.='<th>'.$display.'</th>'."\n";
 3315:     }
 3316:     $result.=&Apache::loncommon::end_data_table_header_row();
 3317: 
 3318:     my %last_resets = 
 3319: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3320: 
 3321:     #get info for each student
 3322:     #list all the students - with points and grade status
 3323:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3324:     my $ctr = 0;
 3325:     foreach (sort 
 3326: 	     {
 3327: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3328: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3329: 		 }
 3330: 		 return $a cmp $b;
 3331: 	     } (keys(%$fullname))) {
 3332: 	$ctr++;
 3333: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3334: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3335:     }
 3336:     $result.=&Apache::loncommon::end_data_table();
 3337:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3338:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3339: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3340:     if (scalar(%$fullname) eq 0) {
 3341: 	my $colspan=3+scalar(@parts);
 3342: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3343:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3344: 	$result='<span class="LC_warning">'.
 3345: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3346: 	        $section_display, $stu_status).
 3347: 	    '</span>';
 3348:     }
 3349:     $result.=&show_grading_menu_form($symb);
 3350:     return $result;
 3351: }
 3352: 
 3353: #--- call by previous routine to display each student
 3354: sub viewstudentgrade {
 3355:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3356:     my ($uname,$udom) = split(/:/,$student);
 3357:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3358:     my %aggregates = (); 
 3359:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3360: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3361: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3362: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3363: 	'\');" target="_self">'.$fullname.'</a> '.
 3364: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3365:     $student=~s/:/_/; # colon doen't work in javascript for names
 3366:     foreach my $apart (@$parts) {
 3367: 	my ($part,$type) = &split_part_type($apart);
 3368: 	my $score=$record{"resource.$part.$type"};
 3369:         $result.='<td align="center">';
 3370:         my ($aggtries,$totaltries);
 3371:         unless (exists($aggregates{$part})) {
 3372: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3373: 
 3374: 	    $aggtries = $totaltries;
 3375:             if ($$last_resets{$part}) {  
 3376:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3377: 					   $part);
 3378:             }
 3379:             $result.='<input type="hidden" name="'.
 3380:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3381:             $result.='<input type="hidden" name="'.
 3382:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3383:             $aggregates{$part} = 1;
 3384:         }
 3385: 	if ($type eq 'awarded') {
 3386: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3387: 	    $result.='<input type="hidden" name="'.
 3388: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3389: 	    $result.='<input type="text" name="'.
 3390: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3391: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3392: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3393: 	} elsif ($type eq 'solved') {
 3394: 	    my ($status,$foo)=split(/_/,$score,2);
 3395: 	    $status = 'nothing' if ($status eq '');
 3396: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3397: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3398: 	    $result.='&nbsp;<select name="'.
 3399: 		'GD_'.$student.'_'.$part.'_solved" '.
 3400: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3401: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3402: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3403: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3404: 	    $result.="</select>&nbsp;</td>\n";
 3405: 	} else {
 3406: 	    $result.='<input type="hidden" name="'.
 3407: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3408: 		    "\n";
 3409: 	    $result.='<input type="text" name="'.
 3410: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3411: 		'value="'.$score.'" size="4" /></td>'."\n";
 3412: 	}
 3413:     }
 3414:     $result.=&Apache::loncommon::end_data_table_row();
 3415:     return $result;
 3416: }
 3417: 
 3418: #--- change scores for all the students in a section/class
 3419: #    record does not get update if unchanged
 3420: sub editgrades {
 3421:     my ($request) = @_;
 3422: 
 3423:     my $symb=&get_symb($request);
 3424:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3425:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3426:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3427:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3428: 
 3429:     my $result= &Apache::loncommon::start_data_table().
 3430: 	&Apache::loncommon::start_data_table_header_row().
 3431: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3432: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3433:     my %scoreptr = (
 3434: 		    'correct'  =>'correct_by_override',
 3435: 		    'incorrect'=>'incorrect_by_override',
 3436: 		    'excused'  =>'excused',
 3437: 		    'ungraded' =>'ungraded_attempted',
 3438: 		    'nothing'  => '',
 3439: 		    );
 3440:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3441: 
 3442:     my (@partid);
 3443:     my %weight = ();
 3444:     my %columns = ();
 3445:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3446: 
 3447:     my (@parts) = sort(&getpartlist($symb));
 3448:     my $header;
 3449:     while ($ctr < $env{'form.totalparts'}) {
 3450: 	my $partid = $env{'form.partid_'.$ctr};
 3451: 	push @partid,$partid;
 3452: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3453: 	$ctr++;
 3454:     }
 3455:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3456:     foreach my $partid (@partid) {
 3457: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3458: 	    '<th align="center">'.&mt('New Score').'</th>';
 3459: 	$columns{$partid}=2;
 3460: 	foreach my $stores (@parts) {
 3461: 	    my ($part,$type) = &split_part_type($stores);
 3462: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3463: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3464: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3465: 	    $display =~ s/\[Part: (\w)+\]//;
 3466: 	    $display =~ s/Number of Attempts/Tries/;
 3467: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3468: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3469: 	    $columns{$partid}+=2;
 3470: 	}
 3471:     }
 3472:     foreach my $partid (@partid) {
 3473: 	my $display_part=&get_display_part($partid,$symb);
 3474: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3475: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3476: 	    '</th>';
 3477: 
 3478:     }
 3479:     $result .= &Apache::loncommon::end_data_table_header_row().
 3480: 	&Apache::loncommon::start_data_table_header_row().
 3481: 	$header.
 3482: 	&Apache::loncommon::end_data_table_header_row();
 3483:     my @noupdate;
 3484:     my ($updateCtr,$noupdateCtr) = (1,1);
 3485:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3486: 	my $line;
 3487: 	my $user = $env{'form.ctr'.$i};
 3488: 	my ($uname,$udom)=split(/:/,$user);
 3489: 	my %newrecord;
 3490: 	my $updateflag = 0;
 3491: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3492: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3493: 	if (!&canmodify($usec)) {
 3494: 	    my $numcols=scalar(@partid)*4+2;
 3495: 	    push(@noupdate,
 3496: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3497: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3498: 	    next;
 3499: 	}
 3500:         my %aggregate = ();
 3501:         my $aggregateflag = 0;
 3502: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3503: 	foreach (@partid) {
 3504: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3505: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3506: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3507: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3508: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3509: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3510: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3511: 	    my $score;
 3512: 	    if ($partial eq '') {
 3513: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3514: 	    } elsif ($partial > 0) {
 3515: 		$score = 'correct_by_override';
 3516: 	    } elsif ($partial == 0) {
 3517: 		$score = 'incorrect_by_override';
 3518: 	    }
 3519: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3520: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3521: 
 3522: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3523: 		"$env{'user.name'}:$env{'user.domain'}";
 3524: 	    if ($dropMenu eq 'reset status' &&
 3525: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3526: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3527: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3528: 		$newrecord{'resource.'.$_.'.award'} = '';
 3529: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3530: 		$updateflag = 1;
 3531:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3532:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3533:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3534:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3535:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3536:                     $aggregateflag = 1;
 3537:                 }
 3538: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3539: 		$updateflag = 1;
 3540: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3541: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3542: 		$rec_update++;
 3543: 	    }
 3544: 
 3545: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3546: 		'<td align="center">'.$awarded.
 3547: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3548: 
 3549: 
 3550: 	    my $partid=$_;
 3551: 	    foreach my $stores (@parts) {
 3552: 		my ($part,$type) = &split_part_type($stores);
 3553: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3554: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3555: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3556: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3557: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3558: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3559: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3560: 		    $updateflag=1;
 3561: 		}
 3562: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3563: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3564: 	    }
 3565: 	}
 3566: 	$line.="\n";
 3567: 
 3568: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3569: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3570: 
 3571: 	if ($updateflag) {
 3572: 	    $count++;
 3573: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3574: 				    $udom,$uname);
 3575: 
 3576: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3577: 					      $cnum,$udom,$uname)) {
 3578: 		# need to figure out if should be in queue.
 3579: 		my %record =  
 3580: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3581: 					     $udom,$uname);
 3582: 		my $all_graded = 1;
 3583: 		my $none_graded = 1;
 3584: 		foreach my $part (@parts) {
 3585: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3586: 			$all_graded = 0;
 3587: 		    } else {
 3588: 			$none_graded = 0;
 3589: 		    }
 3590: 		}
 3591: 
 3592: 		if ($all_graded || $none_graded) {
 3593: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3594: 							   $symb,$cdom,$cnum,
 3595: 							   $udom,$uname);
 3596: 		}
 3597: 	    }
 3598: 
 3599: 	    $result.=&Apache::loncommon::start_data_table_row().
 3600: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3601: 		&Apache::loncommon::end_data_table_row();
 3602: 	    $updateCtr++;
 3603: 	} else {
 3604: 	    push(@noupdate,
 3605: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3606: 	    $noupdateCtr++;
 3607: 	}
 3608:         if ($aggregateflag) {
 3609:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3610: 				  $cdom,$cnum);
 3611:         }
 3612:     }
 3613:     if (@noupdate) {
 3614: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3615: 	my $numcols=scalar(@partid)*4+2;
 3616: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3617: 	    '<td align="center" colspan="'.$numcols.'">'.
 3618: 	    &mt('No Changes Occurred For the Students Below').
 3619: 	    '</td>'.
 3620: 	    &Apache::loncommon::end_data_table_row();
 3621: 	foreach my $line (@noupdate) {
 3622: 	    $result.=
 3623: 		&Apache::loncommon::start_data_table_row().
 3624: 		$line.
 3625: 		&Apache::loncommon::end_data_table_row();
 3626: 	}
 3627:     }
 3628:     $result .= &Apache::loncommon::end_data_table().
 3629: 	&show_grading_menu_form($symb);
 3630:     my $msg = '<p><b>'.
 3631: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3632: 	    $rec_update,$count).'</b><br />'.
 3633: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3634: 	'</b></p>';
 3635:     return $title.$msg.$result;
 3636: }
 3637: 
 3638: sub split_part_type {
 3639:     my ($partstr) = @_;
 3640:     my ($temp,@allparts)=split(/_/,$partstr);
 3641:     my $type=pop(@allparts);
 3642:     my $part=join('_',@allparts);
 3643:     return ($part,$type);
 3644: }
 3645: 
 3646: #------------- end of section for handling grading by section/class ---------
 3647: #
 3648: #----------------------------------------------------------------------------
 3649: 
 3650: 
 3651: #----------------------------------------------------------------------------
 3652: #
 3653: #-------------------------- Next few routines handles grading by csv upload
 3654: #
 3655: #--- Javascript to handle csv upload
 3656: sub csvupload_javascript_reverse_associate {
 3657:     my $error1=&mt('You need to specify the username or ID');
 3658:     my $error2=&mt('You need to specify at least one grading field');
 3659:   return(<<ENDPICK);
 3660:   function verify(vf) {
 3661:     var foundsomething=0;
 3662:     var founduname=0;
 3663:     var foundID=0;
 3664:     for (i=0;i<=vf.nfields.value;i++) {
 3665:       tw=eval('vf.f'+i+'.selectedIndex');
 3666:       if (i==0 && tw!=0) { foundID=1; }
 3667:       if (i==1 && tw!=0) { founduname=1; }
 3668:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3669:     }
 3670:     if (founduname==0 && foundID==0) {
 3671: 	alert('$error1');
 3672: 	return;
 3673:     }
 3674:     if (foundsomething==0) {
 3675: 	alert('$error2');
 3676: 	return;
 3677:     }
 3678:     vf.submit();
 3679:   }
 3680:   function flip(vf,tf) {
 3681:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3682:     var i;
 3683:     for (i=0;i<=vf.nfields.value;i++) {
 3684:       //can not pick the same destination field for both name and domain
 3685:       if (((i ==0)||(i ==1)) && 
 3686:           ((tf==0)||(tf==1)) && 
 3687:           (i!=tf) &&
 3688:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3689:         eval('vf.f'+i+'.selectedIndex=0;')
 3690:       }
 3691:     }
 3692:   }
 3693: ENDPICK
 3694: }
 3695: 
 3696: sub csvupload_javascript_forward_associate {
 3697:     my $error1=&mt('You need to specify the username or ID');
 3698:     my $error2=&mt('You need to specify at least one grading field');
 3699:   return(<<ENDPICK);
 3700:   function verify(vf) {
 3701:     var foundsomething=0;
 3702:     var founduname=0;
 3703:     var foundID=0;
 3704:     for (i=0;i<=vf.nfields.value;i++) {
 3705:       tw=eval('vf.f'+i+'.selectedIndex');
 3706:       if (tw==1) { foundID=1; }
 3707:       if (tw==2) { founduname=1; }
 3708:       if (tw>3) { foundsomething=1; }
 3709:     }
 3710:     if (founduname==0 && foundID==0) {
 3711: 	alert('$error1');
 3712: 	return;
 3713:     }
 3714:     if (foundsomething==0) {
 3715: 	alert('$error2');
 3716: 	return;
 3717:     }
 3718:     vf.submit();
 3719:   }
 3720:   function flip(vf,tf) {
 3721:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3722:     var i;
 3723:     //can not pick the same destination field twice
 3724:     for (i=0;i<=vf.nfields.value;i++) {
 3725:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3726:         eval('vf.f'+i+'.selectedIndex=0;')
 3727:       }
 3728:     }
 3729:   }
 3730: ENDPICK
 3731: }
 3732: 
 3733: sub csvuploadmap_header {
 3734:     my ($request,$symb,$datatoken,$distotal)= @_;
 3735:     my $javascript;
 3736:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3737: 	$javascript=&csvupload_javascript_reverse_associate();
 3738:     } else {
 3739: 	$javascript=&csvupload_javascript_forward_associate();
 3740:     }
 3741: 
 3742:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3743:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3744:     my $ignore=&mt('Ignore First Line');
 3745:     $symb = &Apache::lonenc::check_encrypt($symb);
 3746:     $request->print(<<ENDPICK);
 3747: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3748: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3749: $result
 3750: <hr />
 3751: <h3>Identify fields</h3>
 3752: Total number of records found in file: $distotal <hr />
 3753: Enter as many fields as you can. The system will inform you and bring you back
 3754: to this page if the data selected is insufficient to run your class.<hr />
 3755: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3756: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3757: <input type="hidden" name="associate"  value="" />
 3758: <input type="hidden" name="phase"      value="three" />
 3759: <input type="hidden" name="datatoken"  value="$datatoken" />
 3760: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3761: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3762: <input type="hidden" name="upfile_associate" 
 3763:                                        value="$env{'form.upfile_associate'}" />
 3764: <input type="hidden" name="symb"       value="$symb" />
 3765: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3766: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3767: <input type="hidden" name="command"    value="csvuploadoptions" />
 3768: <hr />
 3769: <script type="text/javascript" language="Javascript">
 3770: $javascript
 3771: </script>
 3772: ENDPICK
 3773:     return '';
 3774: 
 3775: }
 3776: 
 3777: sub csvupload_fields {
 3778:     my ($symb) = @_;
 3779:     my (@parts) = &getpartlist($symb);
 3780:     my @fields=(['ID','Student ID'],
 3781: 		['username','Student Username'],
 3782: 		['domain','Student Domain']);
 3783:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3784:     foreach my $part (sort(@parts)) {
 3785: 	my @datum;
 3786: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3787: 	my $name=$part;
 3788: 	if  (!$display) { $display = $name; }
 3789: 	@datum=($name,$display);
 3790: 	if ($name=~/^stores_(.*)_awarded/) {
 3791: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3792: 	}
 3793: 	push(@fields,\@datum);
 3794:     }
 3795:     return (@fields);
 3796: }
 3797: 
 3798: sub csvuploadmap_footer {
 3799:     my ($request,$i,$keyfields) =@_;
 3800:     $request->print(<<ENDPICK);
 3801: </table>
 3802: <input type="hidden" name="nfields" value="$i" />
 3803: <input type="hidden" name="keyfields" value="$keyfields" />
 3804: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3805: </form>
 3806: ENDPICK
 3807: }
 3808: 
 3809: sub checkforfile_js {
 3810:     my $result =<<CSVFORMJS;
 3811: <script type="text/javascript" language="javascript">
 3812:     function checkUpload(formname) {
 3813: 	if (formname.upfile.value == "") {
 3814: 	    alert("Please use the browse button to select a file from your local directory.");
 3815: 	    return false;
 3816: 	}
 3817: 	formname.submit();
 3818:     }
 3819:     </script>
 3820: CSVFORMJS
 3821:     return $result;
 3822: }
 3823: 
 3824: sub upcsvScores_form {
 3825:     my ($request) = shift;
 3826:     my ($symb)=&get_symb($request);
 3827:     if (!$symb) {return '';}
 3828:     my $result=&checkforfile_js();
 3829:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3830:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3831:     $result.=$table;
 3832:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3833:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3834:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3835: 	'.</b></td></tr>'."\n";
 3836:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3837:     my $upload=&mt("Upload Scores");
 3838:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3839:     my $ignore=&mt('Ignore First Line');
 3840:     $symb = &Apache::lonenc::check_encrypt($symb);
 3841:     $result.=<<ENDUPFORM;
 3842: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3843: <input type="hidden" name="symb" value="$symb" />
 3844: <input type="hidden" name="command" value="csvuploadmap" />
 3845: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3846: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3847: $upfile_select
 3848: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3849: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3850: </form>
 3851: ENDUPFORM
 3852:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3853:                            &mt("How do I create a CSV file from a spreadsheet"))
 3854:     .'</td></tr></table>'."\n";
 3855:     $result.='</td></tr></table><br /><br />'."\n";
 3856:     $result.=&show_grading_menu_form($symb);
 3857:     return $result;
 3858: }
 3859: 
 3860: 
 3861: sub csvuploadmap {
 3862:     my ($request)= @_;
 3863:     my ($symb)=&get_symb($request);
 3864:     if (!$symb) {return '';}
 3865: 
 3866:     my $datatoken;
 3867:     if (!$env{'form.datatoken'}) {
 3868: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3869:     } else {
 3870: 	$datatoken=$env{'form.datatoken'};
 3871: 	&Apache::loncommon::load_tmp_file($request);
 3872:     }
 3873:     my @records=&Apache::loncommon::upfile_record_sep();
 3874:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3875:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3876:     my ($i,$keyfields);
 3877:     if (@records) {
 3878: 	my @fields=&csvupload_fields($symb);
 3879: 
 3880: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3881: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3882: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3883: 							  \@fields);
 3884: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3885: 	    chop($keyfields);
 3886: 	} else {
 3887: 	    unshift(@fields,['none','']);
 3888: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3889: 							    \@fields);
 3890:             foreach my $rec (@records) {
 3891:                 my %temp = &Apache::loncommon::record_sep($rec);
 3892:                 if (%temp) {
 3893:                     $keyfields=join(',',sort(keys(%temp)));
 3894:                     last;
 3895:                 }
 3896:             }
 3897: 	}
 3898:     }
 3899:     &csvuploadmap_footer($request,$i,$keyfields);
 3900:     $request->print(&show_grading_menu_form($symb));
 3901: 
 3902:     return '';
 3903: }
 3904: 
 3905: sub csvuploadoptions {
 3906:     my ($request)= @_;
 3907:     my ($symb)=&get_symb($request);
 3908:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3909:     my $ignore=&mt('Ignore First Line');
 3910:     $request->print(<<ENDPICK);
 3911: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3912: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3913: <input type="hidden" name="command"    value="csvuploadassign" />
 3914: <!--
 3915: <p>
 3916: <label>
 3917:    <input type="checkbox" name="show_full_results" />
 3918:    Show a table of all changes
 3919: </label>
 3920: </p>
 3921: -->
 3922: <p>
 3923: <label>
 3924:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3925:    Overwrite any existing score
 3926: </label>
 3927: </p>
 3928: ENDPICK
 3929:     my %fields=&get_fields();
 3930:     if (!defined($fields{'domain'})) {
 3931: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3932: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3933:     }
 3934:     foreach my $key (sort(keys(%env))) {
 3935: 	if ($key !~ /^form\.(.*)$/) { next; }
 3936: 	my $cleankey=$1;
 3937: 	if ($cleankey eq 'command') { next; }
 3938: 	$request->print('<input type="hidden" name="'.$cleankey.
 3939: 			'"  value="'.$env{$key}.'" />'."\n");
 3940:     }
 3941:     # FIXME do a check for any duplicated user ids...
 3942:     # FIXME do a check for any invalid user ids?...
 3943:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3944: <hr /></form>'."\n");
 3945:     $request->print(&show_grading_menu_form($symb));
 3946:     return '';
 3947: }
 3948: 
 3949: sub get_fields {
 3950:     my %fields;
 3951:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3952:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3953: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3954: 	    if ($env{'form.f'.$i} ne 'none') {
 3955: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3956: 	    }
 3957: 	} else {
 3958: 	    if ($env{'form.f'.$i} ne 'none') {
 3959: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3960: 	    }
 3961: 	}
 3962:     }
 3963:     return %fields;
 3964: }
 3965: 
 3966: sub csvuploadassign {
 3967:     my ($request)= @_;
 3968:     my ($symb)=&get_symb($request);
 3969:     if (!$symb) {return '';}
 3970:     my $error_msg = '';
 3971:     &Apache::loncommon::load_tmp_file($request);
 3972:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3973:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3974:     my %fields=&get_fields();
 3975:     $request->print('<h3>Assigning Grades</h3>');
 3976:     my $courseid=$env{'request.course.id'};
 3977:     my ($classlist) = &getclasslist('all',0);
 3978:     my @notallowed;
 3979:     my @skipped;
 3980:     my $countdone=0;
 3981:     foreach my $grade (@gradedata) {
 3982: 	my %entries=&Apache::loncommon::record_sep($grade);
 3983: 	my $domain;
 3984: 	if ($entries{$fields{'domain'}}) {
 3985: 	    $domain=$entries{$fields{'domain'}};
 3986: 	} else {
 3987: 	    $domain=$env{'form.default_domain'};
 3988: 	}
 3989: 	$domain=~s/\s//g;
 3990: 	my $username=$entries{$fields{'username'}};
 3991: 	$username=~s/\s//g;
 3992: 	if (!$username) {
 3993: 	    my $id=$entries{$fields{'ID'}};
 3994: 	    $id=~s/\s//g;
 3995: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3996: 	    $username=$ids{$id};
 3997: 	}
 3998: 	if (!exists($$classlist{"$username:$domain"})) {
 3999: 	    my $id=$entries{$fields{'ID'}};
 4000: 	    $id=~s/\s//g;
 4001: 	    if ($id) {
 4002: 		push(@skipped,"$id:$domain");
 4003: 	    } else {
 4004: 		push(@skipped,"$username:$domain");
 4005: 	    }
 4006: 	    next;
 4007: 	}
 4008: 	my $usec=$classlist->{"$username:$domain"}[5];
 4009: 	if (!&canmodify($usec)) {
 4010: 	    push(@notallowed,"$username:$domain");
 4011: 	    next;
 4012: 	}
 4013: 	my %points;
 4014: 	my %grades;
 4015: 	foreach my $dest (keys(%fields)) {
 4016: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4017: 		$dest eq 'domain') { next; }
 4018: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4019: 	    if ($dest=~/stores_(.*)_points/) {
 4020: 		my $part=$1;
 4021: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4022: 					      $symb,$domain,$username);
 4023:                 if ($wgt) {
 4024:                     $entries{$fields{$dest}}=~s/\s//g;
 4025:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4026:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4027:                                           : 'correct_by_override';
 4028:                     $grades{"resource.$part.awarded"}=$pcr;
 4029:                     $grades{"resource.$part.solved"}=$award;
 4030:                     $points{$part}=1;
 4031:                 } else {
 4032:                     $error_msg = "<br />" .
 4033:                         &mt("Some point values were assigned"
 4034:                             ." for problems with a weight "
 4035:                             ."of zero. These values were "
 4036:                             ."ignored.");
 4037:                 }
 4038: 	    } else {
 4039: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4040: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4041: 		my $store_key=$dest;
 4042: 		$store_key=~s/^stores/resource/;
 4043: 		$store_key=~s/_/\./g;
 4044: 		$grades{$store_key}=$entries{$fields{$dest}};
 4045: 	    }
 4046: 	}
 4047: 	if (! %grades) { 
 4048:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4049:         } else {
 4050: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4051: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4052: 					   $env{'request.course.id'},
 4053: 					   $domain,$username);
 4054: 	   if ($result eq 'ok') {
 4055: 	      $request->print('.');
 4056: 	   } else {
 4057: 	      $request->print("<p><span class=\"LC_error\">".
 4058:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4059:                                   "$username:$domain",$result)."</span></p>");
 4060: 	   }
 4061: 	   $request->rflush();
 4062: 	   $countdone++;
 4063:         }
 4064:     }
 4065:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4066:     if (@skipped) {
 4067: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4068: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4069:     }
 4070:     if (@notallowed) {
 4071: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4072: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4073:     }
 4074:     $request->print("<br />\n");
 4075:     $request->print(&show_grading_menu_form($symb));
 4076:     return $error_msg;
 4077: }
 4078: #------------- end of section for handling csv file upload ---------
 4079: #
 4080: #-------------------------------------------------------------------
 4081: #
 4082: #-------------- Next few routines handle grading by page/sequence
 4083: #
 4084: #--- Select a page/sequence and a student to grade
 4085: sub pickStudentPage {
 4086:     my ($request) = shift;
 4087: 
 4088:     $request->print(<<LISTJAVASCRIPT);
 4089: <script type="text/javascript" language="javascript">
 4090: 
 4091: function checkPickOne(formname) {
 4092:     if (radioSelection(formname.student) == null) {
 4093: 	alert("Please select the student you wish to grade.");
 4094: 	return;
 4095:     }
 4096:     ptr = pullDownSelection(formname.selectpage);
 4097:     formname.page.value = formname["page"+ptr].value;
 4098:     formname.title.value = formname["title"+ptr].value;
 4099:     formname.submit();
 4100: }
 4101: 
 4102: </script>
 4103: LISTJAVASCRIPT
 4104:     &commonJSfunctions($request);
 4105:     my ($symb) = &get_symb($request);
 4106:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4107:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4108:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4109: 
 4110:     my $result='<h3><span class="LC_info">&nbsp;'.
 4111: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4112: 
 4113:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4114:     my ($titles,$symbx) = &getSymbMap();
 4115:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4116: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4117: #    my $type=($curpage =~ /\.(page|sequence)/);
 4118:     my $select = '<select name="selectpage">'."\n";
 4119:     my $ctr=0;
 4120:     foreach (@$titles) {
 4121: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4122: 	$select.='<option value="'.$ctr.'" '.
 4123: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4124: 	    '>'.$showtitle.'</option>'."\n";
 4125: 	$ctr++;
 4126:     }
 4127:     $select.= '</select>';
 4128:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4129: 
 4130:     $ctr=0;
 4131:     foreach (@$titles) {
 4132: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4133: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4134: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4135: 	$ctr++;
 4136:     }
 4137:     $result.='<input type="hidden" name="page" />'."\n".
 4138: 	'<input type="hidden" name="title" />'."\n";
 4139: 
 4140:     my $options =
 4141: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4142: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4143:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4144: 
 4145:     $options =
 4146: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4147: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4148: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4149:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4150:     
 4151:     $result.=&build_section_inputs();
 4152:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4153:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4154: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4155: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4156: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4157: 
 4158:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4159: 			  '<input type="text" name="CODE" value="" />').
 4160: 			      '<br />'."\n";
 4161: 
 4162:     $result.='&nbsp;<input type="button" '.
 4163: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4164: 
 4165:     $request->print($result);
 4166: 
 4167:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4168: 	&Apache::loncommon::start_data_table().
 4169: 	&Apache::loncommon::start_data_table_header_row().
 4170: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4171: 	'<th>'.&nameUserString('header').'</th>'.
 4172: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4173: 	'<th>'.&nameUserString('header').'</th>'.
 4174: 	&Apache::loncommon::end_data_table_header_row();
 4175:  
 4176:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4177:     my $ptr = 1;
 4178:     foreach my $student (sort 
 4179: 			 {
 4180: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4181: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4182: 			     }
 4183: 			     return $a cmp $b;
 4184: 			 } (keys(%$fullname))) {
 4185: 	my ($uname,$udom) = split(/:/,$student);
 4186: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4187:                                   : '</td>');
 4188: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4189: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4190: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4191: 	$studentTable.=
 4192: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4193:                          : '');
 4194: 	$ptr++;
 4195:     }
 4196:     if ($ptr%2 == 0) {
 4197: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4198: 	    &Apache::loncommon::end_data_table_row();
 4199:     }
 4200:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4201:     $studentTable.='<input type="button" '.
 4202: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4203: 
 4204:     $studentTable.=&show_grading_menu_form($symb);
 4205:     $request->print($studentTable);
 4206: 
 4207:     return '';
 4208: }
 4209: 
 4210: sub getSymbMap {
 4211:     my $navmap = Apache::lonnavmaps::navmap->new();
 4212: 
 4213:     my %symbx = ();
 4214:     my @titles = ();
 4215:     my $minder = 0;
 4216: 
 4217:     # Gather every sequence that has problems.
 4218:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4219: 					       1,0,1);
 4220:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4221: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4222: 	    my $title = $minder.'.'.
 4223: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4224: 	    push(@titles, $title); # minder in case two titles are identical
 4225: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4226: 	    $minder++;
 4227: 	}
 4228:     }
 4229:     return \@titles,\%symbx;
 4230: }
 4231: 
 4232: #
 4233: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4234: sub displayPage {
 4235:     my ($request) = shift;
 4236: 
 4237:     my ($symb) = &get_symb($request);
 4238:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4239:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4240:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4241:     my $pageTitle = $env{'form.page'};
 4242:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4243:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4244:     my $usec=$classlist->{$env{'form.student'}}[5];
 4245: 
 4246:     #need to make sure we have the correct data for later EXT calls, 
 4247:     #thus invalidate the cache
 4248:     &Apache::lonnet::devalidatecourseresdata(
 4249:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4250:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4251:     &Apache::lonnet::clear_EXT_cache_status();
 4252: 
 4253:     if (!&canview($usec)) {
 4254: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4255: 	$request->print(&show_grading_menu_form($symb));
 4256: 	return;
 4257:     }
 4258:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4259:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4260: 	'</h3>'."\n";
 4261:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4262:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4263: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4264:     } else {
 4265: 	delete($env{'form.CODE'});
 4266:     }
 4267:     &sub_page_js($request);
 4268:     $request->print($result);
 4269: 
 4270:     my $navmap = Apache::lonnavmaps::navmap->new();
 4271:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4272:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4273:     if (!$map) {
 4274: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4275: 	$request->print(&show_grading_menu_form($symb));
 4276: 	return; 
 4277:     }
 4278:     my $iterator = $navmap->getIterator($map->map_start(),
 4279: 					$map->map_finish());
 4280: 
 4281:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4282: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4283: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4284: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4285: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4286: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4287: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4288: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4289: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4290: 
 4291:     if (defined($env{'form.CODE'})) {
 4292: 	$studentTable.=
 4293: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4294:     }
 4295:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4296: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4297: 
 4298:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4299: 	&Apache::loncommon::start_data_table().
 4300: 	&Apache::loncommon::start_data_table_header_row().
 4301: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4302: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4303: 	&Apache::loncommon::end_data_table_header_row();
 4304: 
 4305:     &Apache::lonxml::clear_problem_counter();
 4306:     my ($depth,$question,$prob) = (1,1,1);
 4307:     $iterator->next(); # skip the first BEGIN_MAP
 4308:     my $curRes = $iterator->next(); # for "current resource"
 4309:     while ($depth > 0) {
 4310:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4311:         if($curRes == $iterator->END_MAP) { $depth--; }
 4312: 
 4313:         if (ref($curRes) && $curRes->is_problem()) {
 4314: 	    my $parts = $curRes->parts();
 4315:             my $title = $curRes->compTitle();
 4316: 	    my $symbx = $curRes->symb();
 4317: 	    $studentTable.=
 4318: 		&Apache::loncommon::start_data_table_row().
 4319: 		'<td align="center" valign="top" >'.$prob.
 4320: 		(scalar(@{$parts}) == 1 ? '' 
 4321: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4322: 							scalar(@{$parts}))
 4323: 		 ).
 4324: 		 '</td>';
 4325: 	    $studentTable.='<td valign="top">';
 4326: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4327: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4328: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4329: 					     undef,'both',\%form);
 4330: 	    } else {
 4331: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4332: 		$companswer =~ s|<form(.*?)>||g;
 4333: 		$companswer =~ s|</form>||g;
 4334: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4335: #		    $companswer =~ s/$1/ /ms;
 4336: #		    $request->print('match='.$1."<br />\n");
 4337: #		}
 4338: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4339: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4340: 	    }
 4341: 
 4342: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4343: 
 4344: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4345: 		if ($record{'version'} eq '') {
 4346: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4347: 		} else {
 4348: 		    my %responseType = ();
 4349: 		    foreach my $partid (@{$parts}) {
 4350: 			my @responseIds =$curRes->responseIds($partid);
 4351: 			my @responseType =$curRes->responseType($partid);
 4352: 			my %responseIds;
 4353: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4354: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4355: 			}
 4356: 			$responseType{$partid} = \%responseIds;
 4357: 		    }
 4358: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4359: 
 4360: 		}
 4361: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4362: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4363: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4364: 									$env{'request.course.id'},
 4365: 									'','.submission');
 4366:  
 4367: 	    }
 4368: 	    if (&canmodify($usec)) {
 4369: 		foreach my $partid (@{$parts}) {
 4370: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4371: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4372: 		    $question++;
 4373: 		}
 4374: 		$prob++;
 4375: 	    }
 4376: 	    $studentTable.='</td></tr>';
 4377: 
 4378: 	}
 4379:         $curRes = $iterator->next();
 4380:     }
 4381: 
 4382:     $studentTable.='</table>'."\n".
 4383: 	'<input type="button" value="'.&mt('Save').'" '.
 4384: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4385: 	'</form>'."\n";
 4386:     $studentTable.=&show_grading_menu_form($symb);
 4387:     $request->print($studentTable);
 4388: 
 4389:     return '';
 4390: }
 4391: 
 4392: sub displaySubByDates {
 4393:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4394:     my $isCODE=0;
 4395:     my $isTask = ($symb =~/\.task$/);
 4396:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4397:     my $studentTable=&Apache::loncommon::start_data_table().
 4398: 	&Apache::loncommon::start_data_table_header_row().
 4399: 	'<th>'.&mt('Date/Time').'</th>'.
 4400: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4401: 	'<th>'.&mt('Submission').'</th>'.
 4402: 	'<th>'.&mt('Status').'</th>'.
 4403: 	&Apache::loncommon::end_data_table_header_row();
 4404:     my ($version);
 4405:     my %mark;
 4406:     my %orders;
 4407:     $mark{'correct_by_student'} = $checkIcon;
 4408:     if (!exists($$record{'1:timestamp'})) {
 4409: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4410:     }
 4411: 
 4412:     my $interaction;
 4413:     for ($version=1;$version<=$$record{'version'};$version++) {
 4414: 	my $timestamp = 
 4415: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4416: 	if (exists($$record{$version.':resource.0.version'})) {
 4417: 	    $interaction = $$record{$version.':resource.0.version'};
 4418: 	}
 4419: 
 4420: 	my $where = ($isTask ? "$version:resource.$interaction"
 4421: 		             : "$version:resource");
 4422: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4423: 	    '<td>'.$timestamp.'</td>';
 4424: 	if ($isCODE) {
 4425: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4426: 	}
 4427: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4428: 	my @displaySub = ();
 4429: 	foreach my $partid (@{$parts}) {
 4430: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4431: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4432: 	    
 4433: 
 4434: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4435: 	    my $display_part=&get_display_part($partid,$symb);
 4436: 	    foreach my $matchKey (@matchKey) {
 4437: 		if (exists($$record{$version.':'.$matchKey}) &&
 4438: 		    $$record{$version.':'.$matchKey} ne '') {
 4439: 
 4440: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4441: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4442: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4443: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4444: 			$responseId.')</span>&nbsp;<b>';
 4445: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4446: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4447: 		    } else {
 4448: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4449: 					    $$record{"$where.$partid.tries"});
 4450: 		    }
 4451: 		    my $responseType=($isTask ? 'Task'
 4452:                                               : $responseType->{$partid}->{$responseId});
 4453: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4454: 		    if (!exists($orders{$partid}->{$responseId})) {
 4455: 			$orders{$partid}->{$responseId}=
 4456: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4457: 		    }
 4458: 		    $displaySub[0].='</b>&nbsp; '.
 4459: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4460: 		}
 4461: 	    }
 4462: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4463: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4464: 				    $$record{"$where.$partid.checkedin"},
 4465: 				    $$record{"$where.$partid.checkedin.slot"}).
 4466: 					'<br />';
 4467: 	    }
 4468: 	    if (exists $$record{"$where.$partid.award"}) {
 4469: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4470: 		    lc($$record{"$where.$partid.award"}).' '.
 4471: 		    $mark{$$record{"$where.$partid.solved"}}.
 4472: 		    '<br />';
 4473: 	    }
 4474: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4475: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4476: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4477: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4478: 		$displaySub[2].=
 4479: 		    $$record{"$version:resource.$partid.regrader"}.
 4480: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4481: 	    }
 4482: 	}
 4483: 	# needed because old essay regrader has not parts info
 4484: 	if (exists $$record{"$version:resource.regrader"}) {
 4485: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4486: 	}
 4487: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4488: 	if ($displaySub[2]) {
 4489: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4490: 	}
 4491: 	$studentTable.='&nbsp;</td>'.
 4492: 	    &Apache::loncommon::end_data_table_row();
 4493:     }
 4494:     $studentTable.=&Apache::loncommon::end_data_table();
 4495:     return $studentTable;
 4496: }
 4497: 
 4498: sub updateGradeByPage {
 4499:     my ($request) = shift;
 4500: 
 4501:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4502:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4503:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4504:     my $pageTitle = $env{'form.page'};
 4505:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4506:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4507:     my $usec=$classlist->{$env{'form.student'}}[5];
 4508:     if (!&canmodify($usec)) {
 4509: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4510: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4511: 	return;
 4512:     }
 4513:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4514:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4515: 	'</h3>'."\n";
 4516: 
 4517:     $request->print($result);
 4518: 
 4519:     my $navmap = Apache::lonnavmaps::navmap->new();
 4520:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4521:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4522:     if (!$map) {
 4523: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4524: 	my ($symb)=&get_symb($request);
 4525: 	$request->print(&show_grading_menu_form($symb));
 4526: 	return; 
 4527:     }
 4528:     my $iterator = $navmap->getIterator($map->map_start(),
 4529: 					$map->map_finish());
 4530: 
 4531:     my $studentTable=
 4532: 	&Apache::loncommon::start_data_table().
 4533: 	&Apache::loncommon::start_data_table_header_row().
 4534: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4535: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4536: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4537: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4538: 	&Apache::loncommon::end_data_table_header_row();
 4539: 
 4540:     $iterator->next(); # skip the first BEGIN_MAP
 4541:     my $curRes = $iterator->next(); # for "current resource"
 4542:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4543:     while ($depth > 0) {
 4544:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4545:         if($curRes == $iterator->END_MAP) { $depth--; }
 4546: 
 4547:         if (ref($curRes) && $curRes->is_problem()) {
 4548: 	    my $parts = $curRes->parts();
 4549:             my $title = $curRes->compTitle();
 4550: 	    my $symbx = $curRes->symb();
 4551: 	    $studentTable.=
 4552: 		&Apache::loncommon::start_data_table_row().
 4553: 		'<td align="center" valign="top" >'.$prob.
 4554: 		(scalar(@{$parts}) == 1 ? '' 
 4555:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
 4556: 		 ).')</td>';
 4557: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4558: 
 4559: 	    my %newrecord=();
 4560: 	    my @displayPts=();
 4561:             my %aggregate = ();
 4562:             my $aggregateflag = 0;
 4563: 	    foreach my $partid (@{$parts}) {
 4564: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4565: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4566: 
 4567: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4568: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4569: 		my $partial = $newpts/$wgt;
 4570: 		my $score;
 4571: 		if ($partial > 0) {
 4572: 		    $score = 'correct_by_override';
 4573: 		} elsif ($newpts ne '') { #empty is taken as 0
 4574: 		    $score = 'incorrect_by_override';
 4575: 		}
 4576: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4577: 		if ($dropMenu eq 'excused') {
 4578: 		    $partial = '';
 4579: 		    $score = 'excused';
 4580: 		} elsif ($dropMenu eq 'reset status'
 4581: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4582: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4583: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4584: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4585: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4586: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4587: 		    $changeflag++;
 4588: 		    $newpts = '';
 4589:                     
 4590:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4591:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4592:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4593:                     if ($aggtries > 0) {
 4594:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4595:                         $aggregateflag = 1;
 4596:                     }
 4597: 		}
 4598: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4599: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4600: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4601: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4602: 		    '&nbsp;<br />';
 4603: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4604: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4605: 		    '&nbsp;<br />';
 4606: 		$question++;
 4607: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4608: 
 4609: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4610: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4611: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4612: 		    if (scalar(keys(%newrecord)) > 0);
 4613: 
 4614: 		$changeflag++;
 4615: 	    }
 4616: 	    if (scalar(keys(%newrecord)) > 0) {
 4617: 		my %record = 
 4618: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4619: 					     $udom,$uname);
 4620: 
 4621: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4622: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4623: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4624: 		    $newrecord{'resource.CODE'} = '';
 4625: 		}
 4626: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4627: 					$udom,$uname);
 4628: 		%record = &Apache::lonnet::restore($symbx,
 4629: 						   $env{'request.course.id'},
 4630: 						   $udom,$uname);
 4631: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4632: 					     $cdom,$cnum,$udom,$uname);
 4633: 	    }
 4634: 	    
 4635:             if ($aggregateflag) {
 4636:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4637:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4638:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4639:             }
 4640: 
 4641: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4642: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4643: 		&Apache::loncommon::end_data_table_row();
 4644: 
 4645: 	    $prob++;
 4646: 	}
 4647:         $curRes = $iterator->next();
 4648:     }
 4649: 
 4650:     $studentTable.=&Apache::loncommon::end_data_table();
 4651:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4652:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4653: 		  'The scores were changed for '.
 4654: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4655:     $request->print($grademsg.$studentTable);
 4656: 
 4657:     return '';
 4658: }
 4659: 
 4660: #-------- end of section for handling grading by page/sequence ---------
 4661: #
 4662: #-------------------------------------------------------------------
 4663: 
 4664: #--------------------Scantron Grading-----------------------------------
 4665: #
 4666: #------ start of section for handling grading by page/sequence ---------
 4667: 
 4668: =pod
 4669: 
 4670: =head1 Bubble sheet grading routines
 4671: 
 4672:   For this documentation:
 4673: 
 4674:    'scanline' refers to the full line of characters
 4675:    from the file that we are parsing that represents one entire sheet
 4676: 
 4677:    'bubble line' refers to the data
 4678:    representing the line of bubbles that are on the physical bubble sheet
 4679: 
 4680: 
 4681: The overall process is that a scanned in bubble sheet data is uploaded
 4682: into a course. When a user wants to grade, they select a
 4683: sequence/folder of resources, a file of bubble sheet info, and pick
 4684: one of the predefined configurations for what each scanline looks
 4685: like.
 4686: 
 4687: Next each scanline is checked for any errors of either 'missing
 4688: bubbles' (it's an error because it may have been mis-scanned
 4689: because too light bubbling), 'double bubble' (each bubble line should
 4690: have no more that one letter picked), invalid or duplicated CODE,
 4691: invalid student ID
 4692: 
 4693: If the CODE option is used that determines the randomization of the
 4694: homework problems, either way the student ID is looked up into a
 4695: username:domain.
 4696: 
 4697: During the validation phase the instructor can choose to skip scanlines. 
 4698: 
 4699: After the validation phase, there are now 3 bubble sheet files
 4700: 
 4701:   scantron_original_filename (unmodified original file)
 4702:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4703:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4704: 
 4705: Also there is a separate hash nohist_scantrondata that contains extra
 4706: correction information that isn't representable in the bubble sheet
 4707: file (see &scantron_getfile() for more information)
 4708: 
 4709: After all scanlines are either valid, marked as valid or skipped, then
 4710: foreach line foreach problem in the picked sequence, an ssi request is
 4711: made that simulates a user submitting their selected letter(s) against
 4712: the homework problem.
 4713: 
 4714: =over 4
 4715: 
 4716: 
 4717: 
 4718: =item defaultFormData
 4719: 
 4720:   Returns html hidden inputs used to hold context/default values.
 4721: 
 4722:  Arguments:
 4723:   $symb - $symb of the current resource 
 4724: 
 4725: =cut
 4726: 
 4727: sub defaultFormData {
 4728:     my ($symb)=@_;
 4729:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4730:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4731:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4732: }
 4733: 
 4734: 
 4735: =pod 
 4736: 
 4737: =item getSequenceDropDown
 4738: 
 4739:    Return html dropdown of possible sequences to grade
 4740:  
 4741:  Arguments:
 4742:    $symb - $symb of the current resource 
 4743: 
 4744: =cut
 4745: 
 4746: sub getSequenceDropDown {
 4747:     my ($symb)=@_;
 4748:     my $result='<select name="selectpage">'."\n";
 4749:     my ($titles,$symbx) = &getSymbMap();
 4750:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4751:     my $ctr=0;
 4752:     foreach (@$titles) {
 4753: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4754: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4755: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4756: 	    '>'.$showtitle.'</option>'."\n";
 4757: 	$ctr++;
 4758:     }
 4759:     $result.= '</select>';
 4760:     return $result;
 4761: }
 4762: 
 4763: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4764:                                    # index is "symb.part_id"
 4765: 
 4766: my %first_bubble_line;             # First bubble line no. for each bubble.
 4767: 
 4768: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4769:                                    # matchresponse or rankresponse, where 
 4770:                                    # an individual response can have multiple 
 4771:                                    # lines
 4772: 
 4773: my %responsetype_per_response;     # responsetype for each response
 4774: 
 4775: # Save and restore the bubble lines array to the form env.
 4776: 
 4777: 
 4778: sub save_bubble_lines {
 4779:     foreach my $line (keys(%bubble_lines_per_response)) {
 4780: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4781: 	$env{"form.scantron.first_bubble_line.$line"} =
 4782: 	    $first_bubble_line{$line};
 4783:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4784:             $subdivided_bubble_lines{$line};
 4785:         $env{"form.scantron.responsetype.$line"} =
 4786:             $responsetype_per_response{$line};
 4787:     }
 4788: }
 4789: 
 4790: 
 4791: sub restore_bubble_lines {
 4792:     my $line = 0;
 4793:     %bubble_lines_per_response = ();
 4794:     while ($env{"form.scantron.bubblelines.$line"}) {
 4795: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4796: 	$bubble_lines_per_response{$line} = $value;
 4797: 	$first_bubble_line{$line}  =
 4798: 	    $env{"form.scantron.first_bubble_line.$line"};
 4799:         $subdivided_bubble_lines{$line} =
 4800:             $env{"form.scantron.sub_bubblelines.$line"};
 4801:         $responsetype_per_response{$line} =
 4802:             $env{"form.scantron.responsetype.$line"};
 4803: 	$line++;
 4804:     }
 4805: 
 4806: }
 4807: 
 4808: #  Given the parsed scanline, get the response for 
 4809: #  'answer' number n:
 4810: 
 4811: sub get_response_bubbles {
 4812:     my ($parsed_line, $response)  = @_;
 4813: 
 4814: 
 4815:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4816:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4817:     
 4818:     my $selected = "";
 4819: 
 4820:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4821: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4822: 	$bubble_line++;
 4823:     }
 4824:     return $selected;
 4825: }
 4826: 
 4827: =pod 
 4828: 
 4829: =item scantron_filenames
 4830: 
 4831:    Returns a list of the scantron files in the current course 
 4832: 
 4833: =cut
 4834: 
 4835: sub scantron_filenames {
 4836:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4837:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4838:     my $getpropath = 1;
 4839:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4840:                                        $getpropath);
 4841:     my @possiblenames;
 4842:     foreach my $filename (sort(@files)) {
 4843: 	($filename)=split(/&/,$filename);
 4844: 	if ($filename!~/^scantron_orig_/) { next ; }
 4845: 	$filename=~s/^scantron_orig_//;
 4846: 	push(@possiblenames,$filename);
 4847:     }
 4848:     return @possiblenames;
 4849: }
 4850: 
 4851: =pod 
 4852: 
 4853: =item scantron_uploads
 4854: 
 4855:    Returns  html drop-down list of scantron files in current course.
 4856: 
 4857:  Arguments:
 4858:    $file2grade - filename to set as selected in the dropdown
 4859: 
 4860: =cut
 4861: 
 4862: sub scantron_uploads {
 4863:     my ($file2grade) = @_;
 4864:     my $result=	'<select name="scantron_selectfile">';
 4865:     $result.="<option></option>";
 4866:     foreach my $filename (sort(&scantron_filenames())) {
 4867: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4868:     }
 4869:     $result.="</select>";
 4870:     return $result;
 4871: }
 4872: 
 4873: =pod 
 4874: 
 4875: =item scantron_scantab
 4876: 
 4877:   Returns html drop down of the scantron formats in the scantronformat.tab
 4878:   file.
 4879: 
 4880: =cut
 4881: 
 4882: sub scantron_scantab {
 4883:     my $result='<select name="scantron_format">'."\n";
 4884:     $result.='<option></option>'."\n";
 4885:     my @lines = &get_scantronformat_file();
 4886:     if (@lines > 0) {
 4887:         foreach my $line (@lines) {
 4888:             next if (($line =~ /^\#/) || ($line eq ''));
 4889: 	    my ($name,$descrip)=split(/:/,$line);
 4890: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4891:         }
 4892:     }
 4893:     $result.='</select>'."\n";
 4894:     return $result;
 4895: }
 4896: 
 4897: =pod
 4898: 
 4899: =item get_scantronformat_file
 4900: 
 4901:   Returns an array containing lines from the scantron format file for
 4902:   the domain of the course.
 4903: 
 4904:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4905:   lines are from this file.
 4906: 
 4907:   Otherwise, if a default.tab has been published in RES space by the 
 4908:   domainconfig user, lines are from this file.
 4909: 
 4910:   Otherwise, fall back to getting lines from the legacy file on the
 4911:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4912: 
 4913: =cut
 4914: 
 4915: sub get_scantronformat_file {
 4916:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4917:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4918:     my $gottab = 0;
 4919:     my @lines;
 4920:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4921:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4922:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4923:             if ($formatfile ne '-1') {
 4924:                 @lines = split("\n",$formatfile,-1);
 4925:                 $gottab = 1;
 4926:             }
 4927:         }
 4928:     }
 4929:     if (!$gottab) {
 4930:         my $confname = $cdom.'-domainconfig';
 4931:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4932:         my $formatfile =  &Apache::lonnet::getfile($default);
 4933:         if ($formatfile ne '-1') {
 4934:             @lines = split("\n",$formatfile,-1);
 4935:             $gottab = 1;
 4936:         }
 4937:     }
 4938:     if (!$gottab) {
 4939:         my @domains = &Apache::lonnet::current_machine_domains();
 4940:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4941:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4942:             @lines = <$fh>;
 4943:             close($fh);
 4944:         } else {
 4945:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4946:             @lines = <$fh>;
 4947:             close($fh);
 4948:         }
 4949:     }
 4950:     return @lines;
 4951: }
 4952: 
 4953: =pod 
 4954: 
 4955: =item scantron_CODElist
 4956: 
 4957:   Returns html drop down of the saved CODE lists from current course,
 4958:   generated from earlier printings.
 4959: 
 4960: =cut
 4961: 
 4962: sub scantron_CODElist {
 4963:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4964:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4965:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4966:     my $namechoice='<option></option>';
 4967:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4968: 	if ($name =~ /^error: 2 /) { next; }
 4969: 	if ($name =~ /^type\0/) { next; }
 4970: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4971:     }
 4972:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4973:     return $namechoice;
 4974: }
 4975: 
 4976: =pod 
 4977: 
 4978: =item scantron_CODEunique
 4979: 
 4980:   Returns the html for "Each CODE to be used once" radio.
 4981: 
 4982: =cut
 4983: 
 4984: sub scantron_CODEunique {
 4985:     my $result='<span style="white-space: nowrap;">
 4986:                  <label><input type="radio" name="scantron_CODEunique"
 4987:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4988:                 </span>
 4989:                 <span style="white-space: nowrap;">
 4990:                  <label><input type="radio" name="scantron_CODEunique"
 4991:                         value="no" />'.&mt('No').' </label>
 4992:                 </span>';
 4993:     return $result;
 4994: }
 4995: 
 4996: =pod 
 4997: 
 4998: =item scantron_selectphase
 4999: 
 5000:   Generates the initial screen to start the bubble sheet process.
 5001:   Allows for - starting a grading run.
 5002:              - downloading existing scan data (original, corrected
 5003:                                                 or skipped info)
 5004: 
 5005:              - uploading new scan data
 5006: 
 5007:  Arguments:
 5008:   $r          - The Apache request object
 5009:   $file2grade - name of the file that contain the scanned data to score
 5010: 
 5011: =cut
 5012: 
 5013: sub scantron_selectphase {
 5014:     my ($r,$file2grade) = @_;
 5015:     my ($symb)=&get_symb($r);
 5016:     if (!$symb) {return '';}
 5017:     my $sequence_selector=&getSequenceDropDown($symb);
 5018:     my $default_form_data=&defaultFormData($symb);
 5019:     my $grading_menu_button=&show_grading_menu_form($symb);
 5020:     my $file_selector=&scantron_uploads($file2grade);
 5021:     my $format_selector=&scantron_scantab();
 5022:     my $CODE_selector=&scantron_CODElist();
 5023:     my $CODE_unique=&scantron_CODEunique();
 5024:     my $result;
 5025: 
 5026:     $ssi_error = 0;
 5027: 
 5028:     # Chunk of form to prompt for a file to grade and how:
 5029: 
 5030:     $result.= '
 5031:     <br />
 5032:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5033:     <input type="hidden" name="command" value="scantron_warning" />
 5034:     '.$default_form_data.'
 5035:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5036:        '.&Apache::loncommon::start_data_table_header_row().'
 5037:             <th colspan="2">
 5038:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5039:             </th>
 5040:        '.&Apache::loncommon::end_data_table_header_row().'
 5041:        '.&Apache::loncommon::start_data_table_row().'
 5042:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5043:        '.&Apache::loncommon::end_data_table_row().'
 5044:        '.&Apache::loncommon::start_data_table_row().'
 5045:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5046:        '.&Apache::loncommon::end_data_table_row().'
 5047:        '.&Apache::loncommon::start_data_table_row().'
 5048:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5049:        '.&Apache::loncommon::end_data_table_row().'
 5050:        '.&Apache::loncommon::start_data_table_row().'
 5051:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5052:        '.&Apache::loncommon::end_data_table_row().'
 5053:        '.&Apache::loncommon::start_data_table_row().'
 5054:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5055:        '.&Apache::loncommon::end_data_table_row().'
 5056:        '.&Apache::loncommon::start_data_table_row().'
 5057: 	    <td> '.&mt('Options:').' </td>
 5058:             <td>
 5059: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5060:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5061:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5062: 	    </td>
 5063:        '.&Apache::loncommon::end_data_table_row().'
 5064:        '.&Apache::loncommon::start_data_table_row().'
 5065:             <td colspan="2">
 5066:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5067:             </td>
 5068:        '.&Apache::loncommon::end_data_table_row().'
 5069:     '.&Apache::loncommon::end_data_table().'
 5070:     </form>
 5071: ';
 5072:    
 5073:     $r->print($result);
 5074: 
 5075:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5076:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5077: 
 5078: 	# Chunk of form to prompt for a scantron file upload.
 5079: 
 5080:         $r->print('
 5081:     <br />
 5082:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5083:        '.&Apache::loncommon::start_data_table_header_row().'
 5084:             <th>
 5085:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5086:             </th>
 5087:        '.&Apache::loncommon::end_data_table_header_row().'
 5088:        '.&Apache::loncommon::start_data_table_row().'
 5089:             <td>
 5090: ');
 5091:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5092:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5093:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5094:     $r->print('
 5095:               <script type="text/javascript" language="javascript">
 5096:     function checkUpload(formname) {
 5097: 	if (formname.upfile.value == "") {
 5098: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5099: 	    return false;
 5100: 	}
 5101: 	formname.submit();
 5102:     }
 5103:               </script>
 5104: 
 5105:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5106:                 '.$default_form_data.'
 5107:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5108:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5109:                 <input name="command" value="scantronupload_save" type="hidden" />
 5110:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5111:                 <br />
 5112:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5113:               </form>
 5114: ');
 5115: 
 5116:         $r->print('
 5117:             </td>
 5118:        '.&Apache::loncommon::end_data_table_row().'
 5119:        '.&Apache::loncommon::end_data_table().'
 5120: ');
 5121:     }
 5122: 
 5123:     # Chunk of the form that prompts to view a scoring office file,
 5124:     # corrected file, skipped records in a file.
 5125: 
 5126:     $r->print('
 5127:    <br />
 5128:    <form action="/adm/grades" name="scantron_download">
 5129:      '.$default_form_data.'
 5130:      <input type="hidden" name="command" value="scantron_download" />
 5131:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5132:        '.&Apache::loncommon::start_data_table_header_row().'
 5133:               <th>
 5134:                 &nbsp;'.&mt('Download a scoring office file').'
 5135:               </th>
 5136:        '.&Apache::loncommon::end_data_table_header_row().'
 5137:        '.&Apache::loncommon::start_data_table_row().'
 5138:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5139:                 <br />
 5140:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5141:        '.&Apache::loncommon::end_data_table_row().'
 5142:      '.&Apache::loncommon::end_data_table().'
 5143:    </form>
 5144:    <br />
 5145: ');
 5146: 
 5147:     &Apache::lonpickcode::code_list($r,2);
 5148:     $r->print($grading_menu_button);
 5149:     return
 5150: }
 5151: 
 5152: =pod
 5153: 
 5154: =item get_scantron_config
 5155: 
 5156:    Parse and return the scantron configuration line selected as a
 5157:    hash of configuration file fields.
 5158: 
 5159:  Arguments:
 5160:     which - the name of the configuration to parse from the file.
 5161: 
 5162: 
 5163:  Returns:
 5164:             If the named configuration is not in the file, an empty
 5165:             hash is returned.
 5166:     a hash with the fields
 5167:       name         - internal name for the this configuration setup
 5168:       description  - text to display to operator that describes this config
 5169:       CODElocation - if 0 or the string 'none'
 5170:                           - no CODE exists for this config
 5171:                      if -1 || the string 'letter'
 5172:                           - a CODE exists for this config and is
 5173:                             a string of letters
 5174:                      Unsupported value (but planned for future support)
 5175:                           if a positive integer
 5176:                                - The CODE exists as the first n items from
 5177:                                  the question section of the form
 5178:                           if the string 'number'
 5179:                                - The CODE exists for this config and is
 5180:                                  a string of numbers
 5181:       CODEstart   - (only matter if a CODE exists) column in the line where
 5182:                      the CODE starts
 5183:       CODElength  - length of the CODE
 5184:       IDstart     - column where the student ID number starts
 5185:       IDlength    - length of the student ID info
 5186:       Qstart      - column where the information from the bubbled
 5187:                     'questions' start
 5188:       Qlength     - number of columns comprising a single bubble line from
 5189:                     the sheet. (usually either 1 or 10)
 5190:       Qon         - either a single character representing the character used
 5191:                     to signal a bubble was chosen in the positional setup, or
 5192:                     the string 'letter' if the letter of the chosen bubble is
 5193:                     in the final, or 'number' if a number representing the
 5194:                     chosen bubble is in the file (1->A 0->J)
 5195:       Qoff        - the character used to represent that a bubble was
 5196:                     left blank
 5197:       PaperID     - if the scanning process generates a unique number for each
 5198:                     sheet scanned the column that this ID number starts in
 5199:       PaperIDlength - number of columns that comprise the unique ID number
 5200:                       for the sheet of paper
 5201:       FirstName   - column that the first name starts in
 5202:       FirstNameLength - number of columns that the first name spans
 5203:  
 5204:       LastName    - column that the last name starts in
 5205:       LastNameLength - number of columns that the last name spans
 5206: 
 5207: =cut
 5208: 
 5209: sub get_scantron_config {
 5210:     my ($which) = @_;
 5211:     my @lines = &get_scantronformat_file();
 5212:     my %config;
 5213:     #FIXME probably should move to XML it has already gotten a bit much now
 5214:     foreach my $line (@lines) {
 5215: 	my ($name,$descrip)=split(/:/,$line);
 5216: 	if ($name ne $which ) { next; }
 5217: 	chomp($line);
 5218: 	my @config=split(/:/,$line);
 5219: 	$config{'name'}=$config[0];
 5220: 	$config{'description'}=$config[1];
 5221: 	$config{'CODElocation'}=$config[2];
 5222: 	$config{'CODEstart'}=$config[3];
 5223: 	$config{'CODElength'}=$config[4];
 5224: 	$config{'IDstart'}=$config[5];
 5225: 	$config{'IDlength'}=$config[6];
 5226: 	$config{'Qstart'}=$config[7];
 5227:  	$config{'Qlength'}=$config[8];
 5228: 	$config{'Qoff'}=$config[9];
 5229: 	$config{'Qon'}=$config[10];
 5230: 	$config{'PaperID'}=$config[11];
 5231: 	$config{'PaperIDlength'}=$config[12];
 5232: 	$config{'FirstName'}=$config[13];
 5233: 	$config{'FirstNamelength'}=$config[14];
 5234: 	$config{'LastName'}=$config[15];
 5235: 	$config{'LastNamelength'}=$config[16];
 5236: 	last;
 5237:     }
 5238:     return %config;
 5239: }
 5240: 
 5241: =pod 
 5242: 
 5243: =item username_to_idmap
 5244: 
 5245:     creates a hash keyed by student id with values of the corresponding
 5246:     student username:domain.
 5247: 
 5248:   Arguments:
 5249: 
 5250:     $classlist - reference to the class list hash. This is a hash
 5251:                  keyed by student name:domain  whose elements are references
 5252:                  to arrays containing various chunks of information
 5253:                  about the student. (See loncoursedata for more info).
 5254: 
 5255:   Returns
 5256:     %idmap - the constructed hash
 5257: 
 5258: =cut
 5259: 
 5260: sub username_to_idmap {
 5261:     my ($classlist)= @_;
 5262:     my %idmap;
 5263:     foreach my $student (keys(%$classlist)) {
 5264: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5265: 	    $student;
 5266:     }
 5267:     return %idmap;
 5268: }
 5269: 
 5270: =pod
 5271: 
 5272: =item scantron_fixup_scanline
 5273: 
 5274:    Process a requested correction to a scanline.
 5275: 
 5276:   Arguments:
 5277:     $scantron_config   - hash from &get_scantron_config()
 5278:     $scan_data         - hash of correction information 
 5279:                           (see &scantron_getfile())
 5280:     $line              - existing scanline
 5281:     $whichline         - line number of the passed in scanline
 5282:     $field             - type of change to process 
 5283:                          (either 
 5284:                           'ID'     -> correct the student ID number
 5285:                           'CODE'   -> correct the CODE
 5286:                           'answer' -> fixup the submitted answers)
 5287:     
 5288:    $args               - hash of additional info,
 5289:                           - 'ID' 
 5290:                                'newid' -> studentID to use in replacement
 5291:                                           of existing one
 5292:                           - 'CODE' 
 5293:                                'CODE_ignore_dup' - set to true if duplicates
 5294:                                                    should be ignored.
 5295: 	                       'CODE' - is new code or 'use_unfound'
 5296:                                         if the existing unfound code should
 5297:                                         be used as is
 5298:                           - 'answer'
 5299:                                'response' - new answer or 'none' if blank
 5300:                                'question' - the bubble line to change
 5301:                                'questionnum' - the question identifier,
 5302:                                                may include subquestion. 
 5303: 
 5304:   Returns:
 5305:     $line - the modified scanline
 5306: 
 5307:   Side effects: 
 5308:     $scan_data - may be updated
 5309: 
 5310: =cut
 5311: 
 5312: 
 5313: sub scantron_fixup_scanline {
 5314:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5315:     if ($field eq 'ID') {
 5316: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5317: 	    return ($line,1,'New value too large');
 5318: 	}
 5319: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5320: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5321: 				     $args->{'newid'});
 5322: 	}
 5323: 	substr($line,$$scantron_config{'IDstart'}-1,
 5324: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5325: 	if ($args->{'newid'}=~/^\s*$/) {
 5326: 	    &scan_data($scan_data,"$whichline.user",
 5327: 		       $args->{'username'}.':'.$args->{'domain'});
 5328: 	}
 5329:     } elsif ($field eq 'CODE') {
 5330: 	if ($args->{'CODE_ignore_dup'}) {
 5331: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5332: 	}
 5333: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5334: 	if ($args->{'CODE'} ne 'use_unfound') {
 5335: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5336: 		return ($line,1,'New CODE value too large');
 5337: 	    }
 5338: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5339: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5340: 	    }
 5341: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5342: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5343: 	}
 5344:     } elsif ($field eq 'answer') {
 5345: 	my $length=$scantron_config->{'Qlength'};
 5346: 	my $off=$scantron_config->{'Qoff'};
 5347: 	my $on=$scantron_config->{'Qon'};
 5348: 	my $answer=${off}x$length;
 5349: 	if ($args->{'response'} eq 'none') {
 5350: 	    &scan_data($scan_data,
 5351: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5352: 	} else {
 5353: 	    if ($on eq 'letter') {
 5354: 		my @alphabet=('A'..'Z');
 5355: 		$answer=$alphabet[$args->{'response'}];
 5356: 	    } elsif ($on eq 'number') {
 5357: 		$answer=$args->{'response'}+1;
 5358: 		if ($answer == 10) { $answer = '0'; }
 5359: 	    } else {
 5360: 		substr($answer,$args->{'response'},1)=$on;
 5361: 	    }
 5362: 	    &scan_data($scan_data,
 5363: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5364: 	}
 5365: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5366: 	substr($line,$where-1,$length)=$answer;
 5367:     }
 5368:     return $line;
 5369: }
 5370: 
 5371: =pod
 5372: 
 5373: =item scan_data
 5374: 
 5375:     Edit or look up  an item in the scan_data hash.
 5376: 
 5377:   Arguments:
 5378:     $scan_data  - The hash (see scantron_getfile)
 5379:     $key        - shorthand of the key to edit (actual key is
 5380:                   scantronfilename_key).
 5381:     $data        - New value of the hash entry.
 5382:     $delete      - If true, the entry is removed from the hash.
 5383: 
 5384:   Returns:
 5385:     The new value of the hash table field (undefined if deleted).
 5386: 
 5387: =cut
 5388: 
 5389: 
 5390: sub scan_data {
 5391:     my ($scan_data,$key,$value,$delete)=@_;
 5392:     my $filename=$env{'form.scantron_selectfile'};
 5393:     if (defined($value)) {
 5394: 	$scan_data->{$filename.'_'.$key} = $value;
 5395:     }
 5396:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5397:     return $scan_data->{$filename.'_'.$key};
 5398: }
 5399: 
 5400: # ----- These first few routines are general use routines.----
 5401: 
 5402: # Return the number of occurences of a pattern in a string.
 5403: 
 5404: sub occurence_count {
 5405:     my ($string, $pattern) = @_;
 5406: 
 5407:     my @matches = ($string =~ /$pattern/g);
 5408: 
 5409:     return scalar(@matches);
 5410: }
 5411: 
 5412: 
 5413: # Take a string known to have digits and convert all the
 5414: # digits into letters in the range J,A..I.
 5415: 
 5416: sub digits_to_letters {
 5417:     my ($input) = @_;
 5418: 
 5419:     my @alphabet = ('J', 'A'..'I');
 5420: 
 5421:     my @input    = split(//, $input);
 5422:     my $output ='';
 5423:     for (my $i = 0; $i < scalar(@input); $i++) {
 5424: 	if ($input[$i] =~ /\d/) {
 5425: 	    $output .= $alphabet[$input[$i]];
 5426: 	} else {
 5427: 	    $output .= $input[$i];
 5428: 	}
 5429:     }
 5430:     return $output;
 5431: }
 5432: 
 5433: =pod 
 5434: 
 5435: =item scantron_parse_scanline
 5436: 
 5437:   Decodes a scanline from the selected scantron file
 5438: 
 5439:  Arguments:
 5440:     line             - The text of the scantron file line to process
 5441:     whichline        - Line number
 5442:     scantron_config  - Hash describing the format of the scantron lines.
 5443:     scan_data        - Hash of extra information about the scanline
 5444:                        (see scantron_getfile for more information)
 5445:     just_header      - True if should not process question answers but only
 5446:                        the stuff to the left of the answers.
 5447:  Returns:
 5448:    Hash containing the result of parsing the scanline
 5449: 
 5450:    Keys are all proceeded by the string 'scantron.'
 5451: 
 5452:        CODE    - the CODE in use for this scanline
 5453:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5454:                  by the operator
 5455:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5456:                             CODEs were selected, but the usage has been
 5457:                             forced by the operator
 5458:        ID  - student ID
 5459:        PaperID - if used, the ID number printed on the sheet when the 
 5460:                  paper was scanned
 5461:        FirstName - first name from the sheet
 5462:        LastName  - last name from the sheet
 5463: 
 5464:      if just_header was not true these key may also exist
 5465: 
 5466:        missingerror - a list of bubble ranges that are considered to be answers
 5467:                       to a single question that don't have any bubbles filled in.
 5468:                       Of the form questionnumber:firstbubblenumber:count.
 5469:        doubleerror  - a list of bubble ranges that are considered to be answers
 5470:                       to a single question that have more than one bubble filled in.
 5471:                       Of the form questionnumber::firstbubblenumber:count
 5472:    
 5473:                 In the above, count is the number of bubble responses in the
 5474:                 input line needed to represent the possible answers to the question.
 5475:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5476:                 per line would have count = 2.
 5477: 
 5478:        maxquest     - the number of the last bubble line that was parsed
 5479: 
 5480:        (<number> starts at 1)
 5481:        <number>.answer - zero or more letters representing the selected
 5482:                          letters from the scanline for the bubble line 
 5483:                          <number>.
 5484:                          if blank there was either no bubble or there where
 5485:                          multiple bubbles, (consult the keys missingerror and
 5486:                          doubleerror if this is an error condition)
 5487: 
 5488: =cut
 5489: 
 5490: sub scantron_parse_scanline {
 5491:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5492: 
 5493:     my %record;
 5494:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5495:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5496:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5497: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5498: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5499: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5500: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5501: 	    $record{'scantron.CODE'}=substr($data,
 5502: 					    $$scantron_config{'CODEstart'}-1,
 5503: 					    $$scantron_config{'CODElength'});
 5504: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5505: 		$record{'scantron.useCODE'}=1;
 5506: 	    }
 5507: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5508: 		$record{'scantron.CODE_ignore_dup'}=1;
 5509: 	    }
 5510: 	} else {
 5511: 	    #FIXME interpret first N questions
 5512: 	}
 5513:     }
 5514:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5515: 				  $$scantron_config{'IDlength'});
 5516:     $record{'scantron.PaperID'}=
 5517: 	substr($data,$$scantron_config{'PaperID'}-1,
 5518: 	       $$scantron_config{'PaperIDlength'});
 5519:     $record{'scantron.FirstName'}=
 5520: 	substr($data,$$scantron_config{'FirstName'}-1,
 5521: 	       $$scantron_config{'FirstNamelength'});
 5522:     $record{'scantron.LastName'}=
 5523: 	substr($data,$$scantron_config{'LastName'}-1,
 5524: 	       $$scantron_config{'LastNamelength'});
 5525:     if ($just_header) { return \%record; }
 5526: 
 5527:     my @alphabet=('A'..'Z');
 5528:     my $questnum=0;
 5529:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5530: 
 5531:     chomp($questions);		# Get rid of any trailing \n.
 5532:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5533:     while (length($questions)) {
 5534: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5535:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5536:                              || 1;
 5537:         $questnum++;
 5538:         my $quest_id = $questnum;
 5539:         my $currentquest = substr($questions,0,$answer_length);
 5540:         $questions       = substr($questions,$answer_length);
 5541:         if (length($currentquest) < $answer_length) { next; }
 5542: 
 5543:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5544:             my $subquestnum = 1;
 5545:             my $subquestions = $currentquest;
 5546:             my @subanswers_needed = 
 5547:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5548:             foreach my $subans (@subanswers_needed) {
 5549:                 my $subans_length =
 5550:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5551:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5552:                 $subquestions   = substr($subquestions,$subans_length);
 5553:                 $quest_id = "$questnum.$subquestnum";
 5554:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5555:                     ($$scantron_config{'Qon'} eq 'number')) {
 5556:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5557:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5558:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5559:                 } else {
 5560:                     $ansnum = &scantron_validator_positional($ansnum,
 5561:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5562:                 }
 5563:                 $subquestnum ++;
 5564:             }
 5565:         } else {
 5566:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5567:                 ($$scantron_config{'Qon'} eq 'number')) {
 5568:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5569:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5570:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5571:             } else {
 5572:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5573:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5574:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5575:             }
 5576:         }
 5577:     }
 5578:     $record{'scantron.maxquest'}=$questnum;
 5579:     return \%record;
 5580: }
 5581: 
 5582: sub scantron_validator_lettnum {
 5583:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5584:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5585: 
 5586:     # Qon 'letter' implies for each slot in currquest we have:
 5587:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5588:     #    about anything else (esp. a value of Qoff) for missing
 5589:     #    bubbles.
 5590:     #
 5591:     # Qon 'number' implies each slot gives a digit that indexes the
 5592:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5593:     #    and * or ? for double bubbles on a single line.
 5594:     #
 5595: 
 5596:     my $matchon;
 5597:     if ($$scantron_config{'Qon'} eq 'letter') {
 5598:         $matchon = '[A-Z]';
 5599:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5600:         $matchon = '\d';
 5601:     }
 5602:     my $occurrences = 0;
 5603:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5604:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5605:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5606:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5607:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5608:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5609:         my @singlelines = split('',$currquest);
 5610:         foreach my $entry (@singlelines) {
 5611:             $occurrences = &occurence_count($entry,$matchon);
 5612:             if ($occurrences > 1) {
 5613:                 last;
 5614:             }
 5615:         } 
 5616:     } else {
 5617:         $occurrences = &occurence_count($currquest,$matchon); 
 5618:     }
 5619:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5620:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5621:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5622:             my $bubble = substr($currquest,$ans,1);
 5623:             if ($bubble =~ /$matchon/ ) {
 5624:                 if ($$scantron_config{'Qon'} eq 'number') {
 5625:                     if ($bubble == 0) {
 5626:                         $bubble = 10; 
 5627:                     }
 5628:                     $record->{"scantron.$ansnum.answer"} = 
 5629:                         $alphabet->[$bubble-1];
 5630:                 } else {
 5631:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5632:                 }
 5633:             } else {
 5634:                 $record->{"scantron.$ansnum.answer"}='';
 5635:             }
 5636:             $ansnum++;
 5637:         }
 5638:     } elsif (!defined($currquest)
 5639:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5640:             || (&occurence_count($currquest,$matchon) == 0)) {
 5641:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5642:             $record->{"scantron.$ansnum.answer"}='';
 5643:             $ansnum++;
 5644:         }
 5645:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5646:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5647:         }
 5648:     } else {
 5649:         if ($$scantron_config{'Qon'} eq 'number') {
 5650:             $currquest = &digits_to_letters($currquest);            
 5651:         }
 5652:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5653:             my $bubble = substr($currquest,$ans,1);
 5654:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5655:             $ansnum++;
 5656:         }
 5657:     }
 5658:     return $ansnum;
 5659: }
 5660: 
 5661: sub scantron_validator_positional {
 5662:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5663:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5664: 
 5665:     # Otherwise there's a positional notation;
 5666:     # each bubble line requires Qlength items, and there are filled in
 5667:     # bubbles for each case where there 'Qon' characters.
 5668:     #
 5669: 
 5670:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5671: 
 5672:     # If the split only gives us one element.. the full length of the
 5673:     # answer string, no bubbles are filled in:
 5674: 
 5675:     if ($answers_needed eq '') {
 5676:         return;
 5677:     }
 5678: 
 5679:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5680:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5681:             $record->{"scantron.$ansnum.answer"}='';
 5682:             $ansnum++;
 5683:         }
 5684:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5685:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5686:         }
 5687:     } elsif (scalar(@array) == 2) {
 5688:         my $location = length($array[0]);
 5689:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5690:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5691:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5692:             if ($ans eq $line_num) {
 5693:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5694:             } else {
 5695:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5696:             }
 5697:             $ansnum++;
 5698:          }
 5699:     } else {
 5700:         #  If there's more than one instance of a bubble character
 5701:         #  That's a double bubble; with positional notation we can
 5702:         #  record all the bubbles filled in as well as the
 5703:         #  fact this response consists of multiple bubbles.
 5704:         #
 5705:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5706:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5707:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5708:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5709:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5710:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5711:             my $doubleerror = 0;
 5712:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5713:                    (!$doubleerror)) {
 5714:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5715:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5716:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5717:                if (length(@currarray) > 2) {
 5718:                    $doubleerror = 1;
 5719:                } 
 5720:             }
 5721:             if ($doubleerror) {
 5722:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5723:             }
 5724:         } else {
 5725:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5726:         }
 5727:         my $item = $ansnum;
 5728:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5729:             $record->{"scantron.$item.answer"} = '';
 5730:             $item ++;
 5731:         }
 5732: 
 5733:         my @ans=@array;
 5734:         my $i=0;
 5735:         my $increment = 0;
 5736:         while ($#ans) {
 5737:             $i+=length($ans[0]) + $increment;
 5738:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5739:             my $bubble = $i%$$scantron_config{'Qlength'};
 5740:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5741:             shift(@ans);
 5742:             $increment = 1;
 5743:         }
 5744:         $ansnum += $answers_needed;
 5745:     }
 5746:     return $ansnum;
 5747: }
 5748: 
 5749: =pod
 5750: 
 5751: =item scantron_add_delay
 5752: 
 5753:    Adds an error message that occurred during the grading phase to a
 5754:    queue of messages to be shown after grading pass is complete
 5755: 
 5756:  Arguments:
 5757:    $delayqueue  - arrary ref of hash ref of error messages
 5758:    $scanline    - the scanline that caused the error
 5759:    $errormesage - the error message
 5760:    $errorcode   - a numeric code for the error
 5761: 
 5762:  Side Effects:
 5763:    updates the $delayqueue to have a new hash ref of the error
 5764: 
 5765: =cut
 5766: 
 5767: sub scantron_add_delay {
 5768:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5769:     push(@$delayqueue,
 5770: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5771: 	  'ecode' => $errorcode }
 5772: 	 );
 5773: }
 5774: 
 5775: =pod
 5776: 
 5777: =item scantron_find_student
 5778: 
 5779:    Finds the username for the current scanline
 5780: 
 5781:   Arguments:
 5782:    $scantron_record - hash result from scantron_parse_scanline
 5783:    $scan_data       - hash of correction information 
 5784:                       (see &scantron_getfile() form more information)
 5785:    $idmap           - hash from &username_to_idmap()
 5786:    $line            - number of current scanline
 5787:  
 5788:   Returns:
 5789:    Either 'username:domain' or undef if unknown
 5790: 
 5791: =cut
 5792: 
 5793: sub scantron_find_student {
 5794:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5795:     my $scanID=$$scantron_record{'scantron.ID'};
 5796:     if ($scanID =~ /^\s*$/) {
 5797:  	return &scan_data($scan_data,"$line.user");
 5798:     }
 5799:     foreach my $id (keys(%$idmap)) {
 5800:  	if (lc($id) eq lc($scanID)) {
 5801:  	    return $$idmap{$id};
 5802:  	}
 5803:     }
 5804:     return undef;
 5805: }
 5806: 
 5807: =pod
 5808: 
 5809: =item scantron_filter
 5810: 
 5811:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5812:    hidden resources was selected
 5813: 
 5814: =cut
 5815: 
 5816: sub scantron_filter {
 5817:     my ($curres)=@_;
 5818: 
 5819:     if (ref($curres) && $curres->is_problem()) {
 5820: 	# if the user has asked to not have either hidden
 5821: 	# or 'randomout' controlled resources to be graded
 5822: 	# don't include them
 5823: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5824: 	    && $curres->randomout) {
 5825: 	    return 0;
 5826: 	}
 5827: 	return 1;
 5828:     }
 5829:     return 0;
 5830: }
 5831: 
 5832: =pod
 5833: 
 5834: =item scantron_process_corrections
 5835: 
 5836:    Gets correction information out of submitted form data and corrects
 5837:    the scanline
 5838: 
 5839: =cut
 5840: 
 5841: sub scantron_process_corrections {
 5842:     my ($r) = @_;
 5843:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5844:     my ($scanlines,$scan_data)=&scantron_getfile();
 5845:     my $classlist=&Apache::loncoursedata::get_classlist();
 5846:     my $which=$env{'form.scantron_line'};
 5847:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5848:     my ($skip,$err,$errmsg);
 5849:     if ($env{'form.scantron_skip_record'}) {
 5850: 	$skip=1;
 5851:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5852: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5853: 	    $env{'form.scantron_domain'};
 5854: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5855: 	($line,$err,$errmsg)=
 5856: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5857: 				     'ID',{'newid'=>$newid,
 5858: 				    'username'=>$env{'form.scantron_username'},
 5859: 				    'domain'=>$env{'form.scantron_domain'}});
 5860:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5861: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5862: 	my $newCODE;
 5863: 	my %args;
 5864: 	if      ($resolution eq 'use_unfound') {
 5865: 	    $newCODE='use_unfound';
 5866: 	} elsif ($resolution eq 'use_found') {
 5867: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5868: 	} elsif ($resolution eq 'use_typed') {
 5869: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5870: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5871: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5872: 	}
 5873: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5874: 	    $args{'CODE_ignore_dup'}=1;
 5875: 	}
 5876: 	$args{'CODE'}=$newCODE;
 5877: 	($line,$err,$errmsg)=
 5878: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5879: 				     'CODE',\%args);
 5880:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5881: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5882: 	    ($line,$err,$errmsg)=
 5883: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5884: 					 $which,'answer',
 5885: 					 { 'question'=>$question,
 5886: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5887:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5888: 	    if ($err) { last; }
 5889: 	}
 5890:     }
 5891:     if ($err) {
 5892: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5893:     } else {
 5894: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5895: 	&scantron_putfile($scanlines,$scan_data);
 5896:     }
 5897: }
 5898: 
 5899: =pod
 5900: 
 5901: =item reset_skipping_status
 5902: 
 5903:    Forgets the current set of remember skipped scanlines (and thus
 5904:    reverts back to considering all lines in the
 5905:    scantron_skipped_<filename> file)
 5906: 
 5907: =cut
 5908: 
 5909: sub reset_skipping_status {
 5910:     my ($scanlines,$scan_data)=&scantron_getfile();
 5911:     &scan_data($scan_data,'remember_skipping',undef,1);
 5912:     &scantron_putfile(undef,$scan_data);
 5913: }
 5914: 
 5915: =pod
 5916: 
 5917: =item start_skipping
 5918: 
 5919:    Marks a scanline to be skipped. 
 5920: 
 5921: =cut
 5922: 
 5923: sub start_skipping {
 5924:     my ($scan_data,$i)=@_;
 5925:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5926:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5927: 	$remembered{$i}=2;
 5928:     } else {
 5929: 	$remembered{$i}=1;
 5930:     }
 5931:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5932: }
 5933: 
 5934: =pod
 5935: 
 5936: =item should_be_skipped
 5937: 
 5938:    Checks whether a scanline should be skipped.
 5939: 
 5940: =cut
 5941: 
 5942: sub should_be_skipped {
 5943:     my ($scanlines,$scan_data,$i)=@_;
 5944:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5945: 	# not redoing old skips
 5946: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5947: 	return 0;
 5948:     }
 5949:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5950: 
 5951:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5952: 	return 0;
 5953:     }
 5954:     return 1;
 5955: }
 5956: 
 5957: =pod
 5958: 
 5959: =item remember_current_skipped
 5960: 
 5961:    Discovers what scanlines are in the scantron_skipped_<filename>
 5962:    file and remembers them into scan_data for later use.
 5963: 
 5964: =cut
 5965: 
 5966: sub remember_current_skipped {
 5967:     my ($scanlines,$scan_data)=&scantron_getfile();
 5968:     my %to_remember;
 5969:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5970: 	if ($scanlines->{'skipped'}[$i]) {
 5971: 	    $to_remember{$i}=1;
 5972: 	}
 5973:     }
 5974: 
 5975:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5976:     &scantron_putfile(undef,$scan_data);
 5977: }
 5978: 
 5979: =pod
 5980: 
 5981: =item check_for_error
 5982: 
 5983:     Checks if there was an error when attempting to remove a specific
 5984:     scantron_.. bubble sheet data file. Prints out an error if
 5985:     something went wrong.
 5986: 
 5987: =cut
 5988: 
 5989: sub check_for_error {
 5990:     my ($r,$result)=@_;
 5991:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5992: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 5993:     }
 5994: }
 5995: 
 5996: =pod
 5997: 
 5998: =item scantron_warning_screen
 5999: 
 6000:    Interstitial screen to make sure the operator has selected the
 6001:    correct options before we start the validation phase.
 6002: 
 6003: =cut
 6004: 
 6005: sub scantron_warning_screen {
 6006:     my ($button_text)=@_;
 6007:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6008:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6009:     my $CODElist;
 6010:     if ($scantron_config{'CODElocation'} &&
 6011: 	$scantron_config{'CODEstart'} &&
 6012: 	$scantron_config{'CODElength'}) {
 6013: 	$CODElist=$env{'form.scantron_CODElist'};
 6014: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6015: 	$CODElist=
 6016: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6017: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6018:     }
 6019:     return ('
 6020: <p>
 6021: <span class="LC_warning">
 6022: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6023: </p>
 6024: <table>
 6025: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6026: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6027: '.$CODElist.'
 6028: </table>
 6029: <br />
 6030: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6031: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6032: 
 6033: <br />
 6034: ');
 6035: }
 6036: 
 6037: =pod
 6038: 
 6039: =item scantron_do_warning
 6040: 
 6041:    Check if the operator has picked something for all required
 6042:    fields. Error out if something is missing.
 6043: 
 6044: =cut
 6045: 
 6046: sub scantron_do_warning {
 6047:     my ($r)=@_;
 6048:     my ($symb)=&get_symb($r);
 6049:     if (!$symb) {return '';}
 6050:     my $default_form_data=&defaultFormData($symb);
 6051:     $r->print(&scantron_form_start().$default_form_data);
 6052:     if ( $env{'form.selectpage'} eq '' ||
 6053: 	 $env{'form.scantron_selectfile'} eq '' ||
 6054: 	 $env{'form.scantron_format'} eq '' ) {
 6055: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6056: 	if ( $env{'form.selectpage'} eq '') {
 6057: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6058: 	} 
 6059: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6060: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6061: 	} 
 6062: 	if ( $env{'form.scantron_format'} eq '') {
 6063: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6064: 	} 
 6065:     } else {
 6066: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6067: 	$r->print('
 6068: '.$warning.'
 6069: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6070: <input type="hidden" name="command" value="scantron_validate" />
 6071: ');
 6072:     }
 6073:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6074:     return '';
 6075: }
 6076: 
 6077: =pod
 6078: 
 6079: =item scantron_form_start
 6080: 
 6081:     html hidden input for remembering all selected grading options
 6082: 
 6083: =cut
 6084: 
 6085: sub scantron_form_start {
 6086:     my ($max_bubble)=@_;
 6087:     my $result= <<SCANTRONFORM;
 6088: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6089:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6090:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6091:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6092:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6093:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6094:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6095:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6096:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6097:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6098: SCANTRONFORM
 6099: 
 6100:   my $line = 0;
 6101:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6102:        my $chunk =
 6103: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6104:        $chunk .=
 6105: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6106:        $chunk .= 
 6107:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6108:        $chunk .=
 6109:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6110:        $result .= $chunk;
 6111:        $line++;
 6112:    }
 6113:     return $result;
 6114: }
 6115: 
 6116: =pod
 6117: 
 6118: =item scantron_validate_file
 6119: 
 6120:     Dispatch routine for doing validation of a bubble sheet data file.
 6121: 
 6122:     Also processes any necessary information resets that need to
 6123:     occur before validation begins (ignore previous corrections,
 6124:     restarting the skipped records processing)
 6125: 
 6126: =cut
 6127: 
 6128: sub scantron_validate_file {
 6129:     my ($r) = @_;
 6130:     my ($symb)=&get_symb($r);
 6131:     if (!$symb) {return '';}
 6132:     my $default_form_data=&defaultFormData($symb);
 6133:     
 6134:     # do the detection of only doing skipped records first befroe we delete
 6135:     # them when doing the corrections reset
 6136:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6137: 	&reset_skipping_status();
 6138:     }
 6139:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6140: 	&remember_current_skipped();
 6141: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6142:     }
 6143: 
 6144:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6145: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6146: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6147: 	&check_for_error($r,&scantron_remove_scan_data());
 6148: 	$env{'form.scantron_options_ignore'}='done';
 6149:     }
 6150: 
 6151:     if ($env{'form.scantron_corrections'}) {
 6152: 	&scantron_process_corrections($r);
 6153:     }
 6154:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6155:     #get the student pick code ready
 6156:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6157:     my $max_bubble=&scantron_get_maxbubble();
 6158:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6159:     $r->print($result);
 6160:     
 6161:     my @validate_phases=( 'sequence',
 6162: 			  'ID',
 6163: 			  'CODE',
 6164: 			  'doublebubble',
 6165: 			  'missingbubbles');
 6166:     if (!$env{'form.validatepass'}) {
 6167: 	$env{'form.validatepass'} = 0;
 6168:     }
 6169:     my $currentphase=$env{'form.validatepass'};
 6170: 
 6171: 
 6172:     my $stop=0;
 6173:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6174: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6175: 	$r->rflush();
 6176: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6177: 	{
 6178: 	    no strict 'refs';
 6179: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6180: 	}
 6181:     }
 6182:     if (!$stop) {
 6183: 	my $warning=&scantron_warning_screen('Start Grading');
 6184: 	$r->print(&mt('Validation process complete.').'<br />
 6185: '.$warning.'
 6186: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6187: <input type="hidden" name="command" value="scantron_process" />
 6188: ');
 6189: 
 6190:     } else {
 6191: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6192: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6193:     }
 6194:     if ($stop) {
 6195: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6196: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6197: 	    $r->print(' '.&mt('this error').' <br />');
 6198: 
 6199: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6200: 	} else {
 6201:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6202: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6203:             } else {
 6204:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6205:             }
 6206: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6207: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6208: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6209: 	}
 6210:     }
 6211:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6212:     return '';
 6213: }
 6214: 
 6215: 
 6216: =pod
 6217: 
 6218: =item scantron_remove_file
 6219: 
 6220:    Removes the requested bubble sheet data file, makes sure that
 6221:    scantron_original_<filename> is never removed
 6222: 
 6223: 
 6224: =cut
 6225: 
 6226: sub scantron_remove_file {
 6227:     my ($which)=@_;
 6228:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6229:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6230:     my $file='scantron_';
 6231:     if ($which eq 'corrected' || $which eq 'skipped') {
 6232: 	$file.=$which.'_';
 6233:     } else {
 6234: 	return 'refused';
 6235:     }
 6236:     $file.=$env{'form.scantron_selectfile'};
 6237:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6238: }
 6239: 
 6240: 
 6241: =pod
 6242: 
 6243: =item scantron_remove_scan_data
 6244: 
 6245:    Removes all scan_data correction for the requested bubble sheet
 6246:    data file.  (In the case that both the are doing skipped records we need
 6247:    to remember the old skipped lines for the time being so that element
 6248:    persists for a while.)
 6249: 
 6250: =cut
 6251: 
 6252: sub scantron_remove_scan_data {
 6253:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6254:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6255:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6256:     my @todelete;
 6257:     my $filename=$env{'form.scantron_selectfile'};
 6258:     foreach my $key (@keys) {
 6259: 	if ($key=~/^\Q$filename\E_/) {
 6260: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6261: 		$key=~/remember_skipping/) {
 6262: 		next;
 6263: 	    }
 6264: 	    push(@todelete,$key);
 6265: 	}
 6266:     }
 6267:     my $result;
 6268:     if (@todelete) {
 6269: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6270: 				       \@todelete,$cdom,$cname);
 6271:     } else {
 6272: 	$result = 'ok';
 6273:     }
 6274:     return $result;
 6275: }
 6276: 
 6277: 
 6278: =pod
 6279: 
 6280: =item scantron_getfile
 6281: 
 6282:     Fetches the requested bubble sheet data file (all 3 versions), and
 6283:     the scan_data hash
 6284:   
 6285:   Arguments:
 6286:     None
 6287: 
 6288:   Returns:
 6289:     2 hash references
 6290: 
 6291:      - first one has 
 6292:          orig      -
 6293:          corrected -
 6294:          skipped   -  each of which points to an array ref of the specified
 6295:                       file broken up into individual lines
 6296:          count     - number of scanlines
 6297:  
 6298:      - second is the scan_data hash possible keys are
 6299:        ($number refers to scanline numbered $number and thus the key affects
 6300:         only that scanline
 6301:         $bubline refers to the specific bubble line element and the aspects
 6302:         refers to that specific bubble line element)
 6303: 
 6304:        $number.user - username:domain to use
 6305:        $number.CODE_ignore_dup 
 6306:                     - ignore the duplicate CODE error 
 6307:        $number.useCODE
 6308:                     - use the CODE in the scanline as is
 6309:        $number.no_bubble.$bubline
 6310:                     - it is valid that there is no bubbled in bubble
 6311:                       at $number $bubline
 6312:        remember_skipping
 6313:                     - a frozen hash containing keys of $number and values
 6314:                       of either 
 6315:                         1 - we are on a 'do skipped records pass' and plan
 6316:                             on processing this line
 6317:                         2 - we are on a 'do skipped records pass' and this
 6318:                             scanline has been marked to skip yet again
 6319: 
 6320: =cut
 6321: 
 6322: sub scantron_getfile {
 6323:     #FIXME really would prefer a scantron directory
 6324:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6325:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6326:     my $lines;
 6327:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6328: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6329:     my %scanlines;
 6330:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6331:     my $temp=$scanlines{'orig'};
 6332:     $scanlines{'count'}=$#$temp;
 6333: 
 6334:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6335: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6336:     if ($lines eq '-1') {
 6337: 	$scanlines{'corrected'}=[];
 6338:     } else {
 6339: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6340:     }
 6341:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6342: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6343:     if ($lines eq '-1') {
 6344: 	$scanlines{'skipped'}=[];
 6345:     } else {
 6346: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6347:     }
 6348:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6349:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6350:     my %scan_data = @tmp;
 6351:     return (\%scanlines,\%scan_data);
 6352: }
 6353: 
 6354: =pod
 6355: 
 6356: =item lonnet_putfile
 6357: 
 6358:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6359: 
 6360:  Arguments:
 6361:    $contents - data to store
 6362:    $filename - filename to store $contents into
 6363: 
 6364:  Returns:
 6365:    result value from &Apache::lonnet::finishuserfileupload
 6366: 
 6367: =cut
 6368: 
 6369: sub lonnet_putfile {
 6370:     my ($contents,$filename)=@_;
 6371:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6372:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6373:     $env{'form.sillywaytopassafilearound'}=$contents;
 6374:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6375: 
 6376: }
 6377: 
 6378: =pod
 6379: 
 6380: =item scantron_putfile
 6381: 
 6382:     Stores the current version of the bubble sheet data files, and the
 6383:     scan_data hash. (Does not modify the original version only the
 6384:     corrected and skipped versions.
 6385: 
 6386:  Arguments:
 6387:     $scanlines - hash ref that looks like the first return value from
 6388:                  &scantron_getfile()
 6389:     $scan_data - hash ref that looks like the second return value from
 6390:                  &scantron_getfile()
 6391: 
 6392: =cut
 6393: 
 6394: sub scantron_putfile {
 6395:     my ($scanlines,$scan_data) = @_;
 6396:     #FIXME really would prefer a scantron directory
 6397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6399:     if ($scanlines) {
 6400: 	my $prefix='scantron_';
 6401: # no need to update orig, shouldn't change
 6402: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6403: #		    $env{'form.scantron_selectfile'});
 6404: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6405: 			$prefix.'corrected_'.
 6406: 			$env{'form.scantron_selectfile'});
 6407: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6408: 			$prefix.'skipped_'.
 6409: 			$env{'form.scantron_selectfile'});
 6410:     }
 6411:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6412: }
 6413: 
 6414: =pod
 6415: 
 6416: =item scantron_get_line
 6417: 
 6418:    Returns the correct version of the scanline
 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:     $i         - number of the requested line (starts at 0)
 6426: 
 6427:  Returns:
 6428:    A scanline, (either the original or the corrected one if it
 6429:    exists), or undef if the requested scanline should be
 6430:    skipped. (Either because it's an skipped scanline, or it's an
 6431:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6432:    pass.
 6433: 
 6434: =cut
 6435: 
 6436: sub scantron_get_line {
 6437:     my ($scanlines,$scan_data,$i)=@_;
 6438:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6439:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6440:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6441:     return $scanlines->{'orig'}[$i]; 
 6442: }
 6443: 
 6444: =pod
 6445: 
 6446: =item scantron_todo_count
 6447: 
 6448:     Counts the number of scanlines that need processing.
 6449: 
 6450:  Arguments:
 6451:     $scanlines - hash ref that looks like the first return value from
 6452:                  &scantron_getfile()
 6453:     $scan_data - hash ref that looks like the second return value from
 6454:                  &scantron_getfile()
 6455: 
 6456:  Returns:
 6457:     $count - number of scanlines to process
 6458: 
 6459: =cut
 6460: 
 6461: sub get_todo_count {
 6462:     my ($scanlines,$scan_data)=@_;
 6463:     my $count=0;
 6464:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6465: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6466: 	if ($line=~/^[\s\cz]*$/) { next; }
 6467: 	$count++;
 6468:     }
 6469:     return $count;
 6470: }
 6471: 
 6472: =pod
 6473: 
 6474: =item scantron_put_line
 6475: 
 6476:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6477:     data file.
 6478: 
 6479:  Arguments:
 6480:     $scanlines - hash ref that looks like the first return value from
 6481:                  &scantron_getfile()
 6482:     $scan_data - hash ref that looks like the second return value from
 6483:                  &scantron_getfile()
 6484:     $i         - line number to update
 6485:     $newline   - contents of the updated scanline
 6486:     $skip      - if true make the line for skipping and update the
 6487:                  'skipped' file
 6488: 
 6489: =cut
 6490: 
 6491: sub scantron_put_line {
 6492:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6493:     if ($skip) {
 6494: 	$scanlines->{'skipped'}[$i]=$newline;
 6495: 	&start_skipping($scan_data,$i);
 6496: 	return;
 6497:     }
 6498:     $scanlines->{'corrected'}[$i]=$newline;
 6499: }
 6500: 
 6501: =pod
 6502: 
 6503: =item scantron_clear_skip
 6504: 
 6505:    Remove a line from the 'skipped' file
 6506: 
 6507:  Arguments:
 6508:     $scanlines - hash ref that looks like the first return value from
 6509:                  &scantron_getfile()
 6510:     $scan_data - hash ref that looks like the second return value from
 6511:                  &scantron_getfile()
 6512:     $i         - line number to update
 6513: 
 6514: =cut
 6515: 
 6516: sub scantron_clear_skip {
 6517:     my ($scanlines,$scan_data,$i)=@_;
 6518:     if (exists($scanlines->{'skipped'}[$i])) {
 6519: 	undef($scanlines->{'skipped'}[$i]);
 6520: 	return 1;
 6521:     }
 6522:     return 0;
 6523: }
 6524: 
 6525: =pod
 6526: 
 6527: =item scantron_filter_not_exam
 6528: 
 6529:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6530:    filter out resources that are not marked as 'exam' mode
 6531: 
 6532: =cut
 6533: 
 6534: sub scantron_filter_not_exam {
 6535:     my ($curres)=@_;
 6536:     
 6537:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6538: 	# if the user has asked to not have either hidden
 6539: 	# or 'randomout' controlled resources to be graded
 6540: 	# don't include them
 6541: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6542: 	    && $curres->randomout) {
 6543: 	    return 0;
 6544: 	}
 6545: 	return 1;
 6546:     }
 6547:     return 0;
 6548: }
 6549: 
 6550: =pod
 6551: 
 6552: =item scantron_validate_sequence
 6553: 
 6554:     Validates the selected sequence, checking for resource that are
 6555:     not set to exam mode.
 6556: 
 6557: =cut
 6558: 
 6559: sub scantron_validate_sequence {
 6560:     my ($r,$currentphase) = @_;
 6561: 
 6562:     my $navmap=Apache::lonnavmaps::navmap->new();
 6563:     my (undef,undef,$sequence)=
 6564: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6565: 
 6566:     my $map=$navmap->getResourceByUrl($sequence);
 6567: 
 6568:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6569:                                     value="ignore" />');
 6570:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6571: 	my @resources=
 6572: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6573: 	if (@resources) {
 6574: 	    $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>");
 6575: 	    return (1,$currentphase);
 6576: 	}
 6577:     }
 6578: 
 6579:     return (0,$currentphase+1);
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_validate_ID
 6585: 
 6586:    Validates all scanlines in the selected file to not have any
 6587:    invalid or underspecified student IDs
 6588: 
 6589: =cut
 6590: 
 6591: sub scantron_validate_ID {
 6592:     my ($r,$currentphase) = @_;
 6593:     
 6594:     #get student info
 6595:     my $classlist=&Apache::loncoursedata::get_classlist();
 6596:     my %idmap=&username_to_idmap($classlist);
 6597: 
 6598:     #get scantron line setup
 6599:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6600:     my ($scanlines,$scan_data)=&scantron_getfile();
 6601:     
 6602:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6603: 
 6604:     my %found=('ids'=>{},'usernames'=>{});
 6605:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6606: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6607: 	if ($line=~/^[\s\cz]*$/) { next; }
 6608: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6609: 						 $scan_data);
 6610: 	my $id=$$scan_record{'scantron.ID'};
 6611: 	my $found;
 6612: 	foreach my $checkid (keys(%idmap)) {
 6613: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6614: 	}
 6615: 	if ($found) {
 6616: 	    my $username=$idmap{$found};
 6617: 	    if ($found{'ids'}{$found}) {
 6618: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6619: 					 $line,'duplicateID',$found);
 6620: 		return(1,$currentphase);
 6621: 	    } elsif ($found{'usernames'}{$username}) {
 6622: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6623: 					 $line,'duplicateID',$username);
 6624: 		return(1,$currentphase);
 6625: 	    }
 6626: 	    #FIXME store away line we previously saw the ID on to use above
 6627: 	    $found{'ids'}{$found}++;
 6628: 	    $found{'usernames'}{$username}++;
 6629: 	} else {
 6630: 	    if ($id =~ /^\s*$/) {
 6631: 		my $username=&scan_data($scan_data,"$i.user");
 6632: 		if (defined($username) && $found{'usernames'}{$username}) {
 6633: 		    &scantron_get_correction($r,$i,$scan_record,
 6634: 					     \%scantron_config,
 6635: 					     $line,'duplicateID',$username);
 6636: 		    return(1,$currentphase);
 6637: 		} elsif (!defined($username)) {
 6638: 		    &scantron_get_correction($r,$i,$scan_record,
 6639: 					     \%scantron_config,
 6640: 					     $line,'incorrectID');
 6641: 		    return(1,$currentphase);
 6642: 		}
 6643: 		$found{'usernames'}{$username}++;
 6644: 	    } else {
 6645: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6646: 					 $line,'incorrectID');
 6647: 		return(1,$currentphase);
 6648: 	    }
 6649: 	}
 6650:     }
 6651: 
 6652:     return (0,$currentphase+1);
 6653: }
 6654: 
 6655: =pod
 6656: 
 6657: =item scantron_get_correction
 6658: 
 6659:    Builds the interface screen to interact with the operator to fix a
 6660:    specific error condition in a specific scanline
 6661: 
 6662:  Arguments:
 6663:     $r           - Apache request object
 6664:     $i           - number of the current scanline
 6665:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6666:     $scan_config - hash ref as returned from &get_scantron_config()
 6667:     $line        - full contents of the current scanline
 6668:     $error       - error condition, valid values are
 6669:                    'incorrectCODE', 'duplicateCODE',
 6670:                    'doublebubble', 'missingbubble',
 6671:                    'duplicateID', 'incorrectID'
 6672:     $arg         - extra information needed
 6673:        For errors:
 6674:          - duplicateID   - paper number that this studentID was seen before on
 6675:          - duplicateCODE - array ref of the paper numbers this CODE was
 6676:                            seen on before
 6677:          - incorrectCODE - current incorrect CODE 
 6678:          - doublebubble  - array ref of the bubble lines that have double
 6679:                            bubble errors
 6680:          - missingbubble - array ref of the bubble lines that have missing
 6681:                            bubble errors
 6682: 
 6683: =cut
 6684: 
 6685: sub scantron_get_correction {
 6686:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6687: #FIXME in the case of a duplicated ID the previous line, probably need
 6688: #to show both the current line and the previous one and allow skipping
 6689: #the previous one or the current one
 6690: 
 6691:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6692: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6693: 			    " for PaperID <tt>[_1]</tt>",
 6694: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6695:     } else {
 6696: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6697: 			    " in scanline [_1] <pre>[_2]</pre>",
 6698: 			    $i,$line)."</p> \n");
 6699:     }
 6700:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6701: 			  "The name on the paper is [_2],[_3]",
 6702: 			  $$scan_record{'scantron.ID'},
 6703: 			  $$scan_record{'scantron.LastName'},
 6704: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6705: 
 6706:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6707:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6708:                            # Array populated for doublebubble or
 6709:     my @lines_to_correct;  # missingbubble errors to build javascript
 6710:                            # to validate radio button checking   
 6711: 
 6712:     if ($error =~ /ID$/) {
 6713: 	if ($error eq 'incorrectID') {
 6714: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6715: 		      "</p>\n");
 6716: 	} elsif ($error eq 'duplicateID') {
 6717: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6718: 	}
 6719: 	$r->print($message);
 6720: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6721: 	$r->print("\n<ul><li> ");
 6722: 	#FIXME it would be nice if this sent back the user ID and
 6723: 	#could do partial userID matches
 6724: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6725: 				       'scantron_username','scantron_domain'));
 6726: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6727: 	$r->print("\n@".
 6728: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6729: 
 6730: 	$r->print('</li>');
 6731:     } elsif ($error =~ /CODE$/) {
 6732: 	if ($error eq 'incorrectCODE') {
 6733: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6734: 	} elsif ($error eq 'duplicateCODE') {
 6735: 	    $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");
 6736: 	}
 6737: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6738: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6739: 	$r->print($message);
 6740: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6741: 	$r->print("\n<br /> ");
 6742: 	my $i=0;
 6743: 	if ($error eq 'incorrectCODE' 
 6744: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6745: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6746: 	    if ($closest > 0) {
 6747: 		foreach my $testcode (@{$closest}) {
 6748: 		    my $checked='';
 6749: 		    if (!$i) { $checked=' checked="checked" '; }
 6750: 		    $r->print("
 6751:    <label>
 6752:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6753:        ".&mt("Use the similar CODE [_1] instead.",
 6754: 	    "<b><tt>".$testcode."</tt></b>")."
 6755:     </label>
 6756:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6757: 		    $r->print("\n<br />");
 6758: 		    $i++;
 6759: 		}
 6760: 	    }
 6761: 	}
 6762: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6763: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6764: 	    $r->print("
 6765:     <label>
 6766:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6767:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6768: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6769:     </label>");
 6770: 	    $r->print("\n<br />");
 6771: 	}
 6772: 
 6773: 	$r->print(<<ENDSCRIPT);
 6774: <script type="text/javascript">
 6775: function change_radio(field) {
 6776:     var slct=document.scantronupload.scantron_CODE_resolution;
 6777:     var i;
 6778:     for (i=0;i<slct.length;i++) {
 6779:         if (slct[i].value==field) { slct[i].checked=true; }
 6780:     }
 6781: }
 6782: </script>
 6783: ENDSCRIPT
 6784: 	my $href="/adm/pickcode?".
 6785: 	   "form=".&escape("scantronupload").
 6786: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6787: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6788: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6789: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6790: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6791: 	    $r->print("
 6792:     <label>
 6793:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6794:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6795: 	     "<a target='_blank' href='$href'>","</a>")."
 6796:     </label> 
 6797:     ".&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')\" />"));
 6798: 	    $r->print("\n<br />");
 6799: 	}
 6800: 	$r->print("
 6801:     <label>
 6802:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6803:        ".&mt("Use [_1] as the CODE.",
 6804: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6805: 	$r->print("\n<br /><br />");
 6806:     } elsif ($error eq 'doublebubble') {
 6807: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6808: 
 6809: 	# The form field scantron_questions is acutally a list of line numbers.
 6810: 	# represented by this form so:
 6811: 
 6812: 	my $line_list = &questions_to_line_list($arg);
 6813: 
 6814: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6815: 		  $line_list.'" />');
 6816: 	$r->print($message);
 6817: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6818: 	foreach my $question (@{$arg}) {
 6819: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6820:                                                    $scan_record, $error);
 6821:             push (@lines_to_correct,@linenums);
 6822: 	}
 6823:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6824:     } elsif ($error eq 'missingbubble') {
 6825: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6826: 	$r->print($message);
 6827: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6828: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6829: 
 6830: 	# The form field scantron_questions is actually a list of line numbers not
 6831: 	# a list of question numbers. Therefore:
 6832: 	#
 6833: 	
 6834: 	my $line_list = &questions_to_line_list($arg);
 6835: 
 6836: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6837: 		  $line_list.'" />');
 6838: 	foreach my $question (@{$arg}) {
 6839: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6840:                                                    $scan_record, $error);
 6841:             push (@lines_to_correct,@linenums);
 6842: 	}
 6843:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6844:     } else {
 6845: 	$r->print("\n<ul>");
 6846:     }
 6847:     $r->print("\n</li></ul>");
 6848: }
 6849: 
 6850: sub verify_bubbles_checked {
 6851:     my (@ansnums) = @_;
 6852:     my $ansnumstr = join('","',@ansnums);
 6853:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6854:     my $output = (<<ENDSCRIPT);
 6855: <script type="text/javascript">
 6856: function verify_bubble_radio(form) {
 6857:     var ansnumArray = new Array ("$ansnumstr");
 6858:     var need_bubble_count = 0;
 6859:     for (var i=0; i<ansnumArray.length; i++) {
 6860:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6861:             var bubble_picked = 0; 
 6862:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6863:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6864:                     bubble_picked = 1;
 6865:                 }
 6866:             }
 6867:             if (bubble_picked == 0) {
 6868:                 need_bubble_count ++;
 6869:             }
 6870:         }
 6871:     }
 6872:     if (need_bubble_count) {
 6873:         alert("$warning");
 6874:         return;
 6875:     }
 6876:     form.submit(); 
 6877: }
 6878: </script>
 6879: ENDSCRIPT
 6880:     return $output;
 6881: }
 6882: 
 6883: =pod
 6884: 
 6885: =item  questions_to_line_list
 6886: 
 6887: Converts a list of questions into a string of comma separated
 6888: line numbers in the answer sheet used by the questions.  This is
 6889: used to fill in the scantron_questions form field.
 6890: 
 6891:   Arguments:
 6892:      questions    - Reference to an array of questions.
 6893: 
 6894: =cut
 6895: 
 6896: 
 6897: sub questions_to_line_list {
 6898:     my ($questions) = @_;
 6899:     my @lines;
 6900: 
 6901:     foreach my $item (@{$questions}) {
 6902:         my $question = $item;
 6903:         my ($first,$count,$last);
 6904:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6905:             $question = $1;
 6906:             my $subquestion = $2;
 6907:             $first = $first_bubble_line{$question-1} + 1;
 6908:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6909:             my $subcount = 1;
 6910:             while ($subcount<$subquestion) {
 6911:                 $first += $subans[$subcount-1];
 6912:                 $subcount ++;
 6913:             }
 6914:             $count = $subans[$subquestion-1];
 6915:         } else {
 6916: 	    $first   = $first_bubble_line{$question-1} + 1;
 6917: 	    $count   = $bubble_lines_per_response{$question-1};
 6918:         }
 6919:         $last = $first+$count-1;
 6920:         push(@lines, ($first..$last));
 6921:     }
 6922:     return join(',', @lines);
 6923: }
 6924: 
 6925: =pod 
 6926: 
 6927: =item prompt_for_corrections
 6928: 
 6929: Prompts for a potentially multiline correction to the
 6930: user's bubbling (factors out common code from scantron_get_correction
 6931: for multi and missing bubble cases).
 6932: 
 6933:  Arguments:
 6934:    $r           - Apache request object.
 6935:    $question    - The question number to prompt for.
 6936:    $scan_config - The scantron file configuration hash.
 6937:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6938:    $error       - Type of error
 6939: 
 6940:  Implicit inputs:
 6941:    %bubble_lines_per_response   - Starting line numbers for each question.
 6942:                                   Numbered from 0 (but question numbers are from
 6943:                                   1.
 6944:    %first_bubble_line           - Starting bubble line for each question.
 6945:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6946:                                   type problems render as separate sub-questions, 
 6947:                                   in exam mode. This hash contains a 
 6948:                                   comma-separated list of the lines per 
 6949:                                   sub-question.
 6950:    %responsetype_per_response   - essayresponse, formularesponse,
 6951:                                   stringresponse, imageresponse, reactionresponse,
 6952:                                   and organicresponse type problem parts can have
 6953:                                   multiple lines per response if the weight
 6954:                                   assigned exceeds 10.  In this case, only
 6955:                                   one bubble per line is permitted, but more 
 6956:                                   than one line might contain bubbles, e.g.
 6957:                                   bubbling of: line 1 - J, line 2 - J, 
 6958:                                   line 3 - B would assign 22 points.  
 6959: 
 6960: =cut
 6961: 
 6962: sub prompt_for_corrections {
 6963:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6964:     my ($current_line,$lines);
 6965:     my @linenums;
 6966:     my $questionnum = $question;
 6967:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6968:         $question = $1;
 6969:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6970:         my $subquestion = $2;
 6971:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6972:         my $subcount = 1;
 6973:         while ($subcount<$subquestion) {
 6974:             $current_line += $subans[$subcount-1];
 6975:             $subcount ++;
 6976:         }
 6977:         $lines = $subans[$subquestion-1];
 6978:     } else {
 6979:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6980:         $lines        = $bubble_lines_per_response{$question-1};
 6981:     }
 6982:     if ($lines > 1) {
 6983:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 6984:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 6985:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 6986:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 6987:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 6988:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 6989:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 6990:             $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 />');
 6991:         } else {
 6992:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 6993:         }
 6994:     }
 6995:     for (my $i =0; $i < $lines; $i++) {
 6996:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 6997: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 6998: 	        		  $questionnum,$error,split('', $selected));
 6999:         push (@linenums,$current_line);
 7000: 	$current_line++;
 7001:     }
 7002:     if ($lines > 1) {
 7003: 	$r->print("<hr /><br />");
 7004:     }
 7005:     return @linenums;
 7006: }
 7007: 
 7008: =pod
 7009: 
 7010: =item scantron_bubble_selector
 7011:   
 7012:    Generates the html radiobuttons to correct a single bubble line
 7013:    possibly showing the existing the selected bubbles if known
 7014: 
 7015:  Arguments:
 7016:     $r           - Apache request object
 7017:     $scan_config - hash from &get_scantron_config()
 7018:     $line        - Number of the line being displayed.
 7019:     $questionnum - Question number (may include subquestion)
 7020:     $error       - Type of error.
 7021:     @selected    - Array of bubbles picked on this line.
 7022: 
 7023: =cut
 7024: 
 7025: sub scantron_bubble_selector {
 7026:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7027:     my $max=$$scan_config{'Qlength'};
 7028: 
 7029:     my $scmode=$$scan_config{'Qon'};
 7030:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7031: 
 7032:     my @alphabet=('A'..'Z');
 7033:     $r->print(&Apache::loncommon::start_data_table().
 7034:               &Apache::loncommon::start_data_table_row());
 7035:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7036:     for (my $i=0;$i<$max+1;$i++) {
 7037: 	$r->print("\n".'<td align="center">');
 7038: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7039: 	else { $r->print('&nbsp;'); }
 7040: 	$r->print('</td>');
 7041:     }
 7042:     $r->print(&Apache::loncommon::end_data_table_row().
 7043:               &Apache::loncommon::start_data_table_row());
 7044:     for (my $i=0;$i<$max;$i++) {
 7045: 	$r->print("\n".
 7046: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7047: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7048:     }
 7049:     my $nobub_checked = ' ';
 7050:     if ($error eq 'missingbubble') {
 7051:         $nobub_checked = ' checked = "checked" ';
 7052:     }
 7053:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7054: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7055:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7056:               $line.'" value="'.$questionnum.'" /></td>');
 7057:     $r->print(&Apache::loncommon::end_data_table_row().
 7058:               &Apache::loncommon::end_data_table());
 7059: }
 7060: 
 7061: =pod
 7062: 
 7063: =item num_matches
 7064: 
 7065:    Counts the number of characters that are the same between the two arguments.
 7066: 
 7067:  Arguments:
 7068:    $orig - CODE from the scanline
 7069:    $code - CODE to match against
 7070: 
 7071:  Returns:
 7072:    $count - integer count of the number of same characters between the
 7073:             two arguments
 7074: 
 7075: =cut
 7076: 
 7077: sub num_matches {
 7078:     my ($orig,$code) = @_;
 7079:     my @code=split(//,$code);
 7080:     my @orig=split(//,$orig);
 7081:     my $same=0;
 7082:     for (my $i=0;$i<scalar(@code);$i++) {
 7083: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7084:     }
 7085:     return $same;
 7086: }
 7087: 
 7088: =pod
 7089: 
 7090: =item scantron_get_closely_matching_CODEs
 7091: 
 7092:    Cycles through all CODEs and finds the set that has the greatest
 7093:    number of same characters as the provided CODE
 7094: 
 7095:  Arguments:
 7096:    $allcodes - hash ref returned by &get_codes()
 7097:    $CODE     - CODE from the current scanline
 7098: 
 7099:  Returns:
 7100:    2 element list
 7101:     - first elements is number of how closely matching the best fit is 
 7102:       (5 means best set has 5 matching characters)
 7103:     - second element is an arrary ref containing the set of valid CODEs
 7104:       that best fit the passed in CODE
 7105: 
 7106: =cut
 7107: 
 7108: sub scantron_get_closely_matching_CODEs {
 7109:     my ($allcodes,$CODE)=@_;
 7110:     my @CODEs;
 7111:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7112: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7113:     }
 7114: 
 7115:     return ($#CODEs,$CODEs[-1]);
 7116: }
 7117: 
 7118: =pod
 7119: 
 7120: =item get_codes
 7121: 
 7122:    Builds a hash which has keys of all of the valid CODEs from the selected
 7123:    set of remembered CODEs.
 7124: 
 7125:  Arguments:
 7126:   $old_name - name of the set of remembered CODEs
 7127:   $cdom     - domain of the course
 7128:   $cnum     - internal course name
 7129: 
 7130:  Returns:
 7131:   %allcodes - keys are the valid CODEs, values are all 1
 7132: 
 7133: =cut
 7134: 
 7135: sub get_codes {
 7136:     my ($old_name, $cdom, $cnum) = @_;
 7137:     if (!$old_name) {
 7138: 	$old_name=$env{'form.scantron_CODElist'};
 7139:     }
 7140:     if (!$cdom) {
 7141: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7142:     }
 7143:     if (!$cnum) {
 7144: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7145:     }
 7146:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7147: 				    $cdom,$cnum);
 7148:     my %allcodes;
 7149:     if ($result{"type\0$old_name"} eq 'number') {
 7150: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7151:     } else {
 7152: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7153:     }
 7154:     return %allcodes;
 7155: }
 7156: 
 7157: =pod
 7158: 
 7159: =item scantron_validate_CODE
 7160: 
 7161:    Validates all scanlines in the selected file to not have any
 7162:    invalid or underspecified CODEs and that none of the codes are
 7163:    duplicated if this was requested.
 7164: 
 7165: =cut
 7166: 
 7167: sub scantron_validate_CODE {
 7168:     my ($r,$currentphase) = @_;
 7169:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7170:     if ($scantron_config{'CODElocation'} &&
 7171: 	$scantron_config{'CODEstart'} &&
 7172: 	$scantron_config{'CODElength'}) {
 7173: 	if (!defined($env{'form.scantron_CODElist'})) {
 7174: 	    &FIXME_blow_up()
 7175: 	}
 7176:     } else {
 7177: 	return (0,$currentphase+1);
 7178:     }
 7179:     
 7180:     my %usedCODEs;
 7181: 
 7182:     my %allcodes=&get_codes();
 7183: 
 7184:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7185: 
 7186:     my ($scanlines,$scan_data)=&scantron_getfile();
 7187:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7188: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7189: 	if ($line=~/^[\s\cz]*$/) { next; }
 7190: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7191: 						 $scan_data);
 7192: 	my $CODE=$$scan_record{'scantron.CODE'};
 7193: 	my $error=0;
 7194: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7195: 	    &scantron_get_correction($r,$i,$scan_record,
 7196: 				     \%scantron_config,
 7197: 				     $line,'incorrectCODE',\%allcodes);
 7198: 	    return(1,$currentphase);
 7199: 	}
 7200: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7201: 	    && !$$scan_record{'scantron.useCODE'}) {
 7202: 	    &scantron_get_correction($r,$i,$scan_record,
 7203: 				     \%scantron_config,
 7204: 				     $line,'incorrectCODE',\%allcodes);
 7205: 	    return(1,$currentphase);
 7206: 	}
 7207: 	if (exists($usedCODEs{$CODE}) 
 7208: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7209: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7210: 	    &scantron_get_correction($r,$i,$scan_record,
 7211: 				     \%scantron_config,
 7212: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7213: 	    return(1,$currentphase);
 7214: 	}
 7215: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7216:     }
 7217:     return (0,$currentphase+1);
 7218: }
 7219: 
 7220: =pod
 7221: 
 7222: =item scantron_validate_doublebubble
 7223: 
 7224:    Validates all scanlines in the selected file to not have any
 7225:    bubble lines with multiple bubbles marked.
 7226: 
 7227: =cut
 7228: 
 7229: sub scantron_validate_doublebubble {
 7230:     my ($r,$currentphase) = @_;
 7231:     #get student info
 7232:     my $classlist=&Apache::loncoursedata::get_classlist();
 7233:     my %idmap=&username_to_idmap($classlist);
 7234: 
 7235:     #get scantron line setup
 7236:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7237:     my ($scanlines,$scan_data)=&scantron_getfile();
 7238:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7239: 
 7240:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7241: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7242: 	if ($line=~/^[\s\cz]*$/) { next; }
 7243: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7244: 						 $scan_data);
 7245: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7246: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7247: 				 'doublebubble',
 7248: 				 $$scan_record{'scantron.doubleerror'});
 7249:     	return (1,$currentphase);
 7250:     }
 7251:     return (0,$currentphase+1);
 7252: }
 7253: 
 7254: =pod
 7255: 
 7256: =item scantron_get_maxbubble
 7257: 
 7258:    Returns the maximum number of bubble lines that are expected to
 7259:    occur. Does this by walking the selected sequence rendering the
 7260:    resource and then checking &Apache::lonxml::get_problem_counter()
 7261:    for what the current value of the problem counter is.
 7262: 
 7263:    Caches the results to $env{'form.scantron_maxbubble'},
 7264:    $env{'form.scantron.bubble_lines.n'}, 
 7265:    $env{'form.scantron.first_bubble_line.n'} and
 7266:    $env{"form.scantron.sub_bubblelines.n"}
 7267:    which are the total number of bubble, lines, the number of bubble
 7268:    lines for response n and number of the first bubble line for response n,
 7269:    and a comma separated list of numbers of bubble lines for sub-questions
 7270:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7271: 
 7272: =cut
 7273: 
 7274: sub scantron_get_maxbubble {
 7275:     if (defined($env{'form.scantron_maxbubble'}) &&
 7276: 	$env{'form.scantron_maxbubble'}) {
 7277: 	&restore_bubble_lines();
 7278: 	return $env{'form.scantron_maxbubble'};
 7279:     }
 7280: 
 7281:     my (undef, undef, $sequence) =
 7282: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7283: 
 7284:     my $navmap=Apache::lonnavmaps::navmap->new();
 7285:     my $map=$navmap->getResourceByUrl($sequence);
 7286:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7287: 
 7288:     &Apache::lonxml::clear_problem_counter();
 7289: 
 7290:     my $uname       = $env{'form.student'};
 7291:     my $udom        = $env{'form.userdom'};
 7292:     my $cid         = $env{'request.course.id'};
 7293:     my $total_lines = 0;
 7294:     %bubble_lines_per_response = ();
 7295:     %first_bubble_line         = ();
 7296:     %subdivided_bubble_lines   = ();
 7297:     %responsetype_per_response = ();
 7298:   
 7299:     my $response_number = 0;
 7300:     my $bubble_line     = 0;
 7301:     foreach my $resource (@resources) {
 7302:         my $symb = $resource->symb();
 7303:         # Need to retrieve part IDs and response IDs because essayresponse,
 7304:         # reactionresponse and organicresponse items are not included in 
 7305:         # $analysis{'parts'} from lonnet::ssi.  
 7306:         my %possible_part_ids; 
 7307:         if (ref($resource->parts()) eq 'ARRAY') { 
 7308:             foreach my $part (@{$resource->parts()}) {
 7309:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
 7310:                     my @resp_ids = $resource->responseIds($part);
 7311:                     foreach my $id (@resp_ids) {
 7312:                         $possible_part_ids{$part.'.'.$id} = 1;
 7313:                     }
 7314:                 }
 7315:             }
 7316:         }
 7317: 	my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7318: 					('symb' => $symb,
 7319: 					 'grade_target' => 'analyze',
 7320: 					 'grade_courseid' => $cid,
 7321: 					 'grade_domain' => $udom,
 7322: 					 'grade_username' => $uname));
 7323: 	my (undef, $an) =
 7324: 	    split(/_HASH_REF__/,$result, 2);
 7325: 
 7326:         my @parts;
 7327: 
 7328: 	my %analysis = &Apache::lonnet::str2hash($an);
 7329: 
 7330:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7331:             foreach my $part (@{$analysis{'parts'}}) {
 7332:                 my ($id,$respid) = split(/\./,$part);
 7333:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7334:                     push(@parts,$part);
 7335:                 }
 7336:             }
 7337:         }
 7338:         # Add part_ids for any essayresponse items. 
 7339:         foreach my $part_id (keys(%possible_part_ids)) {
 7340:             if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
 7341:                 ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
 7342:                 ($analysis{$part_id.'.type'} eq 'organicresponse')) {
 7343:                 if (!grep(/^\Q$part_id\E$/,@parts)) {
 7344:                     push (@parts,$part_id);
 7345:                 }
 7346:             }
 7347:         }
 7348: 
 7349: 	foreach my $part_id (@parts) {
 7350:             my $lines = $analysis{"$part_id.bubble_lines"};
 7351: 
 7352: 	    # TODO - make this a persistent hash not an array.
 7353: 
 7354:             # optionresponse, matchresponse and rankresponse type items 
 7355:             # render as separate sub-questions in exam mode.
 7356:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
 7357:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
 7358:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
 7359:                 my ($numbub,$numshown);
 7360:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
 7361:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
 7362:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
 7363:                     }
 7364:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
 7365:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
 7366:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
 7367:                     }
 7368:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
 7369:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
 7370:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
 7371:                     }
 7372:                 }
 7373:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
 7374:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
 7375:                 }
 7376:                 my $bubbles_per_line = 10;
 7377:                 my $inner_bubble_lines = int($numshown/$bubbles_per_line);
 7378:                 if (($numshown % $bubbles_per_line) != 0) {
 7379:                     $inner_bubble_lines++;
 7380:                 }
 7381:                 for (my $i=0; $i<$numshown; $i++) {
 7382:                     $subdivided_bubble_lines{$response_number} .= 
 7383:                         $inner_bubble_lines.',';
 7384:                 }
 7385:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7386:             } 
 7387: 
 7388:             $first_bubble_line{$response_number} = $bubble_line;
 7389: 	    $bubble_lines_per_response{$response_number} = $lines;
 7390:             $responsetype_per_response{$response_number} = 
 7391:                 $analysis{$part_id.'.type'};
 7392: 	    $response_number++;
 7393: 
 7394: 	    $bubble_line +=  $lines;
 7395: 	    $total_lines +=  $lines;
 7396: 	}
 7397: 
 7398:     }
 7399:     &Apache::lonnet::delenv('scantron\.');
 7400: 
 7401:     &save_bubble_lines();
 7402:     $env{'form.scantron_maxbubble'} =
 7403: 	$total_lines;
 7404:     return $env{'form.scantron_maxbubble'};
 7405: }
 7406: 
 7407: =pod
 7408: 
 7409: =item scantron_validate_missingbubbles
 7410: 
 7411:    Validates all scanlines in the selected file to not have any
 7412:     answers that don't have bubbles that have not been verified
 7413:     to be bubble free.
 7414: 
 7415: =cut
 7416: 
 7417: sub scantron_validate_missingbubbles {
 7418:     my ($r,$currentphase) = @_;
 7419:     #get student info
 7420:     my $classlist=&Apache::loncoursedata::get_classlist();
 7421:     my %idmap=&username_to_idmap($classlist);
 7422: 
 7423:     #get scantron line setup
 7424:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7425:     my ($scanlines,$scan_data)=&scantron_getfile();
 7426:     my $max_bubble=&scantron_get_maxbubble();
 7427:     if (!$max_bubble) { $max_bubble=2**31; }
 7428:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7429: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7430: 	if ($line=~/^[\s\cz]*$/) { next; }
 7431: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7432: 						 $scan_data);
 7433: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7434: 	my @to_correct;
 7435: 	
 7436: 	# Probably here's where the error is...
 7437: 
 7438: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7439:             my $lastbubble;
 7440:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7441:                my $question = $1;
 7442:                my $subquestion = $2;
 7443:                if (!defined($first_bubble_line{$question -1})) { next; }
 7444:                my $first = $first_bubble_line{$question-1};
 7445:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7446:                my $subcount = 1;
 7447:                while ($subcount<$subquestion) {
 7448:                    $first += $subans[$subcount-1];
 7449:                    $subcount ++;
 7450:                }
 7451:                my $count = $subans[$subquestion-1];
 7452:                $lastbubble = $first + $count;
 7453:             } else {
 7454:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7455:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7456:             }
 7457:             if ($lastbubble > $max_bubble) { next; }
 7458: 	    push(@to_correct,$missing);
 7459: 	}
 7460: 	if (@to_correct) {
 7461: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7462: 				     $line,'missingbubble',\@to_correct);
 7463: 	    return (1,$currentphase);
 7464: 	}
 7465: 
 7466:     }
 7467:     return (0,$currentphase+1);
 7468: }
 7469: 
 7470: =pod
 7471: 
 7472: =item scantron_process_students
 7473: 
 7474:    Routine that does the actual grading of the bubble sheet information.
 7475: 
 7476:    The parsed scanline hash is added to %env 
 7477: 
 7478:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7479:    foreach resource , with the form data of
 7480: 
 7481: 	'submitted'     =>'scantron' 
 7482: 	'grade_target'  =>'grade',
 7483: 	'grade_username'=> username of student
 7484: 	'grade_domain'  => domain of student
 7485: 	'grade_courseid'=> of course
 7486: 	'grade_symb'    => symb of resource to grade
 7487: 
 7488:     This triggers a grading pass. The problem grading code takes care
 7489:     of converting the bubbled letter information (now in %env) into a
 7490:     valid submission.
 7491: 
 7492: =cut
 7493: 
 7494: sub scantron_process_students {
 7495:     my ($r) = @_;
 7496: 
 7497:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7498:     my ($symb)=&get_symb($r);
 7499:     if (!$symb) {
 7500: 	return '';
 7501:     }
 7502:     my $default_form_data=&defaultFormData($symb);
 7503: 
 7504:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7505:     my ($scanlines,$scan_data)=&scantron_getfile();
 7506:     my $classlist=&Apache::loncoursedata::get_classlist();
 7507:     my %idmap=&username_to_idmap($classlist);
 7508:     my $navmap=Apache::lonnavmaps::navmap->new();
 7509:     my $map=$navmap->getResourceByUrl($sequence);
 7510:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7511: #    $r->print("geto ".scalar(@resources)."<br />");
 7512:     my $result= <<SCANTRONFORM;
 7513: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7514:   <input type="hidden" name="command" value="scantron_configphase" />
 7515:   $default_form_data
 7516: SCANTRONFORM
 7517:     $r->print($result);
 7518: 
 7519:     my @delayqueue;
 7520:     my %completedstudents;
 7521:     
 7522:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7523:     my $count=&get_todo_count($scanlines,$scan_data);
 7524:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7525:  				    'Scantron Progress',$count,
 7526: 				    'inline',undef,'scantronupload');
 7527:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7528: 					  'Processing first student');
 7529:     my $start=&Time::HiRes::time();
 7530:     my $i=-1;
 7531:     my ($uname,$udom,$started);
 7532: 
 7533:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7534:     
 7535: 
 7536:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7537:     # the user and return.
 7538: 
 7539:     if ($ssi_error) {
 7540: 	$r->print("</form>");
 7541: 	&ssi_print_error($r);
 7542: 	$r->print(&show_grading_menu_form($symb));
 7543:         &Apache::lonnet::remove_lock($lock);
 7544: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7545:     }
 7546: 
 7547:     while ($i<$scanlines->{'count'}) {
 7548:  	($uname,$udom)=('','');
 7549:  	$i++;
 7550:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7551:  	if ($line=~/^[\s\cz]*$/) { next; }
 7552: 	if ($started) {
 7553: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7554: 						     'last student');
 7555: 	}
 7556: 	$started=1;
 7557:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7558:  						 $scan_data);
 7559:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7560:  					      \%idmap,$i)) {
 7561:   	    &scantron_add_delay(\@delayqueue,$line,
 7562:  				'Unable to find a student that matches',1);
 7563:  	    next;
 7564:   	}
 7565:  	if (exists $completedstudents{$uname}) {
 7566:  	    &scantron_add_delay(\@delayqueue,$line,
 7567:  				'Student '.$uname.' has multiple sheets',2);
 7568:  	    next;
 7569:  	}
 7570:   	($uname,$udom)=split(/:/,$uname);
 7571: 
 7572: 	&Apache::lonxml::clear_problem_counter();
 7573:   	&Apache::lonnet::appenv($scan_record);
 7574: 
 7575: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7576: 	    &scantron_putfile($scanlines,$scan_data);
 7577: 	}
 7578: 	
 7579: 	my $i=0;
 7580: 	foreach my $resource (@resources) {
 7581: 	    $i++;
 7582: 	    my %form=('submitted'     =>'scantron',
 7583: 		      'grade_target'  =>'grade',
 7584: 		      'grade_username'=>$uname,
 7585: 		      'grade_domain'  =>$udom,
 7586: 		      'grade_courseid'=>$env{'request.course.id'},
 7587: 		      'grade_symb'    =>$resource->symb());
 7588: 	    if (exists($scan_record->{'scantron.CODE'})
 7589: 		&& 
 7590: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 7591: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 7592: 	    } else {
 7593: 		$form{'CODE'}='';
 7594: 	    } 
 7595: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
 7596: 	    if ($ssi_error) {
 7597: 		$ssi_error = 0;	# So end of handler error message does not trigger.
 7598: 		$r->print("</form>");
 7599: 		&ssi_print_error($r);
 7600: 		$r->print(&show_grading_menu_form($symb));
 7601:                 &Apache::lonnet::remove_lock($lock);
 7602: 		return '';	# Why return ''?  Beats me.
 7603: 	    }
 7604: 
 7605: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 7606: 	}
 7607: 	$completedstudents{$uname}={'line'=>$line};
 7608: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7609:     } continue {
 7610: 	&Apache::lonxml::clear_problem_counter();
 7611: 	&Apache::lonnet::delenv('scantron\.');
 7612:     }
 7613:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7614:     &Apache::lonnet::remove_lock($lock);
 7615: #    my $lasttime = &Time::HiRes::time()-$start;
 7616: #    $r->print("<p>took $lasttime</p>");
 7617: 
 7618:     $r->print("</form>");
 7619:     $r->print(&show_grading_menu_form($symb));
 7620:     return '';
 7621: }
 7622: 
 7623: =pod
 7624: 
 7625: =item scantron_upload_scantron_data
 7626: 
 7627:     Creates the screen for adding a new bubble sheet data file to a course.
 7628: 
 7629: =cut
 7630: 
 7631: sub scantron_upload_scantron_data {
 7632:     my ($r)=@_;
 7633:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7634:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7635: 							  'domainid',
 7636: 							  'coursename');
 7637:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7638: 						   'domainid');
 7639:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7640:     $r->print('
 7641: <script type="text/javascript" language="javascript">
 7642:     function checkUpload(formname) {
 7643: 	if (formname.upfile.value == "") {
 7644: 	    alert("Please use the browse button to select a file from your local directory.");
 7645: 	    return false;
 7646: 	}
 7647: 	formname.submit();
 7648:     }
 7649: </script>
 7650: 
 7651: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7652: '.$default_form_data.'
 7653: <table>
 7654: <tr><td>'.$select_link.'                             </td></tr>
 7655: <tr><td>'.&mt('Course ID:').'     </td>
 7656:     <td><input name="courseid"   type="text" />      </td></tr>
 7657: <tr><td>'.&mt('Course Name:').'   </td>
 7658:     <td><input name="coursename" type="text" />      </td></tr>
 7659: <tr><td>'.&mt('Domain:').'        </td>
 7660:     <td>'.$domsel.'                                  </td></tr>
 7661: <tr><td>'.&mt('File to upload:').'</td>
 7662:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7663: </table>
 7664: <input name="command" value="scantronupload_save" type="hidden" />
 7665: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7666: </form>
 7667: ');
 7668:     return '';
 7669: }
 7670: 
 7671: =pod
 7672: 
 7673: =item scantron_upload_scantron_data_save
 7674: 
 7675:    Adds a provided bubble information data file to the course if user
 7676:    has the correct privileges to do so.  
 7677: 
 7678: =cut
 7679: 
 7680: sub scantron_upload_scantron_data_save {
 7681:     my($r)=@_;
 7682:     my ($symb)=&get_symb($r,1);
 7683:     my $doanotherupload=
 7684: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7685: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7686: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7687: 	'</form>'."\n";
 7688:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7689: 	!&Apache::lonnet::allowed('usc',
 7690: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7691: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7692: 	if ($symb) {
 7693: 	    $r->print(&show_grading_menu_form($symb));
 7694: 	} else {
 7695: 	    $r->print($doanotherupload);
 7696: 	}
 7697: 	return '';
 7698:     }
 7699:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7700:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7701:     my $fname=$env{'form.upfile.filename'};
 7702:     #FIXME
 7703:     #copied from lonnet::userfileupload()
 7704:     #make that function able to target a specified course
 7705:     # Replace Windows backslashes by forward slashes
 7706:     $fname=~s/\\/\//g;
 7707:     # Get rid of everything but the actual filename
 7708:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7709:     # Replace spaces by underscores
 7710:     $fname=~s/\s+/\_/g;
 7711:     # Replace all other weird characters by nothing
 7712:     $fname=~s/[^\w\.\-]//g;
 7713:     # See if there is anything left
 7714:     unless ($fname) { return 'error: no uploaded file'; }
 7715:     my $uploadedfile=$fname;
 7716:     $fname='scantron_orig_'.$fname;
 7717:     if (length($env{'form.upfile'}) < 2) {
 7718: 	$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>"));
 7719:     } else {
 7720: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7721: 	if ($result =~ m|^/uploaded/|) {
 7722: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7723: 			  (length($env{'form.upfile'})-1),
 7724: 			  '<span class="LC_filename">'.$result."</span>"));
 7725: 	} else {
 7726: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7727: 			  $result,
 7728: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7729: 
 7730: 	}
 7731:     }
 7732:     if ($symb) {
 7733: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7734:     } else {
 7735: 	$r->print($doanotherupload);
 7736:     }
 7737:     return '';
 7738: }
 7739: 
 7740: =pod
 7741: 
 7742: =item valid_file
 7743: 
 7744:    Validates that the requested bubble data file exists in the course.
 7745: 
 7746: =cut
 7747: 
 7748: sub valid_file {
 7749:     my ($requested_file)=@_;
 7750:     foreach my $filename (sort(&scantron_filenames())) {
 7751: 	if ($requested_file eq $filename) { return 1; }
 7752:     }
 7753:     return 0;
 7754: }
 7755: 
 7756: =pod
 7757: 
 7758: =item scantron_download_scantron_data
 7759: 
 7760:    Shows a list of the three internal files (original, corrected,
 7761:    skipped) for a specific bubble sheet data file that exists in the
 7762:    course.
 7763: 
 7764: =cut
 7765: 
 7766: sub scantron_download_scantron_data {
 7767:     my ($r)=@_;
 7768:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7769:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7770:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7771:     my $file=$env{'form.scantron_selectfile'};
 7772:     if (! &valid_file($file)) {
 7773: 	$r->print('
 7774: 	<p>
 7775: 	    '.&mt('The requested file name was invalid.').'
 7776:         </p>
 7777: ');
 7778: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7779: 	return;
 7780:     }
 7781:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7782:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7783:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7784:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7785:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7786:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7787:     $r->print('
 7788:     <p>
 7789: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7790: 	      '<a href="'.$orig.'">','</a>').'
 7791:     </p>
 7792:     <p>
 7793: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7794: 	      '<a href="'.$corrected.'">','</a>').'
 7795:     </p>
 7796:     <p>
 7797: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7798: 	      '<a href="'.$skipped.'">','</a>').'
 7799:     </p>
 7800: ');
 7801:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7802:     return '';
 7803: }
 7804: 
 7805: =pod
 7806: 
 7807: =back
 7808: 
 7809: =cut
 7810: 
 7811: #-------- end of section for handling grading scantron forms -------
 7812: #
 7813: #-------------------------------------------------------------------
 7814: 
 7815: #-------------------------- Menu interface -------------------------
 7816: #
 7817: #--- Show a Grading Menu button - Calls the next routine ---
 7818: sub show_grading_menu_form {
 7819:     my ($symb)=@_;
 7820:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7821: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7822: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7823: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7824: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 7825: 	'</form>'."\n";
 7826:     return $result;
 7827: }
 7828: 
 7829: # -- Retrieve choices for grading form
 7830: sub savedState {
 7831:     my %savedState = ();
 7832:     if ($env{'form.saveState'}) {
 7833: 	foreach (split(/:/,$env{'form.saveState'})) {
 7834: 	    my ($key,$value) = split(/=/,$_,2);
 7835: 	    $savedState{$key} = $value;
 7836: 	}
 7837:     }
 7838:     return \%savedState;
 7839: }
 7840: 
 7841: sub grading_menu {
 7842:     my ($request) = @_;
 7843:     my ($symb)=&get_symb($request);
 7844:     if (!$symb) {return '';}
 7845:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7846:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7847: 
 7848:     $request->print($table);
 7849:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7850:                   'handgrade'=>$hdgrade,
 7851:                   'probTitle'=>$probTitle,
 7852:                   'command'=>'submit_options',
 7853:                   'saveState'=>"",
 7854:                   'gradingMenu'=>1,
 7855:                   'showgrading'=>"yes");
 7856:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7857:     my @menu = ({ url => $url,
 7858:                      name => &mt('Manual Grading/View Submissions'),
 7859:                      short_description => 
 7860:     &mt('Start the process of hand grading submissions.'),
 7861:                  });
 7862:     $fields{'command'} = 'csvform';
 7863:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7864:     push (@menu, { url => $url,
 7865:                    name => &mt('Upload Scores'),
 7866:                    short_description => 
 7867:             &mt('Specify a file containing the class scores for current resource.')});
 7868:     $fields{'command'} = 'processclicker';
 7869:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7870:     push (@menu, { url => $url,
 7871:                    name => &mt('Process Clicker'),
 7872:                    short_description => 
 7873:             &mt('Specify a file containing the clicker information for this resource.')});
 7874:     $fields{'command'} = 'scantron_selectphase';
 7875:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7876:     push (@menu, { url => $url,
 7877:                    name => &mt('Grade/Manage Scantron Forms'),
 7878:                    short_description => 
 7879:             &mt('')});
 7880:     $fields{'command'} = 'verify';
 7881:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7882:     push (@menu, { url => "",
 7883:                    name => &mt('Verify Receipt'),
 7884:                    short_description => 
 7885:             &mt('')});
 7886:     #
 7887:     # Create the menu
 7888:     my $Str;
 7889:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7890:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7891:     $Str .= '<input type="hidden" name="command" value="" />'.
 7892:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7893: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7894: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7895: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7896: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7897: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7898: 
 7899:     foreach my $menudata (@menu) {
 7900:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7901:             $Str .='    <h3><a '.
 7902:                 $menudata->{'jscript'}.
 7903:                 ' href="'.
 7904:                 $menudata->{'url'}.'" >'.
 7905:                 $menudata->{'name'}."</a></h3>\n";
 7906:         } else {
 7907:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 7908:                 $menudata->{'jscript'}.
 7909:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 7910:                 ' /> '.
 7911: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 7912:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7913:         }
 7914:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7915:             "\n";
 7916:     }
 7917:     $Str .="</form>\n";
 7918:     $request->print(<<GRADINGMENUJS);
 7919: <script type="text/javascript" language="javascript">
 7920:     function checkChoice(formname,val,cmdx) {
 7921: 	if (val <= 2) {
 7922: 	    var cmd = radioSelection(formname.radioChoice);
 7923: 	    var cmdsave = cmd;
 7924: 	} else {
 7925: 	    cmd = cmdx;
 7926: 	    cmdsave = 'submission';
 7927: 	}
 7928: 	formname.command.value = cmd;
 7929: 	if (val < 5) formname.submit();
 7930: 	if (val == 5) {
 7931: 	    if (!checkReceiptNo(formname,'notOK')) { 
 7932: 	        return false;
 7933: 	    } else {
 7934: 	        formname.submit();
 7935: 	    }
 7936: 	}
 7937:     }
 7938: 
 7939:     function checkReceiptNo(formname,nospace) {
 7940: 	var receiptNo = formname.receipt.value;
 7941: 	var checkOpt = false;
 7942: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7943: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7944: 	if (checkOpt) {
 7945: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7946: 	    formname.receipt.value = "";
 7947: 	    formname.receipt.focus();
 7948: 	    return false;
 7949: 	}
 7950: 	return true;
 7951:     }
 7952: </script>
 7953: GRADINGMENUJS
 7954:     &commonJSfunctions($request);
 7955:     return $Str;    
 7956: }
 7957: 
 7958: 
 7959: #--- Displays the submissions first page -------
 7960: sub submit_options {
 7961:     my ($request) = @_;
 7962:     my ($symb)=&get_symb($request);
 7963:     if (!$symb) {return '';}
 7964:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7965: 
 7966:     $request->print(<<GRADINGMENUJS);
 7967: <script type="text/javascript" language="javascript">
 7968:     function checkChoice(formname,val,cmdx) {
 7969: 	if (val <= 2) {
 7970: 	    var cmd = radioSelection(formname.radioChoice);
 7971: 	    var cmdsave = cmd;
 7972: 	} else {
 7973: 	    cmd = cmdx;
 7974: 	    cmdsave = 'submission';
 7975: 	}
 7976: 	formname.command.value = cmd;
 7977: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7978: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7979: 	if (val < 5) formname.submit();
 7980: 	if (val == 5) {
 7981: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7982: 	    formname.submit();
 7983: 	}
 7984: 	if (val < 7) formname.submit();
 7985:     }
 7986: 
 7987:     function checkReceiptNo(formname,nospace) {
 7988: 	var receiptNo = formname.receipt.value;
 7989: 	var checkOpt = false;
 7990: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7991: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7992: 	if (checkOpt) {
 7993: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7994: 	    formname.receipt.value = "";
 7995: 	    formname.receipt.focus();
 7996: 	    return false;
 7997: 	}
 7998: 	return true;
 7999:     }
 8000: </script>
 8001: GRADINGMENUJS
 8002:     &commonJSfunctions($request);
 8003:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8004:     my $result;
 8005:     my (undef,$sections) = &getclasslist('all','0');
 8006:     my $savedState = &savedState();
 8007:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8008:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8009:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8010:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8011: 
 8012:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8013: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8014: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8015: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8016: 	'<input type="hidden" name="command"     value="" />'."\n".
 8017: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8018: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8019: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8020: 
 8021:     $result.='
 8022:     <div class="LC_grade_select_mode">
 8023:       <div class="LC_grade_select_mode_current">
 8024:         <h2>
 8025:           '.&mt('Grade Current Resource').'
 8026:         </h2>
 8027:         <div class="LC_grade_select_mode_body">
 8028:           <div class="LC_grades_resource_info">
 8029:            '.$table.'
 8030:           </div>
 8031:           <div class="LC_grade_select_mode_selector">
 8032:              <div class="LC_grade_select_mode_selector_header">
 8033:                 '.&mt('Sections').'
 8034:              </div>
 8035:              <div class="LC_grade_select_mode_selector_body">
 8036: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8037:     if (ref($sections)) {
 8038: 	foreach my $section (sort (@$sections)) {
 8039: 	    $result.='<option value="'.$section.'" '.
 8040: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8041: 	}
 8042:     }
 8043:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8044:     $result.='
 8045:              </div>
 8046:           </div>
 8047:           <div class="LC_grade_select_mode_selector">
 8048:              <div class="LC_grade_select_mode_selector_header">
 8049:                 '.&mt('Groups').'
 8050:              </div>
 8051:              <div class="LC_grade_select_mode_selector_body">
 8052:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8053:              </div>
 8054:           </div>
 8055:           <div class="LC_grade_select_mode_selector">
 8056:              <div class="LC_grade_select_mode_selector_header">
 8057:                 '.&mt('Access Status').'
 8058:              </div>
 8059:              <div class="LC_grade_select_mode_selector_body">
 8060:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8061:              </div>
 8062:           </div>
 8063:           <div class="LC_grade_select_mode_selector">
 8064:              <div class="LC_grade_select_mode_selector_header">
 8065:                 '.&mt('Submission Status').'
 8066:              </div>
 8067:              <div class="LC_grade_select_mode_selector_body">
 8068:                <select name="submitonly" size="5">
 8069: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8070: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8071: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8072: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8073:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8074:                </select>
 8075:              </div>
 8076:           </div>
 8077:           <div class="LC_grade_select_mode_type_body">
 8078:             <div class="LC_grade_select_mode_type">
 8079:               <label>
 8080:                 <input type="radio" name="radioChoice" value="submission" '.
 8081:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8082:              &mt('Select individual students to grade and view submissions.').'
 8083: 	      </label> 
 8084:             </div>
 8085:             <div class="LC_grade_select_mode_type">
 8086: 	      <label>
 8087:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8088:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8089:                     &mt('Grade all selected students in a grading table.').'
 8090:               </label>
 8091:             </div>
 8092:             <div class="LC_grade_select_mode_type">
 8093: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8094:             </div>
 8095:           </div>
 8096:         </div>
 8097:       </div>
 8098:       <div class="LC_grade_select_mode_page">
 8099:         <h2>
 8100:          '.&mt('Grade Complete Folder for One Student').'
 8101:         </h2>
 8102:         <div class="LC_grades_select_mode_body">
 8103:           <div class="LC_grade_select_mode_type_body">
 8104:             <div class="LC_grade_select_mode_type">
 8105:               <label>
 8106:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8107: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8108:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8109:               </label>
 8110:             </div>
 8111:             <div class="LC_grade_select_mode_type">
 8112: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8113:             </div>
 8114:           </div>
 8115:         </div>
 8116:       </div>
 8117:     </div>
 8118:   </form>';
 8119:     $result .= &show_grading_menu_form($symb);
 8120:     return $result;
 8121: }
 8122: 
 8123: sub reset_perm {
 8124:     undef(%perm);
 8125: }
 8126: 
 8127: sub init_perm {
 8128:     &reset_perm();
 8129:     foreach my $test_perm ('vgr','mgr','opa') {
 8130: 
 8131: 	my $scope = $env{'request.course.id'};
 8132: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8133: 
 8134: 	    $scope .= '/'.$env{'request.course.sec'};
 8135: 	    if ( $perm{$test_perm}=
 8136: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8137: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8138: 	    } else {
 8139: 		delete($perm{$test_perm});
 8140: 	    }
 8141: 	}
 8142:     }
 8143: }
 8144: 
 8145: sub gather_clicker_ids {
 8146:     my %clicker_ids;
 8147: 
 8148:     my $classlist = &Apache::loncoursedata::get_classlist();
 8149: 
 8150:     # Set up a couple variables.
 8151:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8152:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8153:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8154: 
 8155:     foreach my $student (keys(%$classlist)) {
 8156:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8157:         my $username = $classlist->{$student}->[$username_idx];
 8158:         my $domain   = $classlist->{$student}->[$domain_idx];
 8159:         my $clickers =
 8160: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8161:         foreach my $id (split(/\,/,$clickers)) {
 8162:             $id=~s/^[\#0]+//;
 8163:             $id=~s/[\-\:]//g;
 8164:             if (exists($clicker_ids{$id})) {
 8165: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8166:             } else {
 8167: 		$clicker_ids{$id}=$username.':'.$domain;
 8168:             }
 8169:         }
 8170:     }
 8171:     return %clicker_ids;
 8172: }
 8173: 
 8174: sub gather_adv_clicker_ids {
 8175:     my %clicker_ids;
 8176:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8177:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8178:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8179:     foreach my $element (sort(keys(%coursepersonnel))) {
 8180:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8181:             my ($puname,$pudom)=split(/\:/,$person);
 8182:             my $clickers =
 8183: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8184:             foreach my $id (split(/\,/,$clickers)) {
 8185: 		$id=~s/^[\#0]+//;
 8186:                 $id=~s/[\-\:]//g;
 8187: 		if (exists($clicker_ids{$id})) {
 8188: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8189: 		} else {
 8190: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8191: 		}
 8192:             }
 8193:         }
 8194:     }
 8195:     return %clicker_ids;
 8196: }
 8197: 
 8198: sub clicker_grading_parameters {
 8199:     return ('gradingmechanism' => 'scalar',
 8200:             'upfiletype' => 'scalar',
 8201:             'specificid' => 'scalar',
 8202:             'pcorrect' => 'scalar',
 8203:             'pincorrect' => 'scalar');
 8204: }
 8205: 
 8206: sub process_clicker {
 8207:     my ($r)=@_;
 8208:     my ($symb)=&get_symb($r);
 8209:     if (!$symb) {return '';}
 8210:     my $result=&checkforfile_js();
 8211:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8212:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8213:     $result.=$table;
 8214:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8215:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8216:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8217:         '.</b></td></tr>'."\n";
 8218:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8219: # Attempt to restore parameters from last session, set defaults if not present
 8220:     my %Saveable_Parameters=&clicker_grading_parameters();
 8221:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8222:                                                  \%Saveable_Parameters);
 8223:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8224:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8225:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8226:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8227: 
 8228:     my %checked;
 8229:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 8230:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8231:           $checked{$gradingmechanism}="checked='checked'";
 8232:        }
 8233:     }
 8234: 
 8235:     my $upload=&mt("Upload File");
 8236:     my $type=&mt("Type");
 8237:     my $attendance=&mt("Award points just for participation");
 8238:     my $personnel=&mt("Correctness determined from response by course personnel");
 8239:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8240:     my $pcorrect=&mt("Percentage points for correct solution");
 8241:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8242:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8243: 						   ('iclicker' => 'i>clicker',
 8244:                                                     'interwrite' => 'interwrite PRS'));
 8245:     $symb = &Apache::lonenc::check_encrypt($symb);
 8246:     $result.=<<ENDUPFORM;
 8247: <script type="text/javascript">
 8248: function sanitycheck() {
 8249: // Accept only integer percentages
 8250:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8251:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8252: // Find out grading choice
 8253:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8254:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8255:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8256:       }
 8257:    }
 8258: // By default, new choice equals user selection
 8259:    newgradingchoice=gradingchoice;
 8260: // Not good to give more points for false answers than correct ones
 8261:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8262:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8263:    }
 8264: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8265:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8266:       document.forms.gradesupload.pcorrect.value=100;
 8267:       document.forms.gradesupload.pincorrect.value=100;
 8268:    }
 8269: // If the values are different, cannot be attendance only
 8270:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8271:        (gradingchoice=='attendance')) {
 8272:        newgradingchoice='personnel';
 8273:    }
 8274: // Change grading choice to new one
 8275:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8276:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8277:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8278:       } else {
 8279:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8280:       }
 8281:    }
 8282: // Remember the old state
 8283:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8284: }
 8285: </script>
 8286: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8287: <input type="hidden" name="symb" value="$symb" />
 8288: <input type="hidden" name="command" value="processclickerfile" />
 8289: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8290: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8291: <input type="file" name="upfile" size="50" />
 8292: <br /><label>$type: $selectform</label>
 8293: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8294: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8295: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8296: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8297: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8298: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8299: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8300: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8301: </form>
 8302: ENDUPFORM
 8303:     $result.='</td></tr></table>'."\n".
 8304:              '</td></tr></table><br /><br />'."\n";
 8305:     $result.=&show_grading_menu_form($symb);
 8306:     return $result;
 8307: }
 8308: 
 8309: sub process_clicker_file {
 8310:     my ($r)=@_;
 8311:     my ($symb)=&get_symb($r);
 8312:     if (!$symb) {return '';}
 8313: 
 8314:     my %Saveable_Parameters=&clicker_grading_parameters();
 8315:     &Apache::loncommon::store_course_settings('grades_clicker',
 8316:                                               \%Saveable_Parameters);
 8317: 
 8318:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8319:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8320: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8321: 	return $result.&show_grading_menu_form($symb);
 8322:     }
 8323:     my %clicker_ids=&gather_clicker_ids();
 8324:     my %correct_ids;
 8325:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8326: 	%correct_ids=&gather_adv_clicker_ids();
 8327:     }
 8328:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8329: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8330: 	   $correct_id=~tr/a-z/A-Z/;
 8331: 	   $correct_id=~s/\s//gs;
 8332: 	   $correct_id=~s/^[\#0]+//;
 8333:            $correct_id=~s/[\-\:]//g;
 8334:            if ($correct_id) {
 8335: 	      $correct_ids{$correct_id}='specified';
 8336:            }
 8337:         }
 8338:     }
 8339:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8340: 	$result.=&mt('Score based on attendance only');
 8341:     } else {
 8342: 	my $number=0;
 8343: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8344: 	foreach my $id (sort(keys(%correct_ids))) {
 8345: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8346: 	    if ($correct_ids{$id} eq 'specified') {
 8347: 		$result.=&mt('specified');
 8348: 	    } else {
 8349: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8350: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8351: 	    }
 8352: 	    $number++;
 8353: 	}
 8354:         $result.="</p>\n";
 8355: 	if ($number==0) {
 8356: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8357: 	    return $result.&show_grading_menu_form($symb);
 8358: 	}
 8359:     }
 8360:     if (length($env{'form.upfile'}) < 2) {
 8361:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8362: 		     '<span class="LC_error">',
 8363: 		     '</span>',
 8364: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8365:         return $result.&show_grading_menu_form($symb);
 8366:     }
 8367: 
 8368: # Were able to get all the info needed, now analyze the file
 8369: 
 8370:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8371:     $symb = &Apache::lonenc::check_encrypt($symb);
 8372:     my $heading=&mt('Scanning clicker file');
 8373:     $result.=(<<ENDHEADER);
 8374: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8375: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8376: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8377: <form method="post" action="/adm/grades" name="clickeranalysis">
 8378: <input type="hidden" name="symb" value="$symb" />
 8379: <input type="hidden" name="command" value="assignclickergrades" />
 8380: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8381: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8382: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8383: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8384: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8385: ENDHEADER
 8386:     my %responses;
 8387:     my @questiontitles;
 8388:     my $errormsg='';
 8389:     my $number=0;
 8390:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8391: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8392:     }
 8393:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8394:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8395:     }
 8396:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8397:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8398:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8399:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8400:              '<br />';
 8401: # Remember Question Titles
 8402: # FIXME: Possibly need delimiter other than ":"
 8403:     for (my $i=0;$i<$number;$i++) {
 8404:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8405:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8406:     }
 8407:     my $correct_count=0;
 8408:     my $student_count=0;
 8409:     my $unknown_count=0;
 8410: # Match answers with usernames
 8411: # FIXME: Possibly need delimiter other than ":"
 8412:     foreach my $id (keys(%responses)) {
 8413:        if ($correct_ids{$id}) {
 8414:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8415:           $correct_count++;
 8416:        } elsif ($clicker_ids{$id}) {
 8417:           if ($clicker_ids{$id}=~/\,/) {
 8418: # More than one user with the same clicker!
 8419:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8420:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8421:                            "<select name='multi".$id."'>";
 8422:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8423:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8424:              }
 8425:              $result.='</select>';
 8426:              $unknown_count++;
 8427:           } else {
 8428: # Good: found one and only one user with the right clicker
 8429:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8430:              $student_count++;
 8431:           }
 8432:        } else {
 8433:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8434:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8435:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8436:                    "\n".&mt("Domain").": ".
 8437:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8438:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8439:           $unknown_count++;
 8440:        }
 8441:     }
 8442:     $result.='<hr />'.
 8443:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8444:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 8445:        if ($correct_count==0) {
 8446:           $errormsg.="Found no correct answers answers for grading!";
 8447:        } elsif ($correct_count>1) {
 8448:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8449:        }
 8450:     }
 8451:     if ($number<1) {
 8452:        $errormsg.="Found no questions.";
 8453:     }
 8454:     if ($errormsg) {
 8455:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8456:     } else {
 8457:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8458:     }
 8459:     $result.='</form></td></tr></table>'."\n".
 8460:              '</td></tr></table><br /><br />'."\n";
 8461:     return $result.&show_grading_menu_form($symb);
 8462: }
 8463: 
 8464: sub iclicker_eval {
 8465:     my ($questiontitles,$responses)=@_;
 8466:     my $number=0;
 8467:     my $errormsg='';
 8468:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8469:         my %components=&Apache::loncommon::record_sep($line);
 8470:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8471: 	if ($entries[0] eq 'Question') {
 8472: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8473: 		$$questiontitles[$number]=$entries[$i];
 8474: 		$number++;
 8475: 	    }
 8476: 	}
 8477: 	if ($entries[0]=~/^\#/) {
 8478: 	    my $id=$entries[0];
 8479: 	    my @idresponses;
 8480: 	    $id=~s/^[\#0]+//;
 8481: 	    for (my $i=0;$i<$number;$i++) {
 8482: 		my $idx=3+$i*6;
 8483: 		push(@idresponses,$entries[$idx]);
 8484: 	    }
 8485: 	    $$responses{$id}=join(',',@idresponses);
 8486: 	}
 8487:     }
 8488:     return ($errormsg,$number);
 8489: }
 8490: 
 8491: sub interwrite_eval {
 8492:     my ($questiontitles,$responses)=@_;
 8493:     my $number=0;
 8494:     my $errormsg='';
 8495:     my $skipline=1;
 8496:     my $questionnumber=0;
 8497:     my %idresponses=();
 8498:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8499:         my %components=&Apache::loncommon::record_sep($line);
 8500:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8501:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8502:         if ($entries[1] eq 'Response') { $skipline=1; }
 8503:         next if $skipline;
 8504:         if ($entries[0]!=$questionnumber) {
 8505:            $questionnumber=$entries[0];
 8506:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8507:            $number++;
 8508:         }
 8509:         my $id=$entries[4];
 8510:         $id=~s/^[\#0]+//;
 8511:         $id=~s/^v\d*\://i;
 8512:         $id=~s/[\-\:]//g;
 8513:         $idresponses{$id}[$number]=$entries[6];
 8514:     }
 8515:     foreach my $id (keys %idresponses) {
 8516:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8517:        $$responses{$id}=~s/^\s*\,//;
 8518:     }
 8519:     return ($errormsg,$number);
 8520: }
 8521: 
 8522: sub assign_clicker_grades {
 8523:     my ($r)=@_;
 8524:     my ($symb)=&get_symb($r);
 8525:     if (!$symb) {return '';}
 8526: # See which part we are saving to
 8527:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8528: # FIXME: This should probably look for the first handgradeable part
 8529:     my $part=$$partlist[0];
 8530: # Start screen output
 8531:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8532: 
 8533:     my $heading=&mt('Assigning grades based on clicker file');
 8534:     $result.=(<<ENDHEADER);
 8535: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8536: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8537: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8538: ENDHEADER
 8539: # Get correct result
 8540: # FIXME: Possibly need delimiter other than ":"
 8541:     my @correct=();
 8542:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8543:     my $number=$env{'form.number'};
 8544:     if ($gradingmechanism ne 'attendance') {
 8545:        foreach my $key (keys(%env)) {
 8546:           if ($key=~/^form\.correct\:/) {
 8547:              my @input=split(/\,/,$env{$key});
 8548:              for (my $i=0;$i<=$#input;$i++) {
 8549:                  if (($correct[$i]) && ($input[$i]) &&
 8550:                      ($correct[$i] ne $input[$i])) {
 8551:                     $result.='<br /><span class="LC_warning">'.
 8552:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8553:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8554:                  } elsif ($input[$i]) {
 8555:                     $correct[$i]=$input[$i];
 8556:                  }
 8557:              }
 8558:           }
 8559:        }
 8560:        for (my $i=0;$i<$number;$i++) {
 8561:           if (!$correct[$i]) {
 8562:              $result.='<br /><span class="LC_error">'.
 8563:                       &mt('No correct result given for question "[_1]"!',
 8564:                           $env{'form.question:'.$i}).'</span>';
 8565:           }
 8566:        }
 8567:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8568:     }
 8569: # Start grading
 8570:     my $pcorrect=$env{'form.pcorrect'};
 8571:     my $pincorrect=$env{'form.pincorrect'};
 8572:     my $storecount=0;
 8573:     foreach my $key (keys(%env)) {
 8574:        my $user='';
 8575:        if ($key=~/^form\.student\:(.*)$/) {
 8576:           $user=$1;
 8577:        }
 8578:        if ($key=~/^form\.unknown\:(.*)$/) {
 8579:           my $id=$1;
 8580:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8581:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8582:           } elsif ($env{'form.multi'.$id}) {
 8583:              $user=$env{'form.multi'.$id};
 8584:           }
 8585:        }
 8586:        if ($user) { 
 8587:           my @answer=split(/\,/,$env{$key});
 8588:           my $sum=0;
 8589:           for (my $i=0;$i<$number;$i++) {
 8590:              if ($answer[$i]) {
 8591:                 if ($gradingmechanism eq 'attendance') {
 8592:                    $sum+=$pcorrect;
 8593:                 } else {
 8594:                    if ($answer[$i] eq $correct[$i]) {
 8595:                       $sum+=$pcorrect;
 8596:                    } else {
 8597:                       $sum+=$pincorrect;
 8598:                    }
 8599:                 }
 8600:              }
 8601:           }
 8602:           my $ave=$sum/(100*$number);
 8603: # Store
 8604:           my ($username,$domain)=split(/\:/,$user);
 8605:           my %grades=();
 8606:           $grades{"resource.$part.solved"}='correct_by_override';
 8607:           $grades{"resource.$part.awarded"}=$ave;
 8608:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8609:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8610:                                                  $env{'request.course.id'},
 8611:                                                  $domain,$username);
 8612:           if ($returncode ne 'ok') {
 8613:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8614:           } else {
 8615:              $storecount++;
 8616:           }
 8617:        }
 8618:     }
 8619: # We are done
 8620:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8621:              '</td></tr></table>'."\n".
 8622:              '</td></tr></table><br /><br />'."\n";
 8623:     return $result.&show_grading_menu_form($symb);
 8624: }
 8625: 
 8626: sub handler {
 8627:     my $request=$_[0];
 8628:     &reset_caches();
 8629:     if ($env{'browser.mathml'}) {
 8630: 	&Apache::loncommon::content_type($request,'text/xml');
 8631:     } else {
 8632: 	&Apache::loncommon::content_type($request,'text/html');
 8633:     }
 8634:     $request->send_http_header;
 8635:     return '' if $request->header_only;
 8636:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8637:     my $symb=&get_symb($request,1);
 8638:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8639:     my $command=$commands[0];
 8640: 
 8641:     if ($#commands > 0) {
 8642: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8643:     }
 8644: 
 8645:     $ssi_error = 0;
 8646:     $request->print(&Apache::loncommon::start_page('Grading'));
 8647:     if ($symb eq '' && $command eq '') {
 8648: 	if ($env{'user.adv'}) {
 8649: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8650: 		($env{'form.codethree'})) {
 8651: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8652: 		    $env{'form.codethree'};
 8653: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8654: 		    &Apache::lonnet::checkin($token);
 8655: 		if ($tsymb) {
 8656: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8657: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8658: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8659: 					  ('grade_username' => $tuname,
 8660: 					   'grade_domain' => $tudom,
 8661: 					   'grade_courseid' => $tcrsid,
 8662: 					   'grade_symb' => $tsymb)));
 8663: 		    } else {
 8664: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8665: 		    }
 8666: 		} else {
 8667: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8668: 		}
 8669: 	    } else {
 8670: 		$request->print(&Apache::lonxml::tokeninputfield());
 8671: 	    }
 8672: 	}
 8673:     } else {
 8674: 	&init_perm();
 8675: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8676: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8677: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8678: 	    &pickStudentPage($request);
 8679: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8680: 	    &displayPage($request);
 8681: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8682: 	    &updateGradeByPage($request);
 8683: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8684: 	    &processGroup($request);
 8685: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8686: 	    $request->print(&grading_menu($request));
 8687: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8688: 	    $request->print(&submit_options($request));
 8689: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8690: 	    $request->print(&viewgrades($request));
 8691: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8692: 	    $request->print(&processHandGrade($request));
 8693: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8694: 	    $request->print(&editgrades($request));
 8695: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8696: 	    $request->print(&verifyreceipt($request));
 8697:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8698:             $request->print(&process_clicker($request));
 8699:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8700:             $request->print(&process_clicker_file($request));
 8701:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8702:             $request->print(&assign_clicker_grades($request));
 8703: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8704: 	    $request->print(&upcsvScores_form($request));
 8705: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8706: 	    $request->print(&csvupload($request));
 8707: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8708: 	    $request->print(&csvuploadmap($request));
 8709: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8710: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8711: 		$request->print(&csvuploadoptions($request));
 8712: 	    } else {
 8713: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8714: 		    $env{'form.upfile_associate'} = 'reverse';
 8715: 		} else {
 8716: 		    $env{'form.upfile_associate'} = 'forward';
 8717: 		}
 8718: 		$request->print(&csvuploadmap($request));
 8719: 	    }
 8720: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8721: 	    $request->print(&csvuploadassign($request));
 8722: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8723: 	    $request->print(&scantron_selectphase($request));
 8724:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8725:  	    $request->print(&scantron_do_warning($request));
 8726: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8727: 	    $request->print(&scantron_validate_file($request));
 8728: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8729: 	    $request->print(&scantron_process_students($request));
 8730:  	} elsif ($command eq 'scantronupload' && 
 8731:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8732: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8733:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8734:  	} elsif ($command eq 'scantronupload_save' &&
 8735:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8736: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8737:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8738:  	} elsif ($command eq 'scantron_download' &&
 8739: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8740:  	    $request->print(&scantron_download_scantron_data($request));
 8741: 	} elsif ($command) {
 8742: 	    $request->print("Access Denied ($command)");
 8743: 	}
 8744:     }
 8745:     if ($ssi_error) {
 8746: 	&ssi_print_error($request);
 8747:     }
 8748:     $request->print(&Apache::loncommon::end_page());
 8749:     &reset_caches();
 8750:     return '';
 8751: }
 8752: 
 8753: 1;
 8754: 
 8755: __END__;

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