File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.526: download - view: text, annotated - select for diffs
Tue Jul 8 05:29:24 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Localization.
- Missing &mt().

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.526 2008/07/08 05:29:24 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::lonpickcode;
   39: use Apache::loncoursedata;
   40: use Apache::lonmsg();
   41: use Apache::Constants qw(:common);
   42: use Apache::lonlocal;
   43: use Apache::lonenc;
   44: use String::Similarity;
   45: use LONCAPA;
   46: 
   47: use POSIX qw(floor);
   48: 
   49: 
   50: 
   51: my %perm=();
   52: 
   53: #  These variables are used to recover from ssi errors
   54: 
   55: my $ssi_retries = 5;
   56: my $ssi_error;
   57: my $ssi_error_resource;
   58: my $ssi_error_message;
   59: 
   60: 
   61: #  Do an ssi with retries:
   62: #  While I'd love to factor out this with the vesrion in lonprintout,
   63: #  that would either require a data coupling between modules, which I refuse to perpetuate
   64: #  (there's quite enough of that already), or would require the invention of another infrastructure
   65: #  I'm not quite ready to invent (e.g. an ssi_with_retry object).
   66: #
   67: # At least the logic that drives this has been pulled out into loncommon.
   68: 
   69: 
   70: #
   71: #   ssi_with_retries - Does the server side include of a resource.
   72: #                      if the ssi call returns an error we'll retry it up to
   73: #                      the number of times requested by the caller.
   74: #                      If we still have a proble, no text is appended to the
   75: #                      output and we set some global variables.
   76: #                      to indicate to the caller an SSI error occurred.  
   77: #                      All of this is supposed to deal with the issues described
   78: #                      in LonCAPA BZ 5631 see:
   79: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
   80: #                      by informing the user that this happened.
   81: #
   82: # Parameters:
   83: #   resource   - The resource to include.  This is passed directly, without
   84: #                interpretation to lonnet::ssi.
   85: #   form       - The form hash parameters that guide the interpretation of the resource
   86: #                
   87: #   retries    - Number of retries allowed before giving up completely.
   88: # Returns:
   89: #   On success, returns the rendered resource identified by the resource parameter.
   90: # Side Effects:
   91: #   The following global variables can be set:
   92: #    ssi_error                - If an unrecoverable error occurred this becomes true.
   93: #                               It is up to the caller to initialize this to false
   94: #                               if desired.
   95: #    ssi_error_resource  - If an unrecoverable error occurred, this is the value
   96: #                               of the resource that could not be rendered by the ssi
   97: #                               call.
   98: #    ssi_error_message   - The error string fetched from the ssi response
   99: #                               in the event of an error.
  100: #
  101: sub ssi_with_retries {
  102:     my ($resource, $retries, %form) = @_;
  103:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  104:     if ($response->is_error) {
  105: 	$ssi_error          = 1;
  106: 	$ssi_error_resource = $resource;
  107: 	$ssi_error_message  = $response->code . " " . $response->message;
  108:     }
  109: 
  110:     return $content;
  111: 
  112: }
  113: #
  114: #  Prodcuces an ssi retry failure error message to the user:
  115: #
  116: 
  117: sub ssi_print_error {
  118:     my ($r) = @_;
  119:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
  120:     $r->print('
  121: <br />
  122: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
  123: <p>
  124: '.&mt('Unable to retrieve a resource from a server:').'<br />
  125: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
  126: '.&mt('Error:').' '.$ssi_error_message.'
  127: </p>
  128: <p>'.
  129: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
  130: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  131: '</p>');
  132:     return;
  133: }
  134: 
  135: #
  136: # --- Retrieve the parts from the metadata file.---
  137: sub getpartlist {
  138:     my ($symb) = @_;
  139: 
  140:     my $navmap   = Apache::lonnavmaps::navmap->new();
  141:     my $res      = $navmap->getBySymb($symb);
  142:     my $partlist = $res->parts();
  143:     my $url      = $res->src();
  144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  145: 
  146:     my @stores;
  147:     foreach my $part (@{ $partlist }) {
  148: 	foreach my $key (@metakeys) {
  149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  150: 	}
  151:     }
  152:     return @stores;
  153: }
  154: 
  155: # --- Get the symbolic name of a problem and the url
  156: sub get_symb {
  157:     my ($request,$silent) = @_;
  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  160:     if ($symb eq '') { 
  161: 	if (!$silent) {
  162: 	    $request->print("Unable to handle ambiguous references:$url:.");
  163: 	    return ();
  164: 	}
  165:     }
  166:     &Apache::lonenc::check_decrypt(\$symb);
  167:     return ($symb);
  168: }
  169: 
  170: #--- Format fullname, username:domain if different for display
  171: #--- Use anywhere where the student names are listed
  172: sub nameUserString {
  173:     my ($type,$fullname,$uname,$udom) = @_;
  174:     if ($type eq 'header') {
  175: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  176:     } else {
  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  179:     }
  180: }
  181: 
  182: #--- Get the partlist and the response type for a given problem. ---
  183: #--- Indicate if a response type is coded handgraded or not. ---
  184: sub response_type {
  185:     my ($symb) = shift;
  186: 
  187:     my $navmap = Apache::lonnavmaps::navmap->new();
  188:     my $res = $navmap->getBySymb($symb);
  189:     my $partlist = $res->parts();
  190:     my %vPart = 
  191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  192:     my (%response_types,%handgrade);
  193:     foreach my $part (@{ $partlist }) {
  194: 	next if (%vPart && !exists($vPart{$part}));
  195: 
  196: 	my @types = $res->responseType($part);
  197: 	my @ids = $res->responseIds($part);
  198: 	for (my $i=0; $i < scalar(@ids); $i++) {
  199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  200: 	    $handgrade{$part.'_'.$ids[$i]} = 
  201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  202: 				     '.handgrade',$symb);
  203: 	}
  204:     }
  205:     return ($partlist,\%handgrade,\%response_types);
  206: }
  207: 
  208: sub flatten_responseType {
  209:     my ($responseType) = @_;
  210:     my @part_response_id =
  211: 	map { 
  212: 	    my $part = $_;
  213: 	    map {
  214: 		[$part,$_]
  215: 		} sort(keys(%{ $responseType->{$part} }));
  216: 	} sort(keys(%$responseType));
  217:     return @part_response_id;
  218: }
  219: 
  220: sub get_display_part {
  221:     my ($partID,$symb)=@_;
  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  223:     if (defined($display) and $display ne '') {
  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  225:     } else {
  226: 	$display=$partID;
  227:     }
  228:     return $display;
  229: }
  230: 
  231: #--- Show resource title
  232: #--- and parts and response type
  233: sub showResourceInfo {
  234:     my ($symb,$probTitle,$checkboxes) = @_;
  235:     my $col=3;
  236:     if ($checkboxes) { $col=4; }
  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  238:     $result .='<table border="0">';
  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  240:     my %resptype = ();
  241:     my $hdgrade='no';
  242:     my %partsseen;
  243:     foreach my $partID (sort(keys(%$responseType))) {
  244: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  246: 	    my $responsetype = $responseType->{$partID}->{$resID};
  247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  248: 	    $result.='<tr>';
  249: 	    if ($checkboxes) {
  250: 		if (exists($partsseen{$partID})) {
  251: 		    $result.="<td>&nbsp;</td>";
  252: 		} else {
  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  254: 		}
  255: 		$partsseen{$partID}=1;
  256: 	    }
  257: 	    my $display_part=&get_display_part($partID,$symb);
  258: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
  259: 		$resID.'</span></td>'.
  260: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
  261: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  262: 	}
  263:     }
  264:     $result.='</table>'."\n";
  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  266: }
  267: 
  268: sub reset_caches {
  269:     &reset_analyze_cache();
  270:     &reset_perm();
  271: }
  272: 
  273: {
  274:     my %analyze_cache;
  275: 
  276:     sub reset_analyze_cache {
  277: 	undef(%analyze_cache);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  284: 
  285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  286: 	$url=&Apache::lonnet::clutter($url);
  287: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  288: 					   ('grade_target' => 'analyze',
  289: 					    'grade_domain' => $udom,
  290: 					    'grade_symb' => $symb,
  291: 					    'grade_courseid' => 
  292: 					    $env{'request.course.id'},
  293: 					    'grade_username' => $uname,
  294:                                             'grade_noincrement' => $no_increment));
  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  297: 	return $analyze_cache{$key} = \%analyze;
  298:     }
  299: 
  300:     sub get_order {
  301: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  302: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  303: 	return $analyze->{"$partid.$respid.shown"};
  304:     }
  305: 
  306:     sub get_radiobutton_correct_foil {
  307: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  308: 	my $analyze = &get_analyze($symb,$uname,$udom);
  309: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  310: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  311: 		return $foil;
  312: 	    }
  313: 	}
  314:     }
  315: }
  316: 
  317: #--- Clean response type for display
  318: #--- Currently filters option/rank/radiobutton/match/essay/Task
  319: #        response types only.
  320: sub cleanRecord {
  321:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  322: 	$uname,$udom) = @_;
  323:     my $grayFont = '<span class="LC_internal_info">';
  324:     if ($response =~ /^(option|rank)$/) {
  325: 	my %answer=&Apache::lonnet::str2hash($answer);
  326: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  327: 	my ($toprow,$bottomrow);
  328: 	foreach my $foil (@$order) {
  329: 	    if ($grading{$foil} == 1) {
  330: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  331: 	    } else {
  332: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  333: 	    }
  334: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  335: 	}
  336: 	return '<blockquote><table border="1">'.
  337: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  338: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  339: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  340:     } elsif ($response eq 'match') {
  341: 	my %answer=&Apache::lonnet::str2hash($answer);
  342: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  343: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  344: 	my ($toprow,$middlerow,$bottomrow);
  345: 	foreach my $foil (@$order) {
  346: 	    my $item=shift(@items);
  347: 	    if ($grading{$foil} == 1) {
  348: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  349: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  350: 	    } else {
  351: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  352: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  353: 	    }
  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  355: 	}
  356: 	return '<blockquote><table border="1">'.
  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  359: 	    $middlerow.'</tr>'.
  360: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  361: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  362:     } elsif ($response eq 'radiobutton') {
  363: 	my %answer=&Apache::lonnet::str2hash($answer);
  364: 	my ($toprow,$bottomrow);
  365: 	my $correct = 
  366: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  367: 	foreach my $foil (@$order) {
  368: 	    if (exists($answer{$foil})) {
  369: 		if ($foil eq $correct) {
  370: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  371: 		} else {
  372: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  373: 		}
  374: 	    } else {
  375: 		$toprow.='<td>'.&mt('false').'</td>';
  376: 	    }
  377: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  378: 	}
  379: 	return '<blockquote><table border="1">'.
  380: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  381: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  382: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  383:     } elsif ($response eq 'essay') {
  384: 	if (! exists ($env{'form.'.$symb})) {
  385: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  386: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  387: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  388: 
  389: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  390: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  391: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  392: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  393: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  394: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  395: 	}
  396: 	$answer =~ s-\n-<br />-g;
  397: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  398:     } elsif ( $response eq 'organic') {
  399: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  400: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  401: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  402: 	return $result;
  403:     } elsif ( $response eq 'Task') {
  404: 	if ( $answer eq 'SUBMITTED') {
  405: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  406: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  407: 	    return $result;
  408: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  409: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  410: 			       keys(%{$record}));
  411: 	    return join('<br />',($version,@matches));
  412: 			       
  413: 			       
  414: 	} else {
  415: 	    my $result =
  416: 		'<p>'
  417: 		.&mt('Overall result: [_1]',
  418: 		     $record->{$version."resource.$respid.$partid.status"})
  419: 		.'</p>';
  420: 	    
  421: 	    $result .= '<ul>';
  422: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  423: 			     keys(%{$record}));
  424: 	    foreach my $grade (sort(@grade)) {
  425: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  426: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  427: 				     $dim, $record->{$grade}).
  428: 			  '</li>';
  429: 	    }
  430: 	    $result.='</ul>';
  431: 	    return $result;
  432: 	}
  433:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  434: 	$answer = 
  435: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  436: 							      $answer);
  437:     }
  438:     return $answer;
  439: }
  440: 
  441: #-- A couple of common js functions
  442: sub commonJSfunctions {
  443:     my $request = shift;
  444:     $request->print(<<COMMONJSFUNCTIONS);
  445: <script type="text/javascript" language="javascript">
  446:     function radioSelection(radioButton) {
  447: 	var selection=null;
  448: 	if (radioButton.length > 1) {
  449: 	    for (var i=0; i<radioButton.length; i++) {
  450: 		if (radioButton[i].checked) {
  451: 		    return radioButton[i].value;
  452: 		}
  453: 	    }
  454: 	} else {
  455: 	    if (radioButton.checked) return radioButton.value;
  456: 	}
  457: 	return selection;
  458:     }
  459: 
  460:     function pullDownSelection(selectOne) {
  461: 	var selection="";
  462: 	if (selectOne.length > 1) {
  463: 	    for (var i=0; i<selectOne.length; i++) {
  464: 		if (selectOne[i].selected) {
  465: 		    return selectOne[i].value;
  466: 		}
  467: 	    }
  468: 	} else {
  469:             // only one value it must be the selected one
  470: 	    return selectOne.value;
  471: 	}
  472:     }
  473: </script>
  474: COMMONJSFUNCTIONS
  475: }
  476: 
  477: #--- Dumps the class list with usernames,list of sections,
  478: #--- section, ids and fullnames for each user.
  479: sub getclasslist {
  480:     my ($getsec,$filterlist,$getgroup) = @_;
  481:     my @getsec;
  482:     my @getgroup;
  483:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  484:     if (!ref($getsec)) {
  485: 	if ($getsec ne '' && $getsec ne 'all') {
  486: 	    @getsec=($getsec);
  487: 	}
  488:     } else {
  489: 	@getsec=@{$getsec};
  490:     }
  491:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  492:     if (!ref($getgroup)) {
  493: 	if ($getgroup ne '' && $getgroup ne 'all') {
  494: 	    @getgroup=($getgroup);
  495: 	}
  496:     } else {
  497: 	@getgroup=@{$getgroup};
  498:     }
  499:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  500: 
  501:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  502:     # Bail out if we were unable to get the classlist
  503:     return if (! defined($classlist));
  504:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  505:     #
  506:     my %sections;
  507:     my %fullnames;
  508:     foreach my $student (keys(%$classlist)) {
  509:         my $end      = 
  510:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  511:         my $start    = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  513:         my $id       = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  515:         my $section  = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  517:         my $fullname = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  519:         my $status   = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  521:         my $group   = 
  522:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  523: 	# filter students according to status selected
  524: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  525: 	    if (!($stu_status =~ $status)) {
  526: 		delete($classlist->{$student});
  527: 		next;
  528: 	    }
  529: 	}
  530: 	# filter students according to groups selected
  531: 	my @stu_groups = split(/,/,$group);
  532: 	if (@getgroup) {
  533: 	    my $exclude = 1;
  534: 	    foreach my $grp (@getgroup) {
  535: 	        foreach my $stu_group (@stu_groups) {
  536: 	            if ($stu_group eq $grp) {
  537: 	                $exclude = 0;
  538:     	            } 
  539: 	        }
  540:     	        if (($grp eq 'none') && !$group) {
  541:         	        $exclude = 0;
  542:         	}
  543: 	    }
  544: 	    if ($exclude) {
  545: 	        delete($classlist->{$student});
  546: 	    }
  547: 	}
  548: 	$section = ($section ne '' ? $section : 'none');
  549: 	if (&canview($section)) {
  550: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  551: 		$sections{$section}++;
  552: 		if ($classlist->{$student}) {
  553: 		    $fullnames{$student}=$fullname;
  554: 		}
  555: 	    } else {
  556: 		delete($classlist->{$student});
  557: 	    }
  558: 	} else {
  559: 	    delete($classlist->{$student});
  560: 	}
  561:     }
  562:     my %seen = ();
  563:     my @sections = sort(keys(%sections));
  564:     return ($classlist,\@sections,\%fullnames);
  565: }
  566: 
  567: sub canmodify {
  568:     my ($sec)=@_;
  569:     if ($perm{'mgr'}) {
  570: 	if (!defined($perm{'mgr_section'})) {
  571: 	    # can modify whole class
  572: 	    return 1;
  573: 	} else {
  574: 	    if ($sec eq $perm{'mgr_section'}) {
  575: 		#can modify the requested section
  576: 		return 1;
  577: 	    } else {
  578: 		# can't modify the request section
  579: 		return 0;
  580: 	    }
  581: 	}
  582:     }
  583:     #can't modify
  584:     return 0;
  585: }
  586: 
  587: sub canview {
  588:     my ($sec)=@_;
  589:     if ($perm{'vgr'}) {
  590: 	if (!defined($perm{'vgr_section'})) {
  591: 	    # can modify whole class
  592: 	    return 1;
  593: 	} else {
  594: 	    if ($sec eq $perm{'vgr_section'}) {
  595: 		#can modify the requested section
  596: 		return 1;
  597: 	    } else {
  598: 		# can't modify the request section
  599: 		return 0;
  600: 	    }
  601: 	}
  602:     }
  603:     #can't modify
  604:     return 0;
  605: }
  606: 
  607: #--- Retrieve the grade status of a student for all the parts
  608: sub student_gradeStatus {
  609:     my ($symb,$udom,$uname,$partlist) = @_;
  610:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  611:     my %partstatus = ();
  612:     foreach (@$partlist) {
  613: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  614: 	$status              = 'nothing' if ($status eq '');
  615: 	$partstatus{$_}      = $status;
  616: 	my $subkey           = "resource.$_.submitted_by";
  617: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  618:     }
  619:     return %partstatus;
  620: }
  621: 
  622: # hidden form and javascript that calls the form
  623: # Use by verifyscript and viewgrades
  624: # Shows a student's view of problem and submission
  625: sub jscriptNform {
  626:     my ($symb) = @_;
  627:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  628:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  629: 	'    function viewOneStudent(user,domain) {'."\n".
  630: 	'	document.onestudent.student.value = user;'."\n".
  631: 	'	document.onestudent.userdom.value = domain;'."\n".
  632: 	'	document.onestudent.submit();'."\n".
  633: 	'    }'."\n".
  634: 	'</script>'."\n";
  635:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  636: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  637: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  638: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  639: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  640: 	'<input type="hidden" name="command" value="submission" />'."\n".
  641: 	'<input type="hidden" name="student" value="" />'."\n".
  642: 	'<input type="hidden" name="userdom" value="" />'."\n".
  643: 	'</form>'."\n";
  644:     return $jscript;
  645: }
  646: 
  647: 
  648: 
  649: # Given the score (as a number [0-1] and the weight) what is the final
  650: # point value? This function will round to the nearest tenth, third,
  651: # or quarter if one of those is within the tolerance of .00001.
  652: sub compute_points {
  653:     my ($score, $weight) = @_;
  654:     
  655:     my $tolerance = .00001;
  656:     my $points = $score * $weight;
  657: 
  658:     # Check for nearness to 1/x.
  659:     my $check_for_nearness = sub {
  660:         my ($factor) = @_;
  661:         my $num = ($points * $factor) + $tolerance;
  662:         my $floored_num = floor($num);
  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  664:             return $floored_num / $factor;
  665:         }
  666:         return $points;
  667:     };
  668: 
  669:     $points = $check_for_nearness->(10);
  670:     $points = $check_for_nearness->(3);
  671:     $points = $check_for_nearness->(4);
  672:     
  673:     return $points;
  674: }
  675: 
  676: #------------------ End of general use routines --------------------
  677: 
  678: #
  679: # Find most similar essay
  680: #
  681: 
  682: sub most_similar {
  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
  684: 
  685: # ignore spaces and punctuation
  686: 
  687:     $uessay=~s/\W+/ /gs;
  688: 
  689: # ignore empty submissions (occuring when only files are sent)
  690: 
  691:     unless ($uessay=~/\w+/) { return ''; }
  692: 
  693: # these will be returned. Do not care if not at least 50 percent similar
  694:     my $limit=0.6;
  695:     my $sname='';
  696:     my $sdom='';
  697:     my $scrsid='';
  698:     my $sessay='';
  699: # go through all essays ...
  700:     foreach my $tkey (keys(%$old_essays)) {
  701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  702: # ... except the same student
  703:         next if (($tname eq $uname) && ($tdom eq $udom));
  704: 	my $tessay=$old_essays->{$tkey};
  705: 	$tessay=~s/\W+/ /gs;
  706: # String similarity gives up if not even limit
  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  708: # Found one
  709: 	if ($tsimilar>$limit) {
  710: 	    $limit=$tsimilar;
  711: 	    $sname=$tname;
  712: 	    $sdom=$tdom;
  713: 	    $scrsid=$tcrsid;
  714: 	    $sessay=$old_essays->{$tkey};
  715: 	}
  716:     }
  717:     if ($limit>0.6) {
  718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  719:     } else {
  720:        return ('','','','',0);
  721:     }
  722: }
  723: 
  724: #-------------------------------------------------------------------
  725: 
  726: #------------------------------------ Receipt Verification Routines
  727: #
  728: #--- Check whether a receipt number is valid.---
  729: sub verifyreceipt {
  730:     my $request  = shift;
  731: 
  732:     my $courseid = $env{'request.course.id'};
  733:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  734: 	$env{'form.receipt'};
  735:     $receipt     =~ s/[^\-\d]//g;
  736:     my ($symb)   = &get_symb($request);
  737: 
  738:     my $title.=
  739: 	'<h3><span class="LC_info">'.
  740: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  741: 	'</span></h3>'."\n".
  742: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  743: 	'</h4>'."\n";
  744: 
  745:     my ($string,$contents,$matches) = ('','',0);
  746:     my (undef,undef,$fullname) = &getclasslist('all','0');
  747:     
  748:     my $receiptparts=0;
  749:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  750: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  751:     my $parts=['0'];
  752:     if ($receiptparts) { ($parts)=&response_type($symb); }
  753:     
  754:     my $header = 
  755: 	&Apache::loncommon::start_data_table().
  756: 	&Apache::loncommon::start_data_table_header_row().
  757: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  758: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  759: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  760:     if ($receiptparts) {
  761: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  762:     }
  763:     $header.=
  764: 	&Apache::loncommon::end_data_table_header_row();
  765: 
  766:     foreach (sort 
  767: 	     {
  768: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  769: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  770: 		 }
  771: 		 return $a cmp $b;
  772: 	     } (keys(%$fullname))) {
  773: 	my ($uname,$udom)=split(/\:/);
  774: 	foreach my $part (@$parts) {
  775: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  776: 		$contents.=
  777: 		    &Apache::loncommon::start_data_table_row().
  778: 		    '<td>&nbsp;'."\n".
  779: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  780: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  781: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  782: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  783: 		if ($receiptparts) {
  784: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  785: 		}
  786: 		$contents.= 
  787: 		    &Apache::loncommon::end_data_table_row()."\n";
  788: 		
  789: 		$matches++;
  790: 	    }
  791: 	}
  792:     }
  793:     if ($matches == 0) {
  794: 	$string = $title.&mt('No match found for the above receipt.');
  795:     } else {
  796: 	$string = &jscriptNform($symb).$title.
  797: 	    '<p>'.
  798: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  799: 	    '</p>'.
  800: 	    $header.
  801: 	    $contents.
  802: 	    &Apache::loncommon::end_data_table()."\n";
  803:     }
  804:     return $string.&show_grading_menu_form($symb);
  805: }
  806: 
  807: #--- This is called by a number of programs.
  808: #--- Called from the Grading Menu - View/Grade an individual student
  809: #--- Also called directly when one clicks on the subm button 
  810: #    on the problem page.
  811: sub listStudents {
  812:     my ($request) = shift;
  813: 
  814:     my ($symb) = &get_symb($request);
  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  819:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  820:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  821:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  822: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  823: 
  824:     my $result='<h3><span class="LC_info">&nbsp;'.
  825: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  826: 	.'</span></h3>';
  827: 
  828:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  829: 
  830:     my %lt = ( 'multiple' =>
  831: 	       "Please select a student or group of students before clicking on the Next button.",
  832: 	       'single'   =>
  833: 	       "Please select the student before clicking on the Next button.",
  834: 	       );
  835:     %lt = &Apache::lonlocal::texthash(%lt);
  836:     $request->print(<<LISTJAVASCRIPT);
  837: <script type="text/javascript" language="javascript">
  838:     function checkSelect(checkBox) {
  839: 	var ctr=0;
  840: 	var sense="";
  841: 	if (checkBox.length > 1) {
  842: 	    for (var i=0; i<checkBox.length; i++) {
  843: 		if (checkBox[i].checked) {
  844: 		    ctr++;
  845: 		}
  846: 	    }
  847: 	    sense = '$lt{'multiple'}';
  848: 	} else {
  849: 	    if (checkBox.checked) {
  850: 		ctr = 1;
  851: 	    }
  852: 	    sense = '$lt{'single'}';
  853: 	}
  854: 	if (ctr == 0) {
  855: 	    alert(sense);
  856: 	    return false;
  857: 	}
  858: 	document.gradesub.submit();
  859:     }
  860: 
  861:     function reLoadList(formname) {
  862: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  863: 	formname.command.value = 'submission';
  864: 	formname.submit();
  865:     }
  866: </script>
  867: LISTJAVASCRIPT
  868: 
  869:     &commonJSfunctions($request);
  870:     $request->print($result);
  871: 
  872:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  873:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  874:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  875: 	"\n".$table;
  876: 	
  877:     $gradeTable .= 
  878: 	'&nbsp;'.
  879: 	&mt('<b>View Problem Text: </b>[_1]',
  880: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  881: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  882: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
  883:     $gradeTable .= 
  884: 	'&nbsp;'.
  885: 	&mt('<b>View Answer: </b>[_1]',
  886: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  887: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  888: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
  889: 
  890:     my $submission_options;
  891:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  892: 	$submission_options.=
  893: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  894:     }
  895:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  896:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  897:     $env{'form.Status'} = $saveStatus;
  898:     $submission_options.=
  899: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  900: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  901: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  902: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  903:     $gradeTable .= 
  904: 	'&nbsp;'.
  905: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
  906: 
  907:     $gradeTable .= 
  908:         '&nbsp;'.
  909: 	&mt('<b>Grading Increments:</b> [_1]',
  910: 	    '<select name="increment">'.
  911: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  912: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  913: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  914: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  915: 	    '</select>');
  916:     
  917:     $gradeTable .= 
  918:         &build_section_inputs().
  919: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  920: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  921: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  922: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  923: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  926: 
  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  928: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  929:     } else {
  930: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  931: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  932:     }
  933: 
  934:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  935: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
  936: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  937: 
  938: # checkall buttons
  939:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  940:     $gradeTable.='<input type="button" '."\n".
  941: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  942: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
  943:     $gradeTable.=&check_buttons();
  944:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  945:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  946:     $gradeTable.= &Apache::loncommon::start_data_table().
  947: 	&Apache::loncommon::start_data_table_header_row();
  948:     my $loop = 0;
  949:     while ($loop < 2) {
  950: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  951: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  952: 	if ($env{'form.showgrading'} eq 'yes' 
  953: 	    && $submitonly ne 'queued'
  954: 	    && $submitonly ne 'all') {
  955: 	    foreach my $part (sort(@$partlist)) {
  956: 		my $display_part=
  957: 		    &get_display_part((split(/_/,$part))[0],$symb);
  958: 		$gradeTable.=
  959: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  960: 	    }
  961: 	} elsif ($submitonly eq 'queued') {
  962: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  963: 	}
  964: 	$loop++;
  965: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  966:     }
  967:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  968: 
  969:     my $ctr = 0;
  970:     foreach my $student (sort 
  971: 			 {
  972: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  973: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  974: 			     }
  975: 			     return $a cmp $b;
  976: 			 }
  977: 			 (keys(%$fullname))) {
  978: 	my ($uname,$udom) = split(/:/,$student);
  979: 
  980: 	my %status = ();
  981: 
  982: 	if ($submitonly eq 'queued') {
  983: 	    my %queue_status = 
  984: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  985: 							$udom,$uname);
  986: 	    next if (!defined($queue_status{'gradingqueue'}));
  987: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  988: 	}
  989: 
  990: 	if ($env{'form.showgrading'} eq 'yes' 
  991: 	    && $submitonly ne 'queued'
  992: 	    && $submitonly ne 'all') {
  993: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  994: 	    my $submitted = 0;
  995: 	    my $graded = 0;
  996: 	    my $incorrect = 0;
  997: 	    foreach (keys(%status)) {
  998: 		$submitted = 1 if ($status{$_} ne 'nothing');
  999: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1000: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1001: 		
 1002: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1003: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1004: 		    $submitted = 0;
 1005: 		    my ($part)=split(/\./,$partid);
 1006: 		    $gradeTable.='<input type="hidden" name="'.
 1007: 			$student.':'.$part.':submitted_by" value="'.
 1008: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1009: 		}
 1010: 	    }
 1011: 	    
 1012: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1013: 				     $submitonly eq 'incorrect' ||
 1014: 				     $submitonly eq 'graded'));
 1015: 	    next if (!$graded && ($submitonly eq 'graded'));
 1016: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1017: 	}
 1018: 
 1019: 	$ctr++;
 1020: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1021:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1022: 	if ( $perm{'vgr'} eq 'F' ) {
 1023: 	    if ($ctr%2 ==1) {
 1024: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1025: 	    }
 1026: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1027:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1028:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1029: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1030: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1031: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1032: 
 1033: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1034: 		foreach (sort(keys(%status))) {
 1035: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1036: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1037: 		}
 1038: 	    }
 1039: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1040: 	    if ($ctr%2 ==0) {
 1041: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1042: 	    }
 1043: 	}
 1044:     }
 1045:     if ($ctr%2 ==1) {
 1046: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1047: 	    if ($env{'form.showgrading'} eq 'yes' 
 1048: 		&& $submitonly ne 'queued'
 1049: 		&& $submitonly ne 'all') {
 1050: 		foreach (@$partlist) {
 1051: 		    $gradeTable.='<td>&nbsp;</td>';
 1052: 		}
 1053: 	    } elsif ($submitonly eq 'queued') {
 1054: 		$gradeTable.='<td>&nbsp;</td>';
 1055: 	    }
 1056: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1057:     }
 1058: 
 1059:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1060: 	'<input type="button" '.
 1061: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1062: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1063:     if ($ctr == 0) {
 1064: 	my $num_students=(scalar(keys(%$fullname)));
 1065: 	if ($num_students eq 0) {
 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1067: 	} else {
 1068: 	    my $submissions='submissions';
 1069: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1070: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1071: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1072: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1073: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1074: 		    $num_students).
 1075: 		'</span><br />';
 1076: 	}
 1077:     } elsif ($ctr == 1) {
 1078: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1079:     }
 1080:     $gradeTable.=&show_grading_menu_form($symb);
 1081:     $request->print($gradeTable);
 1082:     return '';
 1083: }
 1084: 
 1085: #---- Called from the listStudents routine
 1086: 
 1087: sub check_script {
 1088:     my ($form, $type)=@_;
 1089:     my $chkallscript='<script type="text/javascript">
 1090:     function checkall() {
 1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1092:             ele = document.forms.'.$form.'.elements[i];
 1093:             if (ele.name == "'.$type.'") {
 1094:             document.forms.'.$form.'.elements[i].checked=true;
 1095:                                        }
 1096:         }
 1097:     }
 1098: 
 1099:     function checksec() {
 1100:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1101:             ele = document.forms.'.$form.'.elements[i];
 1102:            string = document.forms.'.$form.'.chksec.value;
 1103:            if
 1104:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1105:               document.forms.'.$form.'.elements[i].checked=true;
 1106:             }
 1107:         }
 1108:     }
 1109: 
 1110: 
 1111:     function uncheckall() {
 1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1113:             ele = document.forms.'.$form.'.elements[i];
 1114:             if (ele.name == "'.$type.'") {
 1115:             document.forms.'.$form.'.elements[i].checked=false;
 1116:                                        }
 1117:         }
 1118:     }
 1119: 
 1120: </script>'."\n";
 1121:     return $chkallscript;
 1122: }
 1123: 
 1124: sub check_buttons {
 1125:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1126:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1127:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1128:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1129:     return $buttons;
 1130: }
 1131: 
 1132: #     Displays the submissions for one student or a group of students
 1133: sub processGroup {
 1134:     my ($request)  = shift;
 1135:     my $ctr        = 0;
 1136:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1137:     my $total      = scalar(@stuchecked)-1;
 1138: 
 1139:     foreach my $student (@stuchecked) {
 1140: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1141: 	$env{'form.student'}        = $uname;
 1142: 	$env{'form.userdom'}        = $udom;
 1143: 	$env{'form.fullname'}       = $fullname;
 1144: 	&submission($request,$ctr,$total);
 1145: 	$ctr++;
 1146:     }
 1147:     return '';
 1148: }
 1149: 
 1150: #------------------------------------------------------------------------------------
 1151: #
 1152: #-------------------------- Next few routines handles grading by student, essentially
 1153: #                           handles essay response type problem/part
 1154: #
 1155: #--- Javascript to handle the submission page functionality ---
 1156: sub sub_page_js {
 1157:     my $request = shift;
 1158:     $request->print(<<SUBJAVASCRIPT);
 1159: <script type="text/javascript" language="javascript">
 1160:     function updateRadio(formname,id,weight) {
 1161: 	var gradeBox = formname["GD_BOX"+id];
 1162: 	var radioButton = formname["RADVAL"+id];
 1163: 	var oldpts = formname["oldpts"+id].value;
 1164: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1165: 	gradeBox.value = pts;
 1166: 	var resetbox = false;
 1167: 	if (isNaN(pts) || pts < 0) {
 1168: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1169: 	    for (var i=0; i<radioButton.length; i++) {
 1170: 		if (radioButton[i].checked) {
 1171: 		    gradeBox.value = i;
 1172: 		    resetbox = true;
 1173: 		}
 1174: 	    }
 1175: 	    if (!resetbox) {
 1176: 		formtextbox.value = "";
 1177: 	    }
 1178: 	    return;
 1179: 	}
 1180: 
 1181: 	if (pts > weight) {
 1182: 	    var resp = confirm("You entered a value ("+pts+
 1183: 			       ") greater than the weight for the part. Accept?");
 1184: 	    if (resp == false) {
 1185: 		gradeBox.value = oldpts;
 1186: 		return;
 1187: 	    }
 1188: 	}
 1189: 
 1190: 	for (var i=0; i<radioButton.length; i++) {
 1191: 	    radioButton[i].checked=false;
 1192: 	    if (pts == i && pts != "") {
 1193: 		radioButton[i].checked=true;
 1194: 	    }
 1195: 	}
 1196: 	updateSelect(formname,id);
 1197: 	formname["stores"+id].value = "0";
 1198:     }
 1199: 
 1200:     function writeBox(formname,id,pts) {
 1201: 	var gradeBox = formname["GD_BOX"+id];
 1202: 	if (checkSolved(formname,id) == 'update') {
 1203: 	    gradeBox.value = pts;
 1204: 	} else {
 1205: 	    var oldpts = formname["oldpts"+id].value;
 1206: 	    gradeBox.value = oldpts;
 1207: 	    var radioButton = formname["RADVAL"+id];
 1208: 	    for (var i=0; i<radioButton.length; i++) {
 1209: 		radioButton[i].checked=false;
 1210: 		if (i == oldpts) {
 1211: 		    radioButton[i].checked=true;
 1212: 		}
 1213: 	    }
 1214: 	}
 1215: 	formname["stores"+id].value = "0";
 1216: 	updateSelect(formname,id);
 1217: 	return;
 1218:     }
 1219: 
 1220:     function clearRadBox(formname,id) {
 1221: 	if (checkSolved(formname,id) == 'noupdate') {
 1222: 	    updateSelect(formname,id);
 1223: 	    return;
 1224: 	}
 1225: 	gradeSelect = formname["GD_SEL"+id];
 1226: 	for (var i=0; i<gradeSelect.length; i++) {
 1227: 	    if (gradeSelect[i].selected) {
 1228: 		var selectx=i;
 1229: 	    }
 1230: 	}
 1231: 	var stores = formname["stores"+id];
 1232: 	if (selectx == stores.value) { return };
 1233: 	var gradeBox = formname["GD_BOX"+id];
 1234: 	gradeBox.value = "";
 1235: 	var radioButton = formname["RADVAL"+id];
 1236: 	for (var i=0; i<radioButton.length; i++) {
 1237: 	    radioButton[i].checked=false;
 1238: 	}
 1239: 	stores.value = selectx;
 1240:     }
 1241: 
 1242:     function checkSolved(formname,id) {
 1243: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1244: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1245: 	    if (!reply) {return "noupdate";}
 1246: 	    formname.overRideScore.value = 'yes';
 1247: 	}
 1248: 	return "update";
 1249:     }
 1250: 
 1251:     function updateSelect(formname,id) {
 1252: 	formname["GD_SEL"+id][0].selected = true;
 1253: 	return;
 1254:     }
 1255: 
 1256: //=========== Check that a point is assigned for all the parts  ============
 1257:     function checksubmit(formname,val,total,parttot) {
 1258: 	formname.gradeOpt.value = val;
 1259: 	if (val == "Save & Next") {
 1260: 	    for (i=0;i<=total;i++) {
 1261: 		for (j=0;j<parttot;j++) {
 1262: 		    var partid = formname["partid"+i+"_"+j].value;
 1263: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1264: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1265: 			if (points == "") {
 1266: 			    var name = formname["name"+i].value;
 1267: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1268: 			    var resp = confirm("You did not assign a score for "+studentID+
 1269: 					       ", part "+partid+". Continue?");
 1270: 			    if (resp == false) {
 1271: 				formname["GD_BOX"+i+"_"+partid].focus();
 1272: 				return false;
 1273: 			    }
 1274: 			}
 1275: 		    }
 1276: 		    
 1277: 		}
 1278: 	    }
 1279: 	    
 1280: 	}
 1281: 	if (val == "Grade Student") {
 1282: 	    formname.showgrading.value = "yes";
 1283: 	    if (formname.Status.value == "") {
 1284: 		formname.Status.value = "Active";
 1285: 	    }
 1286: 	    formname.studentNo.value = total;
 1287: 	}
 1288: 	formname.submit();
 1289:     }
 1290: 
 1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1292:     function checkSubmitPage(formname,total) {
 1293: 	noscore = new Array(100);
 1294: 	var ptr = 0;
 1295: 	for (i=1;i<total;i++) {
 1296: 	    var partid = formname["q_"+i].value;
 1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1299: 		var status = formname["solved"+i+"_"+partid].value;
 1300: 		if (points == "" && status != "correct_by_student") {
 1301: 		    noscore[ptr] = i;
 1302: 		    ptr++;
 1303: 		}
 1304: 	    }
 1305: 	}
 1306: 	if (ptr != 0) {
 1307: 	    var sense = ptr == 1 ? ": " : "s: ";
 1308: 	    var prolist = "";
 1309: 	    if (ptr == 1) {
 1310: 		prolist = noscore[0];
 1311: 	    } else {
 1312: 		var i = 0;
 1313: 		while (i < ptr-1) {
 1314: 		    prolist += noscore[i]+", ";
 1315: 		    i++;
 1316: 		}
 1317: 		prolist += "and "+noscore[i];
 1318: 	    }
 1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1320: 	    if (resp == false) {
 1321: 		return false;
 1322: 	    }
 1323: 	}
 1324: 
 1325: 	formname.submit();
 1326:     }
 1327: </script>
 1328: SUBJAVASCRIPT
 1329: }
 1330: 
 1331: #--- javascript for essay type problem --
 1332: sub sub_page_kw_js {
 1333:     my $request = shift;
 1334:     my $iconpath = $request->dir_config('lonIconsURL');
 1335:     &commonJSfunctions($request);
 1336: 
 1337:     my $inner_js_msg_central=<<INNERJS;
 1338:     <script text="text/javascript">
 1339:     function checkInput() {
 1340:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1341:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1342:       var usrctr = document.msgcenter.usrctr.value;
 1343:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1344:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1345: 
 1346:       var msgchk = "";
 1347:       if (document.msgcenter.subchk.checked) {
 1348:          msgchk = "msgsub,";
 1349:       }
 1350:       var includemsg = 0;
 1351:       for (var i=1; i<=nmsg; i++) {
 1352:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1353:           var frmmsg = document.msgcenter["msg"+i];
 1354:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1355:           var showflg = opener.document.SCORE["shownOnce"+i];
 1356:           showflg.value = "1";
 1357:           var chkbox = document.msgcenter["msgn"+i];
 1358:           if (chkbox.checked) {
 1359:              msgchk += "savemsg"+i+",";
 1360:              includemsg = 1;
 1361:           }
 1362:       }
 1363:       if (document.msgcenter.newmsgchk.checked) {
 1364:          msgchk += "newmsg"+usrctr;
 1365:          includemsg = 1;
 1366:       }
 1367:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1368:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1369:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1370:       includemsg.value = msgchk;
 1371: 
 1372:       self.close()
 1373: 
 1374:     }
 1375:     </script>
 1376: INNERJS
 1377: 
 1378:     my $inner_js_highlight_central=<<INNERJS;
 1379:  <script type="text/javascript">
 1380:     function updateChoice(flag) {
 1381:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1382:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1383:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1384:       opener.document.SCORE.refresh.value = "on";
 1385:       if (opener.document.SCORE.keywords.value!=""){
 1386:          opener.document.SCORE.submit();
 1387:       }
 1388:       self.close()
 1389:     }
 1390: </script>
 1391: INNERJS
 1392: 
 1393:     my $start_page_msg_central = 
 1394:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1395: 				       {'js_ready'  => 1,
 1396: 					'only_body' => 1,
 1397: 					'bgcolor'   =>'#FFFFFF',});
 1398:     my $end_page_msg_central = 
 1399: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1400: 
 1401: 
 1402:     my $start_page_highlight_central = 
 1403:         &Apache::loncommon::start_page('Highlight Central',
 1404: 				       $inner_js_highlight_central,
 1405: 				       {'js_ready'  => 1,
 1406: 					'only_body' => 1,
 1407: 					'bgcolor'   =>'#FFFFFF',});
 1408:     my $end_page_highlight_central = 
 1409: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1410: 
 1411:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1412:     $docopen=~s/^document\.//;
 1413:     $request->print(<<SUBJAVASCRIPT);
 1414: <script type="text/javascript" language="javascript">
 1415: 
 1416: //===================== Show list of keywords ====================
 1417:   function keywords(formname) {
 1418:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1419:     if (nret==null) return;
 1420:     formname.keywords.value = nret;
 1421: 
 1422:     if (formname.keywords.value != "") {
 1423: 	formname.refresh.value = "on";
 1424: 	formname.submit();
 1425:     }
 1426:     return;
 1427:   }
 1428: 
 1429: //===================== Script to view submitted by ==================
 1430:   function viewSubmitter(submitter) {
 1431:     document.SCORE.refresh.value = "on";
 1432:     document.SCORE.NCT.value = "1";
 1433:     document.SCORE.unamedom0.value = submitter;
 1434:     document.SCORE.submit();
 1435:     return;
 1436:   }
 1437: 
 1438: //===================== Script to add keyword(s) ==================
 1439:   function getSel() {
 1440:     if (document.getSelection) txt = document.getSelection();
 1441:     else if (document.selection) txt = document.selection.createRange().text;
 1442:     else return;
 1443:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1444:     if (cleantxt=="") {
 1445: 	alert("Please select a word or group of words from document and then click this link.");
 1446: 	return;
 1447:     }
 1448:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1449:     if (nret==null) return;
 1450:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1451:     if (document.SCORE.keywords.value != "") {
 1452: 	document.SCORE.refresh.value = "on";
 1453: 	document.SCORE.submit();
 1454:     }
 1455:     return;
 1456:   }
 1457: 
 1458: //====================== Script for composing message ==============
 1459:    // preload images
 1460:    img1 = new Image();
 1461:    img1.src = "$iconpath/mailbkgrd.gif";
 1462:    img2 = new Image();
 1463:    img2.src = "$iconpath/mailto.gif";
 1464: 
 1465:   function msgCenter(msgform,usrctr,fullname) {
 1466:     var Nmsg  = msgform.savemsgN.value;
 1467:     savedMsgHeader(Nmsg,usrctr,fullname);
 1468:     var subject = msgform.msgsub.value;
 1469:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1470:     re = /msgsub/;
 1471:     var shwsel = "";
 1472:     if (re.test(msgchk)) { shwsel = "checked" }
 1473:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1474:     displaySubject(checkEntities(subject),shwsel);
 1475:     for (var i=1; i<=Nmsg; i++) {
 1476: 	var testmsg = "savemsg"+i+",";
 1477: 	re = new RegExp(testmsg,"g");
 1478: 	shwsel = "";
 1479: 	if (re.test(msgchk)) { shwsel = "checked" }
 1480: 	var message = document.SCORE["savemsg"+i].value;
 1481: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1482: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1483: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1484:     }
 1485:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1486:     shwsel = "";
 1487:     re = /newmsg/;
 1488:     if (re.test(msgchk)) { shwsel = "checked" }
 1489:     newMsg(newmsg,shwsel);
 1490:     msgTail(); 
 1491:     return;
 1492:   }
 1493: 
 1494:   function checkEntities(strx) {
 1495:     if (strx.length == 0) return strx;
 1496:     var orgStr = ["&", "<", ">", '"']; 
 1497:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1498:     var counter = 0;
 1499:     while (counter < 4) {
 1500: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1501: 	counter++;
 1502:     }
 1503:     return strx;
 1504:   }
 1505: 
 1506:   function strReplace(strx, orgStr, newStr) {
 1507:     return strx.split(orgStr).join(newStr);
 1508:   }
 1509: 
 1510:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1511:     var height = 70*Nmsg+250;
 1512:     var scrollbar = "no";
 1513:     if (height > 600) {
 1514: 	height = 600;
 1515: 	scrollbar = "yes";
 1516:     }
 1517:     var xpos = (screen.width-600)/2;
 1518:     xpos = (xpos < 0) ? '0' : xpos;
 1519:     var ypos = (screen.height-height)/2-30;
 1520:     ypos = (ypos < 0) ? '0' : ypos;
 1521: 
 1522:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1523:     pWin.focus();
 1524:     pDoc = pWin.document;
 1525:     pDoc.$docopen;
 1526:     pDoc.write('$start_page_msg_central');
 1527: 
 1528:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1529:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1530:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1531: 
 1532:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1533:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1534:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1535: }
 1536:     function displaySubject(msg,shwsel) {
 1537:     pDoc = pWin.document;
 1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1539:     pDoc.write("<td>Subject<\\/td>");
 1540:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1541:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1542: }
 1543: 
 1544:   function displaySavedMsg(ctr,msg,shwsel) {
 1545:     pDoc = pWin.document;
 1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1547:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1548:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1549:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1550: }
 1551: 
 1552:   function newMsg(newmsg,shwsel) {
 1553:     pDoc = pWin.document;
 1554:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1555:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1556:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1557:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1558: }
 1559: 
 1560:   function msgTail() {
 1561:     pDoc = pWin.document;
 1562:     pDoc.write("<\\/table>");
 1563:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1564:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1565:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1566:     pDoc.write("<\\/form>");
 1567:     pDoc.write('$end_page_msg_central');
 1568:     pDoc.close();
 1569: }
 1570: 
 1571: //====================== Script for keyword highlight options ==============
 1572:   function kwhighlight() {
 1573:     var kwclr    = document.SCORE.kwclr.value;
 1574:     var kwsize   = document.SCORE.kwsize.value;
 1575:     var kwstyle  = document.SCORE.kwstyle.value;
 1576:     var redsel = "";
 1577:     var grnsel = "";
 1578:     var blusel = "";
 1579:     if (kwclr=="red")   {var redsel="checked"};
 1580:     if (kwclr=="green") {var grnsel="checked"};
 1581:     if (kwclr=="blue")  {var blusel="checked"};
 1582:     var sznsel = "";
 1583:     var sz1sel = "";
 1584:     var sz2sel = "";
 1585:     if (kwsize=="0")  {var sznsel="checked"};
 1586:     if (kwsize=="+1") {var sz1sel="checked"};
 1587:     if (kwsize=="+2") {var sz2sel="checked"};
 1588:     var synsel = "";
 1589:     var syisel = "";
 1590:     var sybsel = "";
 1591:     if (kwstyle=="")    {var synsel="checked"};
 1592:     if (kwstyle=="<i>") {var syisel="checked"};
 1593:     if (kwstyle=="<b>") {var sybsel="checked"};
 1594:     highlightCentral();
 1595:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1596:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1597:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1598:     highlightend();
 1599:     return;
 1600:   }
 1601: 
 1602:   function highlightCentral() {
 1603: //    if (window.hwdWin) window.hwdWin.close();
 1604:     var xpos = (screen.width-400)/2;
 1605:     xpos = (xpos < 0) ? '0' : xpos;
 1606:     var ypos = (screen.height-330)/2-30;
 1607:     ypos = (ypos < 0) ? '0' : ypos;
 1608: 
 1609:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1610:     hwdWin.focus();
 1611:     var hDoc = hwdWin.document;
 1612:     hDoc.$docopen;
 1613:     hDoc.write('$start_page_highlight_central');
 1614:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1615:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1616: 
 1617:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1618:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1619:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1620:   }
 1621: 
 1622:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1623:     var hDoc = hwdWin.document;
 1624:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1625:     hDoc.write("<td align=\\"left\\">");
 1626:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1627:     hDoc.write("<td align=\\"left\\">");
 1628:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1629:     hDoc.write("<td align=\\"left\\">");
 1630:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1631:     hDoc.write("<\\/tr>");
 1632:   }
 1633: 
 1634:   function highlightend() { 
 1635:     var hDoc = hwdWin.document;
 1636:     hDoc.write("<\\/table>");
 1637:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1638:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1639:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1640:     hDoc.write("<\\/form>");
 1641:     hDoc.write('$end_page_highlight_central');
 1642:     hDoc.close();
 1643:   }
 1644: 
 1645: </script>
 1646: SUBJAVASCRIPT
 1647: }
 1648: 
 1649: sub get_increment {
 1650:     my $increment = $env{'form.increment'};
 1651:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1652:         $increment != .1) {
 1653:         $increment = 1;
 1654:     }
 1655:     return $increment;
 1656: }
 1657: 
 1658: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1659: sub gradeBox {
 1660:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1661:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1662: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1663:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1664:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1665:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1666:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1667:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1668: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1669:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1670:     my $display_part= &get_display_part($partid,$symb);
 1671:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1672: 				       [$partid]);
 1673:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1674:     if ($last_resets{$partid}) {
 1675:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1676:     }
 1677:     $result.='<table border="0"><tr>';
 1678:     my $ctr = 0;
 1679:     my $thisweight = 0;
 1680:     my $increment = &get_increment();
 1681: 
 1682:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1683:     while ($thisweight<=$wgt) {
 1684: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1685: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1686: 	    $thisweight.')" value="'.$thisweight.'" '.
 1687: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1688: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1689:         $thisweight += $increment;
 1690: 	$ctr++;
 1691:     }
 1692:     $radio.='</tr></table>';
 1693: 
 1694:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1695: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1696: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1697: 	$wgt.')" /></td>'."\n";
 1698:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1699: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1700: 	' </td><td>'."\n";
 1701:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1702: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1703:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1704: 	$line.='<option></option>'.
 1705: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1706:     } else {
 1707: 	$line.='<option selected="selected"></option>'.
 1708: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1709:     }
 1710:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1711: 
 1712: 
 1713:     $result .= 
 1714: 	&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1715: 
 1716:     
 1717:     $result.='</tr></table>'."\n";
 1718:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1719: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1720: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1721: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1722:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1723:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1724:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1725:         $aggtries.'" />'."\n";
 1726:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1727:     return $result;
 1728: }
 1729: 
 1730: sub handback_box {
 1731:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1732:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1733:     my (@respids);
 1734:      my @part_response_id = &flatten_responseType($responseType);
 1735:     foreach my $part_response_id (@part_response_id) {
 1736:     	my ($part,$resp) = @{ $part_response_id };
 1737:         if ($part eq $partid) {
 1738:             push(@respids,$resp);
 1739:         }
 1740:     }
 1741:     my $result;
 1742:     foreach my $respid (@respids) {
 1743: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1744: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1745: 	next if (!@$files);
 1746: 	my $file_counter = 1;
 1747: 	foreach my $file (@$files) {
 1748: 	    if ($file =~ /\/portfolio\//) {
 1749:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1750:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1751:     	        $file_disp = "$name.$ext";
 1752:     	        $file = $file_path.$file_disp;
 1753:     	        $result.=&mt('Return commented version of [_1] to student.',
 1754:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1755:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1756:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1757:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1758:     	        $file_counter++;
 1759: 	    }
 1760: 	}
 1761:     }
 1762:     return $result;    
 1763: }
 1764: 
 1765: sub show_problem {
 1766:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1767:     my $rendered;
 1768:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1769:     &Apache::lonxml::remember_problem_counter();
 1770:     if ($mode eq 'both' or $mode eq 'text') {
 1771: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1772: 						       $env{'request.course.id'},
 1773: 						       undef,\%form);
 1774:     }
 1775:     if ($removeform) {
 1776: 	$rendered=~s|<form(.*?)>||g;
 1777: 	$rendered=~s|</form>||g;
 1778: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1779:     }
 1780:     my $companswer;
 1781:     if ($mode eq 'both' or $mode eq 'answer') {
 1782: 	&Apache::lonxml::restore_problem_counter();
 1783: 	$companswer=
 1784: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1785: 						    $env{'request.course.id'},
 1786: 						    %form);
 1787:     }
 1788:     if ($removeform) {
 1789: 	$companswer=~s|<form(.*?)>||g;
 1790: 	$companswer=~s|</form>||g;
 1791: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1792:     }
 1793:     $rendered=
 1794: 	'<div class="LC_grade_show_problem_header">'.
 1795: 	&mt('View of the problem').
 1796: 	'</div><div class="LC_grade_show_problem_problem">'.
 1797: 	$rendered.
 1798: 	'</div>';
 1799:     $companswer=
 1800: 	'<div class="LC_grade_show_problem_header">'.
 1801: 	&mt('Correct answer').
 1802: 	'</div><div class="LC_grade_show_problem_problem">'.
 1803: 	$companswer.
 1804: 	'</div>';
 1805:     my $result;
 1806:     if ($mode eq 'both') {
 1807: 	$result=$rendered.$companswer;
 1808:     } elsif ($mode eq 'text') {
 1809: 	$result=$rendered;
 1810:     } elsif ($mode eq 'answer') {
 1811: 	$result=$companswer;
 1812:     }
 1813:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1814:     return $result;
 1815: }
 1816: 
 1817: sub files_exist {
 1818:     my ($r, $symb) = @_;
 1819:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1820: 
 1821:     foreach my $student (@students) {
 1822:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1823:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1824: 					      $udom,$uname);
 1825:         my ($string,$timestamp)= &get_last_submission(\%record);
 1826:         foreach my $submission (@$string) {
 1827:             my ($partid,$respid) =
 1828: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1829:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1830: 					   \%record);
 1831:             return 1 if (@$files);
 1832:         }
 1833:     }
 1834:     return 0;
 1835: }
 1836: 
 1837: sub download_all_link {
 1838:     my ($r,$symb) = @_;
 1839:     my $all_students = 
 1840: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1841: 
 1842:     my $parts =
 1843: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1844: 
 1845:     my $identifier = &Apache::loncommon::get_cgi_id();
 1846:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1847:                              'cgi.'.$identifier.'.symb' => $symb,
 1848:                              'cgi.'.$identifier.'.parts' => $parts,});
 1849:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1850: 	      &mt('Download All Submitted Documents').'</a>');
 1851:     return
 1852: }
 1853: 
 1854: sub build_section_inputs {
 1855:     my $section_inputs;
 1856:     if ($env{'form.section'} eq '') {
 1857:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1858:     } else {
 1859:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1860:         foreach my $section (@sections) {
 1861:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1862:         }
 1863:     }
 1864:     return $section_inputs;
 1865: }
 1866: 
 1867: # --------------------------- show submissions of a student, option to grade 
 1868: sub submission {
 1869:     my ($request,$counter,$total) = @_;
 1870:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1871:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1872:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1873:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1874:     my $symb = &get_symb($request); 
 1875:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1876: 
 1877:     if (!&canview($usec)) {
 1878: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1879: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1880: 			$env{'request.course.id'}.')</span>');
 1881: 	$request->print(&show_grading_menu_form($symb));
 1882: 	return;
 1883:     }
 1884: 
 1885:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1886:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1887:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1888:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1889:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1890: 	'" src="'.$request->dir_config('lonIconsURL').
 1891: 	'/check.gif" height="16" border="0" />';
 1892: 
 1893:     my %old_essays;
 1894:     # header info
 1895:     if ($counter == 0) {
 1896: 	&sub_page_js($request);
 1897: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1898: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1899: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1900: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1901: 	    &download_all_link($request, $symb);
 1902: 	}
 1903: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1904: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1905: 
 1906: 	# option to display problem, only once else it cause problems 
 1907:         # with the form later since the problem has a form.
 1908: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1909: 	    my $mode;
 1910: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1911: 		$mode='both';
 1912: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1913: 		$mode='text';
 1914: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1915: 		$mode='answer';
 1916: 	    }
 1917: 	    &Apache::lonxml::clear_problem_counter();
 1918: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1919: 	}
 1920: 
 1921: 	# kwclr is the only variable that is guaranteed to be non blank 
 1922:         # if this subroutine has been called once.
 1923: 	my %keyhash = ();
 1924: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1925: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1926: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1927: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1928: 
 1929: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1930: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1931: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1932: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1933: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1934: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1935: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1936: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1937: 	}
 1938: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1939: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1940: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1941: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1942: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1943: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1944: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1945: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1946: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1947: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1948: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1949: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1950: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1951: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1952: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1953: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1954: 			&build_section_inputs().
 1955: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1956: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1957: 			'<input type="hidden" name="NCT"'.
 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1959: 	if ($env{'form.handgrade'} eq 'yes') {
 1960: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1961: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1963: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1964: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1965: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1966: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1967: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1968: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1969: 	    }
 1970: 	}
 1971: 	
 1972: 	my ($cts,$prnmsg) = (1,'');
 1973: 	while ($cts <= $env{'form.savemsgN'}) {
 1974: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1975: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1976: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1977: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1978: 		'" />'."\n".
 1979: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1980: 	    $cts++;
 1981: 	}
 1982: 	$request->print($prnmsg);
 1983: 
 1984: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1985: #
 1986: # Print out the keyword options line
 1987: #
 1988: 	    $request->print(<<KEYWORDS);
 1989: &nbsp;<b>Keyword Options:</b>&nbsp;
 1990: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1991: <a href="#" onMouseDown="javascript:getSel(); return false"
 1992:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1993: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1994: KEYWORDS
 1995: #
 1996: # Load the other essays for similarity check
 1997: #
 1998:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1999: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2000: 	    $apath=&escape($apath);
 2001: 	    $apath=~s/\W/\_/gs;
 2002: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2003:         }
 2004:     }
 2005: 
 2006: # This is where output for one specific student would start
 2007:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2008:     $request->print("\n\n".
 2009:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2010: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2011: 		    '<div class="LC_grade_show_user_body">'."\n");
 2012: 
 2013:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2014: 	my $mode;
 2015: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2016: 	    $mode='both';
 2017: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2018: 	    $mode='text';
 2019: 	} elsif ($env{'form.vAns'} eq 'all') {
 2020: 	    $mode='answer';
 2021: 	}
 2022: 	&Apache::lonxml::clear_problem_counter();
 2023: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2024:     }
 2025: 
 2026:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2027:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2028: 
 2029:     # Display student info
 2030:     $request->print(($counter == 0 ? '' : '<br />'));
 2031:     my $result='<div class="LC_grade_submissions">';
 2032:     
 2033:     $result.='<div class="LC_grade_submissions_header">';
 2034:     $result.= &mt('Submissions');
 2035:     $result.='<input type="hidden" name="name'.$counter.
 2036: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2037:     if ($env{'form.handgrade'} eq 'no') {
 2038: 	$result.='<span class="LC_grade_check_note">'.
 2039: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2040: 
 2041:     }
 2042: 
 2043: 
 2044: 
 2045:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2046:     my $fullname;
 2047:     my $col_fullnames = [];
 2048:     if ($env{'form.handgrade'} eq 'yes') {
 2049: 	(my $sub_result,$fullname,$col_fullnames)=
 2050: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2051: 				 $counter);
 2052: 	$result.=$sub_result;
 2053:     }
 2054:     $request->print($result."\n");
 2055:     $request->print('</div>'."\n");
 2056:     # print student answer/submission
 2057:     # Options are (1) Handgaded submission only
 2058:     #             (2) Last submission, includes submission that is not handgraded 
 2059:     #                  (for multi-response type part)
 2060:     #             (3) Last submission plus the parts info
 2061:     #             (4) The whole record for this student
 2062:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2063: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2064: 	
 2065: 	my $lastsubonly;
 2066: 
 2067: 	if ($$timestamp eq '') {
 2068: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2069: 	} else {
 2070: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2071: 
 2072: 	    my %seenparts;
 2073: 	    my @part_response_id = &flatten_responseType($responseType);
 2074: 	    foreach my $part (@part_response_id) {
 2075: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2076: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2077: 
 2078: 		my ($partid,$respid) = @{ $part };
 2079: 		my $display_part=&get_display_part($partid,$symb);
 2080: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2081: 		    if (exists($seenparts{$partid})) { next; }
 2082: 		    $seenparts{$partid}=1;
 2083: 		    my $submitby='<b>Part:</b> '.$display_part.
 2084: 			' <b>Collaborative submission by:</b> '.
 2085: 			'<a href="javascript:viewSubmitter(\''.
 2086: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2087: 			'\');" target="_self">'.
 2088: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2089: 		    $request->print($submitby);
 2090: 		    next;
 2091: 		}
 2092: 		my $responsetype = $responseType->{$partid}->{$respid};
 2093: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2094: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2095: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2096: 			' )</span>&nbsp; &nbsp;'.
 2097: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2098: 		    next;
 2099: 		}
 2100: 		foreach my $submission (@$string) {
 2101: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2102: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2103: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2104: 		    # Similarity check
 2105: 		    my $similar='';
 2106: 		    if($env{'form.checkPlag'}){
 2107: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2108: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2109: 			if ($osim) {
 2110: 			    $osim=int($osim*100.0);
 2111: 			    my %old_course_desc = 
 2112: 				&Apache::lonnet::coursedescription($ocrsid,
 2113: 								   {'one_time' => 1});
 2114: 
 2115: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2116: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2117: 				    $osim,
 2118: 				    &Apache::loncommon::plainname($oname,$odom),
 2119: 				    $oname,$odom,
 2120: 				    $old_course_desc{'description'},
 2121: 				    $old_course_desc{'num'},
 2122: 				    $old_course_desc{'domain'}).
 2123: 				'</span></h3><blockquote><i>'.
 2124: 				&keywords_highlight($oessay).
 2125: 				'</i></blockquote><hr />';
 2126: 			}
 2127: 		    }
 2128: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2129: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2130: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2131: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2132: 			my $display_part=&get_display_part($partid,$symb);
 2133: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2134: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2135: 			    ' )</span>&nbsp; &nbsp;';
 2136: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2137: 			if (@$files) {
 2138: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
 2139: 			    my $file_counter = 0;
 2140: 			    foreach my $file (@$files) {
 2141: 			        $file_counter++;
 2142: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2143: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2144: 			    }
 2145: 			    $lastsubonly.='<br />';
 2146: 			}
 2147: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2148: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2149: 					 $respid,\%record,$order);
 2150: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2151: 			$lastsubonly.='</div>';
 2152: 		    }
 2153: 		}
 2154: 	    }
 2155: 	    $lastsubonly.='</div>'."\n";
 2156: 	}
 2157: 	$request->print($lastsubonly);
 2158:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2159: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2160: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2161:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2162: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2163: 								 $env{'request.course.id'},
 2164: 								 $last,'.submission',
 2165: 								 'Apache::grades::keywords_highlight'));
 2166:     }
 2167: 
 2168:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2169: 	.$udom.'" />'."\n");
 2170:     # return if view submission with no grading option
 2171:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2172: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2173: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2174: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2175: 	$toGrade.='</div>'."\n";
 2176: 	if (($env{'form.command'} eq 'submission') || 
 2177: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2178: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2179: 	}
 2180: 	$request->print($toGrade);
 2181: 	return;
 2182:     } else {
 2183: 	$request->print('</div>'."\n");
 2184:     }
 2185: 
 2186:     # essay grading message center
 2187:     if ($env{'form.handgrade'} eq 'yes') {
 2188: 	my $result='<div class="LC_grade_message_center">';
 2189:     
 2190: 	$result.='<div class="LC_grade_message_center_header">'.
 2191: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2192: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2193: 	my $msgfor = $givenn.' '.$lastname;
 2194: 	if (scalar(@$col_fullnames) > 0) {
 2195: 	    my $lastone = pop(@$col_fullnames);
 2196: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2197: 	}
 2198: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2199: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2200: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2201: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2202: 	    ',\''.$msgfor.'\');" target="_self">'.
 2203: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2204: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2205: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2206: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2207: 	    '<br />&nbsp;('.
 2208: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2209: 	$result.='</div></div>';
 2210: 	$request->print($result);
 2211:     }
 2212: 
 2213:     my %seen = ();
 2214:     my @partlist;
 2215:     my @gradePartRespid;
 2216:     my @part_response_id = &flatten_responseType($responseType);
 2217:     $request->print('<div class="LC_grade_assign">'.
 2218: 		    
 2219: 		    '<div class="LC_grade_assign_header">'.
 2220: 		    &mt('Assign Grades').'</div>'.
 2221: 		    '<div class="LC_grade_assign_body">');
 2222:     foreach my $part_response_id (@part_response_id) {
 2223:     	my ($partid,$respid) = @{ $part_response_id };
 2224: 	my $part_resp = join('_',@{ $part_response_id });
 2225: 	next if ($seen{$partid} > 0);
 2226: 	$seen{$partid}++;
 2227: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2228: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2229: 	push(@partlist,$partid);
 2230: 	push(@gradePartRespid,$partid.'.'.$respid);
 2231: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2232:     }
 2233:     $request->print('</div></div>');
 2234: 
 2235:     $request->print('<div class="LC_grade_info_links">');
 2236:     if ($perm{'vgr'}) {
 2237: 	$request->print(
 2238: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2239: 						   $uname,$udom,'check'));
 2240:     }
 2241:     if ($perm{'opa'}) {
 2242: 	$request->print(
 2243: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2244: 					 $uname,$udom,$symb,'check'));
 2245:     }
 2246:     $request->print('</div>');
 2247: 
 2248:     $result='<input type="hidden" name="partlist'.$counter.
 2249: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2250:     $result.='<input type="hidden" name="gradePartRespid'.
 2251: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2252:     my $ctr = 0;
 2253:     while ($ctr < scalar(@partlist)) {
 2254: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2255: 	    $partlist[$ctr].'" />'."\n";
 2256: 	$ctr++;
 2257:     }
 2258:     $request->print($result.''."\n");
 2259: 
 2260: # Done with printing info for one student
 2261: 
 2262:     $request->print('</div>');#LC_grade_show_user_body
 2263:     $request->print('</div>');#LC_grade_show_user
 2264: 
 2265: 
 2266:     # print end of form
 2267:     if ($counter == $total) {
 2268: 	my $endform='<table border="0"><tr><td>'."\n";
 2269: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2270: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2271: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2272: 	my $ntstu ='<select name="NTSTU">'.
 2273: 	    '<option>1</option><option>2</option>'.
 2274: 	    '<option>3</option><option>5</option>'.
 2275: 	    '<option>7</option><option>10</option></select>'."\n";
 2276: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2277: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2278: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2279: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2280: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2281: 	    '<input type="button" value="'.&mt('Next').'" '.
 2282: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2283: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2284:         $endform.="<input type='hidden' value='".&get_increment().
 2285:             "' name='increment' />";
 2286: 	$endform.='</td></tr></table></form>';
 2287: 	$endform.=&show_grading_menu_form($symb);
 2288: 	$request->print($endform);
 2289:     }
 2290:     return '';
 2291: }
 2292: 
 2293: sub check_collaborators {
 2294:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2295:     my ($result,@col_fullnames);
 2296:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2297:     foreach my $part (keys(%$handgrade)) {
 2298: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2299: 					'.maxcollaborators',
 2300: 					$symb,$udom,$uname);
 2301: 	next if ($ncol <= 0);
 2302: 	$part =~ s/\_/\./g;
 2303: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2304: 	my (@good_collaborators, @bad_collaborators);
 2305: 	foreach my $possible_collaborator
 2306: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2307: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2308: 	    next if ($possible_collaborator eq '');
 2309: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2310: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2311: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2312: 	    # Doing this grep allows 'fuzzy' specification
 2313: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2314: 			       keys(%$classlist));
 2315: 	    if (! scalar(@matches)) {
 2316: 		push(@bad_collaborators, $possible_collaborator);
 2317: 	    } else {
 2318: 		push(@good_collaborators, @matches);
 2319: 	    }
 2320: 	}
 2321: 	if (scalar(@good_collaborators) != 0) {
 2322: 	    $result.='<br />'.&mt('Collaborators: ');
 2323: 	    foreach my $name (@good_collaborators) {
 2324: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2325: 		push(@col_fullnames, $givenn.' '.$lastname);
 2326: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2327: 	    }
 2328: 	    $result.='<br />'."\n";
 2329: 	    my ($part)=split(/\./,$part);
 2330: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2331: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2332: 		"\n";
 2333: 	}
 2334: 	if (scalar(@bad_collaborators) > 0) {
 2335: 	    $result.='<div class="LC_warning">';
 2336: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2337: 	    $result .= '</div>';
 2338: 	}         
 2339: 	if (scalar(@bad_collaborators > $ncol)) {
 2340: 	    $result .= '<div class="LC_warning">';
 2341: 	    $result .= &mt('This student has submitted too many '.
 2342: 		'collaborators.  Maximum is [_1].',$ncol);
 2343: 	    $result .= '</div>';
 2344: 	}
 2345:     }
 2346:     return ($result,$fullname,\@col_fullnames);
 2347: }
 2348: 
 2349: #--- Retrieve the last submission for all the parts
 2350: sub get_last_submission {
 2351:     my ($returnhash)=@_;
 2352:     my (@string,$timestamp);
 2353:     if ($$returnhash{'version'}) {
 2354: 	my %lasthash=();
 2355: 	my ($version);
 2356: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2357: 	    foreach my $key (sort(split(/\:/,
 2358: 					$$returnhash{$version.':keys'}))) {
 2359: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2360: 		$timestamp = 
 2361: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2362: 	    }
 2363: 	}
 2364: 	foreach my $key (keys(%lasthash)) {
 2365: 	    next if ($key !~ /\.submission$/);
 2366: 
 2367: 	    my ($partid,$foo) = split(/submission$/,$key);
 2368: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2369: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2370: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2371: 	}
 2372:     }
 2373:     if (!@string) {
 2374: 	$string[0] =
 2375: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2376:     }
 2377:     return (\@string,\$timestamp);
 2378: }
 2379: 
 2380: #--- High light keywords, with style choosen by user.
 2381: sub keywords_highlight {
 2382:     my $string    = shift;
 2383:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2384:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2385:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2386:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2387:     foreach my $keyword (@keylist) {
 2388: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2389:     }
 2390:     return $string;
 2391: }
 2392: 
 2393: #--- Called from submission routine
 2394: sub processHandGrade {
 2395:     my ($request) = shift;
 2396:     my $symb   = &get_symb($request);
 2397:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2398:     my $button = $env{'form.gradeOpt'};
 2399:     my $ngrade = $env{'form.NCT'};
 2400:     my $ntstu  = $env{'form.NTSTU'};
 2401:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2402:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2403: 
 2404:     if ($button eq 'Save & Next') {
 2405: 	my $ctr = 0;
 2406: 	while ($ctr < $ngrade) {
 2407: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2408: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2409: 	    if ($errorflag eq 'no_score') {
 2410: 		$ctr++;
 2411: 		next;
 2412: 	    }
 2413: 	    if ($errorflag eq 'not_allowed') {
 2414: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2415: 		$ctr++;
 2416: 		next;
 2417: 	    }
 2418: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2419: 	    my ($subject,$message,$msgstatus) = ('','','');
 2420: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2421:             my ($feedurl,$showsymb) =
 2422: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2423: 	    my $messagetail;
 2424: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2425: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2426: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2427: 		$subject.=' ['.$restitle.']';
 2428: 		my (@msgnum) = split(/,/,$includemsg);
 2429: 		foreach (@msgnum) {
 2430: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2431: 		}
 2432: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2433: 		if ($env{'form.withgrades'.$ctr}) {
 2434: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2435: 		    $messagetail = " for <a href=\"".
 2436: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2437: 		}
 2438: 		$msgstatus = 
 2439:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2440: 						     $message.$messagetail,
 2441:                                                      undef,$feedurl,undef,
 2442:                                                      undef,undef,$showsymb,
 2443:                                                      $restitle);
 2444: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2445: 				$msgstatus);
 2446: 	    }
 2447: 	    if ($env{'form.collaborator'.$ctr}) {
 2448: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2449: 		foreach my $collabstr (@collabstrs) {
 2450: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2451: 		    foreach my $collaborator (@collaborators) {
 2452: 			my ($errorflag,$pts,$wgt) = 
 2453: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2454: 					   $env{'form.unamedom'.$ctr},$part);
 2455: 			if ($errorflag eq 'not_allowed') {
 2456: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2457: 			    next;
 2458: 			} elsif ($message ne '') {
 2459: 			    my ($baseurl,$showsymb) = 
 2460: 				&get_feedurl_and_symb($symb,$collaborator,
 2461: 						      $udom);
 2462: 			    if ($env{'form.withgrades'.$ctr}) {
 2463: 				$messagetail = " for <a href=\"".
 2464:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2465: 			    }
 2466: 			    $msgstatus = 
 2467: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2468: 			}
 2469: 		    }
 2470: 		}
 2471: 	    }
 2472: 	    $ctr++;
 2473: 	}
 2474:     }
 2475: 
 2476:     if ($env{'form.handgrade'} eq 'yes') {
 2477: 	# Keywords sorted in alphabatical order
 2478: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2479: 	my %keyhash = ();
 2480: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2481: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2482: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2483: 	$env{'form.keywords'} = join(' ',@keywords);
 2484: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2485: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2486: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2487: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2488: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2489: 
 2490: 	# message center - Order of message gets changed. Blank line is eliminated.
 2491: 	# New messages are saved in env for the next student.
 2492: 	# All messages are saved in nohist_handgrade.db
 2493: 	my ($ctr,$idx) = (1,1);
 2494: 	while ($ctr <= $env{'form.savemsgN'}) {
 2495: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2496: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2497: 		$idx++;
 2498: 	    }
 2499: 	    $ctr++;
 2500: 	}
 2501: 	$ctr = 0;
 2502: 	while ($ctr < $ngrade) {
 2503: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2504: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2505: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2506: 		$idx++;
 2507: 	    }
 2508: 	    $ctr++;
 2509: 	}
 2510: 	$env{'form.savemsgN'} = --$idx;
 2511: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2512: 	my $putresult = &Apache::lonnet::put
 2513: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2514:     }
 2515:     # Called by Save & Refresh from Highlight Attribute Window
 2516:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2517:     if ($env{'form.refresh'} eq 'on') {
 2518: 	my ($ctr,$total) = (0,0);
 2519: 	while ($ctr < $ngrade) {
 2520: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2521: 	    $ctr++;
 2522: 	}
 2523: 	$env{'form.NTSTU'}=$ngrade;
 2524: 	$ctr = 0;
 2525: 	while ($ctr < $total) {
 2526: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2527: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2528: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2529: 	    &submission($request,$ctr,$total-1);
 2530: 	    $ctr++;
 2531: 	}
 2532: 	return '';
 2533:     }
 2534: 
 2535: # Go directly to grade student - from submission or link from chart page
 2536:     if ($button eq 'Grade Student') {
 2537: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2538: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2539: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2540: 	$env{'form.fullname'} = $$fullname{$processUser};
 2541: 	&submission($request,0,0);
 2542: 	return '';
 2543:     }
 2544: 
 2545:     # Get the next/previous one or group of students
 2546:     my $firststu = $env{'form.unamedom0'};
 2547:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2548:     my $ctr = 2;
 2549:     while ($laststu eq '') {
 2550: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2551: 	$ctr++;
 2552: 	$laststu = $firststu if ($ctr > $ngrade);
 2553:     }
 2554: 
 2555:     my (@parsedlist,@nextlist);
 2556:     my ($nextflg) = 0;
 2557:     foreach my $item (sort 
 2558: 	     {
 2559: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2560: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2561: 		 }
 2562: 		 return $a cmp $b;
 2563: 	     } (keys(%$fullname))) {
 2564: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2565: 	    push(@parsedlist,$item);
 2566: 	}
 2567: 	$nextflg = 1 if ($item eq $laststu);
 2568: 	if ($button eq 'Previous') {
 2569: 	    last if ($item eq $firststu);
 2570: 	    push(@parsedlist,$item);
 2571: 	}
 2572:     }
 2573:     $ctr = 0;
 2574:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2575:     my ($partlist) = &response_type($symb);
 2576:     foreach my $student (@parsedlist) {
 2577: 	my $submitonly=$env{'form.submitonly'};
 2578: 	my ($uname,$udom) = split(/:/,$student);
 2579: 	
 2580: 	if ($submitonly eq 'queued') {
 2581: 	    my %queue_status = 
 2582: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2583: 							$udom,$uname);
 2584: 	    next if (!defined($queue_status{'gradingqueue'}));
 2585: 	}
 2586: 
 2587: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2588: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2589: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2590: 	    my $submitted = 0;
 2591: 	    my $ungraded = 0;
 2592: 	    my $incorrect = 0;
 2593: 	    foreach my $item (keys(%status)) {
 2594: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2595: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2596: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2597: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2598: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2599: 		    $submitted = 0;
 2600: 		}
 2601: 	    }
 2602: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2603: 				     $submitonly eq 'incorrect' ||
 2604: 				     $submitonly eq 'graded'));
 2605: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2606: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2607: 	}
 2608: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2609: 	last if ($ctr == $ntstu);
 2610: 	$ctr++;
 2611:     }
 2612: 
 2613:     $ctr = 0;
 2614:     my $total = scalar(@nextlist)-1;
 2615: 
 2616:     foreach (sort(@nextlist)) {
 2617: 	my ($uname,$udom,$submitter) = split(/:/);
 2618: 	$env{'form.student'}  = $uname;
 2619: 	$env{'form.userdom'}  = $udom;
 2620: 	$env{'form.fullname'} = $$fullname{$_};
 2621: 	&submission($request,$ctr,$total);
 2622: 	$ctr++;
 2623:     }
 2624:     if ($total < 0) {
 2625: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2626: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2627: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2628: 	$the_end.=&show_grading_menu_form($symb);
 2629: 	$request->print($the_end);
 2630:     }
 2631:     return '';
 2632: }
 2633: 
 2634: #---- Save the score and award for each student, if changed
 2635: sub saveHandGrade {
 2636:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2637:     my @version_parts;
 2638:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2639: 					   $env{'request.course.id'});
 2640:     if (!&canmodify($usec)) { return('not_allowed'); }
 2641:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2642:     my @parts_graded;
 2643:     my %newrecord  = ();
 2644:     my ($pts,$wgt) = ('','');
 2645:     my %aggregate = ();
 2646:     my $aggregateflag = 0;
 2647:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2648:     foreach my $new_part (@parts) {
 2649: 	#collaborator ($submi may vary for different parts
 2650: 	if ($submitter && $new_part ne $part) { next; }
 2651: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2652: 	if ($dropMenu eq 'excused') {
 2653: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2654: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2655: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2656: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2657: 		}
 2658: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2659: 	    }
 2660: 	} elsif ($dropMenu eq 'reset status'
 2661: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2662: 	    foreach my $key (keys(%record)) {
 2663: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2664: 	    }
 2665: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2666: 		"$env{'user.name'}:$env{'user.domain'}";
 2667:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2668: 
 2669:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2670: 					       [$new_part]);
 2671:             my $aggtries =$totaltries;
 2672:             if ($last_resets{$new_part}) {
 2673:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2674: 					   $new_part);
 2675:             }
 2676: 
 2677:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2678:             if ($aggtries > 0) {
 2679:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2680:                 $aggregateflag = 1;
 2681:             }
 2682: 	} elsif ($dropMenu eq '') {
 2683: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2684: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2685: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2686: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2687: 		next;
 2688: 	    }
 2689: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2690: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2691: 	    my $partial= $pts/$wgt;
 2692: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2693: 		#do not update score for part if not changed.
 2694:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2695: 		next;
 2696: 	    } else {
 2697: 	        push(@parts_graded,$new_part);
 2698: 	    }
 2699: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2700: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2701: 	    }
 2702: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2703: 	    if ($partial == 0) {
 2704: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2705: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2706: 		}
 2707: 	    } else {
 2708: 		if ($record{$reckey} ne 'correct_by_override') {
 2709: 		    $newrecord{$reckey} = 'correct_by_override';
 2710: 		}
 2711: 	    }	    
 2712: 	    if ($submitter && 
 2713: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2714: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2715: 	    }
 2716: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2717: 		"$env{'user.name'}:$env{'user.domain'}";
 2718: 	}
 2719: 	# unless problem has been graded, set flag to version the submitted files
 2720: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2721: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2722: 	        $dropMenu eq 'reset status')
 2723: 	   {
 2724: 	    push(@version_parts,$new_part);
 2725: 	}
 2726:     }
 2727:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2728:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2729: 
 2730:     if (%newrecord) {
 2731:         if (@version_parts) {
 2732:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2733:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2734: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2735: 	    foreach my $new_part (@version_parts) {
 2736: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2737: 				$new_part,\%newrecord);
 2738: 	    }
 2739:         }
 2740: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2741: 				$env{'request.course.id'},$domain,$stuname);
 2742: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2743: 				     $cdom,$cnum,$domain,$stuname);
 2744:     }
 2745:     if ($aggregateflag) {
 2746:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2747: 			      $cdom,$cnum);
 2748:     }
 2749:     return ('',$pts,$wgt);
 2750: }
 2751: 
 2752: sub check_and_remove_from_queue {
 2753:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2754:     my @ungraded_parts;
 2755:     foreach my $part (@{$parts}) {
 2756: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2757: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2758: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2759: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2760: 		) {
 2761: 	    push(@ungraded_parts, $part);
 2762: 	}
 2763:     }
 2764:     if ( !@ungraded_parts ) {
 2765: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2766: 					       $cnum,$domain,$stuname);
 2767:     }
 2768: }
 2769: 
 2770: sub handback_files {
 2771:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2772:     my $portfolio_root = '/userfiles/portfolio';
 2773:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2774: 
 2775:     my @part_response_id = &flatten_responseType($responseType);
 2776:     foreach my $part_response_id (@part_response_id) {
 2777:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2778: 	my $part_resp = join('_',@{ $part_response_id });
 2779:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2780:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2781:                 my $file_counter = 1;
 2782: 		my $file_msg;
 2783:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2784:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2785:                     my ($directory,$answer_file) = 
 2786:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2787:                     my ($answer_name,$answer_ver,$answer_ext) =
 2788: 		        &file_name_version_ext($answer_file);
 2789: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2790:                     my $getpropath = 1;
 2791: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2792: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2793:                     # fix file name
 2794:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2795:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2796:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2797:             	                                $save_file_name);
 2798:                     if ($result !~ m|^/uploaded/|) {
 2799:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2800:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2801:                     } else {
 2802:                         # mark the file as read only
 2803:                         my @files = ($save_file_name);
 2804:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2805:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2806: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2807: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2808: 			}
 2809:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2810: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2811: 
 2812:                     }
 2813:                     $request->print("<br />".$fname." will be the uploaded file name");
 2814:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2815:                     $file_counter++;
 2816:                 }
 2817: 		my $subject = "File Handed Back by Instructor ";
 2818: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2819: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2820: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2821: 		$message .= " and can be found in your portfolio space.";
 2822: 		my ($feedurl,$showsymb) = 
 2823: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2824:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2825: 		my $msgstatus = 
 2826:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2827: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2828:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2829:             }
 2830:         }
 2831:     return;
 2832: }
 2833: 
 2834: sub get_feedurl_and_symb {
 2835:     my ($symb,$uname,$udom) = @_;
 2836:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2837:     $url = &Apache::lonnet::clutter($url);
 2838:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2839: 					$symb,$udom,$uname);
 2840:     if ($encrypturl =~ /^yes$/i) {
 2841: 	&Apache::lonenc::encrypted(\$url,1);
 2842: 	&Apache::lonenc::encrypted(\$symb,1);
 2843:     }
 2844:     return ($url,$symb);
 2845: }
 2846: 
 2847: sub get_submitted_files {
 2848:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2849:     my @files;
 2850:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2851:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2852:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2853:     	    push(@files,$file_url.$file);
 2854:         }
 2855:     }
 2856:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2857:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2858:     }
 2859:     return (\@files);
 2860: }
 2861: 
 2862: # ----------- Provides number of tries since last reset.
 2863: sub get_num_tries {
 2864:     my ($record,$last_reset,$part) = @_;
 2865:     my $timestamp = '';
 2866:     my $num_tries = 0;
 2867:     if ($$record{'version'}) {
 2868:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2869:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2870:                 $timestamp = $$record{$version.':timestamp'};
 2871:                 if ($timestamp > $last_reset) {
 2872:                     $num_tries ++;
 2873:                 } else {
 2874:                     last;
 2875:                 }
 2876:             }
 2877:         }
 2878:     }
 2879:     return $num_tries;
 2880: }
 2881: 
 2882: # ----------- Determine decrements required in aggregate totals 
 2883: sub decrement_aggs {
 2884:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2885:     my %decrement = (
 2886:                         attempts => 0,
 2887:                         users => 0,
 2888:                         correct => 0
 2889:                     );
 2890:     $decrement{'attempts'} = $aggtries;
 2891:     if ($solvedstatus =~ /^correct/) {
 2892:         $decrement{'correct'} = 1;
 2893:     }
 2894:     if ($aggtries == $totaltries) {
 2895:         $decrement{'users'} = 1;
 2896:     }
 2897:     foreach my $type (keys(%decrement)) {
 2898:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2899:     }
 2900:     return;
 2901: }
 2902: 
 2903: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2904: sub get_last_resets {
 2905:     my ($symb,$courseid,$partids) =@_;
 2906:     my %last_resets;
 2907:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2908:     my $cname = $env{'course.'.$courseid.'.num'};
 2909:     my @keys;
 2910:     foreach my $part (@{$partids}) {
 2911: 	push(@keys,"$symb\0$part\0resettime");
 2912:     }
 2913:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2914: 				     $cdom,$cname);
 2915:     foreach my $part (@{$partids}) {
 2916: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2917:     }
 2918:     return %last_resets;
 2919: }
 2920: 
 2921: # ----------- Handles creating versions for portfolio files as answers
 2922: sub version_portfiles {
 2923:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2924:     my $version_parts = join('|',@$v_flag);
 2925:     my @returned_keys;
 2926:     my $parts = join('|', @$parts_graded);
 2927:     my $portfolio_root = '/userfiles/portfolio';
 2928:     foreach my $key (keys(%$record)) {
 2929:         my $new_portfiles;
 2930:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2931:             my @versioned_portfiles;
 2932:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2933:             foreach my $file (@portfiles) {
 2934:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2935:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2936: 		my ($answer_name,$answer_ver,$answer_ext) =
 2937: 		    &file_name_version_ext($answer_file);
 2938:                 my $getpropath = 1;    
 2939:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2940:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2941:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2942:                 if ($new_answer ne 'problem getting file') {
 2943:                     push(@versioned_portfiles, $directory.$new_answer);
 2944:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2945:                         [$directory.$new_answer],
 2946:                         [$symb,$env{'request.course.id'},'graded']);
 2947:                 }
 2948:             }
 2949:             $$record{$key} = join(',',@versioned_portfiles);
 2950:             push(@returned_keys,$key);
 2951:         }
 2952:     } 
 2953:     return (@returned_keys);   
 2954: }
 2955: 
 2956: sub get_next_version {
 2957:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2958:     my $version;
 2959:     foreach my $row (@$dir_list) {
 2960:         my ($file) = split(/\&/,$row,2);
 2961:         my ($file_name,$file_version,$file_ext) =
 2962: 	    &file_name_version_ext($file);
 2963:         if (($file_name eq $answer_name) && 
 2964: 	    ($file_ext eq $answer_ext)) {
 2965:                 # gets here if filename and extension match, regardless of version
 2966:                 if ($file_version ne '') {
 2967:                 # a versioned file is found  so save it for later
 2968:                 if ($file_version > $version) {
 2969: 		    $version = $file_version;
 2970: 	        }
 2971:             }
 2972:         }
 2973:     } 
 2974:     $version ++;
 2975:     return($version);
 2976: }
 2977: 
 2978: sub version_selected_portfile {
 2979:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2980:     my ($answer_name,$answer_ver,$answer_ext) =
 2981:         &file_name_version_ext($file_name);
 2982:     my $new_answer;
 2983:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2984:     if($env{'form.copy'} eq '-1') {
 2985:         $new_answer = 'problem getting file';
 2986:     } else {
 2987:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2988:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2989:                             $stu_name,$domain,'copy',
 2990: 		        '/portfolio'.$directory.$new_answer);
 2991:     }    
 2992:     return ($new_answer);
 2993: }
 2994: 
 2995: sub file_name_version_ext {
 2996:     my ($file)=@_;
 2997:     my @file_parts = split(/\./, $file);
 2998:     my ($name,$version,$ext);
 2999:     if (@file_parts > 1) {
 3000: 	$ext=pop(@file_parts);
 3001: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3002: 	    $version=pop(@file_parts);
 3003: 	}
 3004: 	$name=join('.',@file_parts);
 3005:     } else {
 3006: 	$name=join('.',@file_parts);
 3007:     }
 3008:     return($name,$version,$ext);
 3009: }
 3010: 
 3011: #--------------------------------------------------------------------------------------
 3012: #
 3013: #-------------------------- Next few routines handles grading by section or whole class
 3014: #
 3015: #--- Javascript to handle grading by section or whole class
 3016: sub viewgrades_js {
 3017:     my ($request) = shift;
 3018: 
 3019:     $request->print(<<VIEWJAVASCRIPT);
 3020: <script type="text/javascript" language="javascript">
 3021:    function writePoint(partid,weight,point) {
 3022: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3023: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3024: 	if (point == "textval") {
 3025: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3026: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3027: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3028: 		var resetbox = false;
 3029: 		for (var i=0; i<radioButton.length; i++) {
 3030: 		    if (radioButton[i].checked) {
 3031: 			textbox.value = i;
 3032: 			resetbox = true;
 3033: 		    }
 3034: 		}
 3035: 		if (!resetbox) {
 3036: 		    textbox.value = "";
 3037: 		}
 3038: 		return;
 3039: 	    }
 3040: 	    if (parseFloat(point) > parseFloat(weight)) {
 3041: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3042: 				   ") greater than the weight for the part. Accept?");
 3043: 		if (resp == false) {
 3044: 		    textbox.value = "";
 3045: 		    return;
 3046: 		}
 3047: 	    }
 3048: 	    for (var i=0; i<radioButton.length; i++) {
 3049: 		radioButton[i].checked=false;
 3050: 		if (parseFloat(point) == i) {
 3051: 		    radioButton[i].checked=true;
 3052: 		}
 3053: 	    }
 3054: 
 3055: 	} else {
 3056: 	    textbox.value = parseFloat(point);
 3057: 	}
 3058: 	for (i=0;i<document.classgrade.total.value;i++) {
 3059: 	    var user = document.classgrade["ctr"+i].value;
 3060: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3061: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3062: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3063: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3064: 	    if (saveval != "correct") {
 3065: 		scorename.value = point;
 3066: 		if (selname[0].selected != true) {
 3067: 		    selname[0].selected = true;
 3068: 		}
 3069: 	    }
 3070: 	}
 3071: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3072:     }
 3073: 
 3074:     function writeRadText(partid,weight) {
 3075: 	var selval   = document.classgrade["SELVAL_"+partid];
 3076: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3077:         var override = document.classgrade["FORCE_"+partid].checked;
 3078: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3079: 	if (selval[1].selected || selval[2].selected) {
 3080: 	    for (var i=0; i<radioButton.length; i++) {
 3081: 		radioButton[i].checked=false;
 3082: 
 3083: 	    }
 3084: 	    textbox.value = "";
 3085: 
 3086: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3087: 		var user = document.classgrade["ctr"+i].value;
 3088: 		user = user.replace(new RegExp(':', 'g'),"_");
 3089: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3090: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3091: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3092: 		if ((saveval != "correct") || override) {
 3093: 		    scorename.value = "";
 3094: 		    if (selval[1].selected) {
 3095: 			selname[1].selected = true;
 3096: 		    } else {
 3097: 			selname[2].selected = true;
 3098: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3099: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3100: 		    }
 3101: 		}
 3102: 	    }
 3103: 	} else {
 3104: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3105: 		var user = document.classgrade["ctr"+i].value;
 3106: 		user = user.replace(new RegExp(':', 'g'),"_");
 3107: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3108: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3109: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3110: 		if ((saveval != "correct") || override) {
 3111: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3112: 		    selname[0].selected = true;
 3113: 		}
 3114: 	    }
 3115: 	}	    
 3116:     }
 3117: 
 3118:     function changeSelect(partid,user) {
 3119: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3120: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3121: 	var point  = textbox.value;
 3122: 	var weight = document.classgrade["weight_"+partid].value;
 3123: 
 3124: 	if (isNaN(point) || parseFloat(point) < 0) {
 3125: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3126: 	    textbox.value = "";
 3127: 	    return;
 3128: 	}
 3129: 	if (parseFloat(point) > parseFloat(weight)) {
 3130: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3131: 			       ") greater than the weight of the part. Accept?");
 3132: 	    if (resp == false) {
 3133: 		textbox.value = "";
 3134: 		return;
 3135: 	    }
 3136: 	}
 3137: 	selval[0].selected = true;
 3138:     }
 3139: 
 3140:     function changeOneScore(partid,user) {
 3141: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3142: 	if (selval[1].selected || selval[2].selected) {
 3143: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3144: 	    if (selval[2].selected) {
 3145: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3146: 	    }
 3147:         }
 3148:     }
 3149: 
 3150:     function resetEntry(numpart) {
 3151: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3152: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3153: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3154: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3155: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3156: 	    for (var i=0; i<radioButton.length; i++) {
 3157: 		radioButton[i].checked=false;
 3158: 
 3159: 	    }
 3160: 	    textbox.value = "";
 3161: 	    selval[0].selected = true;
 3162: 
 3163: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3164: 		var user = document.classgrade["ctr"+i].value;
 3165: 		user = user.replace(new RegExp(':', 'g'),"_");
 3166: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3167: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3168: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3169: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3170: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3172: 		if (saveselval == "excused") {
 3173: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3174: 		} else {
 3175: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3176: 		}
 3177: 	    }
 3178: 	}
 3179:     }
 3180: 
 3181: </script>
 3182: VIEWJAVASCRIPT
 3183: }
 3184: 
 3185: #--- show scores for a section or whole class w/ option to change/update a score
 3186: sub viewgrades {
 3187:     my ($request) = shift;
 3188:     &viewgrades_js($request);
 3189: 
 3190:     my ($symb) = &get_symb($request);
 3191:     #need to make sure we have the correct data for later EXT calls, 
 3192:     #thus invalidate the cache
 3193:     &Apache::lonnet::devalidatecourseresdata(
 3194:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3195:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3196:     &Apache::lonnet::clear_EXT_cache_status();
 3197: 
 3198:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3199:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3200: 
 3201:     #view individual student submission form - called using Javascript viewOneStudent
 3202:     $result.=&jscriptNform($symb);
 3203: 
 3204:     #beginning of class grading form
 3205:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3206:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3207: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3208: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3209: 	&build_section_inputs().
 3210: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3211: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3212: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3213: 
 3214:     my $sectionClass;
 3215:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3216:     if ($env{'form.section'} eq 'all') {
 3217: 	$sectionClass='Class';
 3218:     } elsif ($env{'form.section'} eq 'none') {
 3219: 	$sectionClass='Students in no Section';
 3220:     } else {
 3221: 	$sectionClass='Students in Section(s) [_1]';
 3222:     }
 3223:     $result.=
 3224: 	'<h3>'.
 3225: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3226:     $result.= &Apache::loncommon::start_data_table();
 3227:     #radio buttons/text box for assigning points for a section or class.
 3228:     #handles different parts of a problem
 3229:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3230:     my %weight = ();
 3231:     my $ctsparts = 0;
 3232:     my %seen = ();
 3233:     my @part_response_id = &flatten_responseType($responseType);
 3234:     foreach my $part_response_id (@part_response_id) {
 3235:     	my ($partid,$respid) = @{ $part_response_id };
 3236: 	my $part_resp = join('_',@{ $part_response_id });
 3237: 	next if $seen{$partid};
 3238: 	$seen{$partid}++;
 3239: 	my $handgrade=$$handgrade{$part_resp};
 3240: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3241: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3242: 
 3243: 	my $display_part=&get_display_part($partid,$symb);
 3244: 	my $radio.='<table border="0"><tr>';  
 3245: 	my $ctr = 0;
 3246: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3247: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3248: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3249: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3250: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3251: 	    $ctr++;
 3252: 	}
 3253: 	$radio.='</tr></table>';
 3254: 	my $line = '<input type="text" name="TEXTVAL_'.
 3255: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3256: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3257: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3258: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3259: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3260: 		$weight{$partid}.')"> '.
 3261: 	    '<option selected="selected"> </option>'.
 3262: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3263: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3264: 	    '</select></td>'.
 3265:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3266: 	$line.='<input type="hidden" name="partid_'.
 3267: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3268: 	$line.='<input type="hidden" name="weight_'.
 3269: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3270: 
 3271: 	$result.=
 3272: 	    &Apache::loncommon::start_data_table_row()."\n".
 3273: 	    &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).
 3274: 	    &Apache::loncommon::end_data_table_row()."\n";
 3275: 	$ctsparts++;
 3276:     }
 3277:     $result.=&Apache::loncommon::end_data_table()."\n".
 3278: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3279:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3280: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3281: 
 3282:     #table listing all the students in a section/class
 3283:     #header of table
 3284:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3285: 			 $section_display).'</h3>';
 3286:     $result.= &Apache::loncommon::start_data_table().
 3287: 	&Apache::loncommon::start_data_table_header_row().
 3288: 	'<th>'.&mt('No.').'</th>'.
 3289: 	'<th>'.&nameUserString('header')."</th>\n";
 3290:     my (@parts) = sort(&getpartlist($symb));
 3291:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3292:     my @partids = ();
 3293:     foreach my $part (@parts) {
 3294: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3295: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3296: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3297: 	my ($partid) = &split_part_type($part);
 3298:         push(@partids,$partid);
 3299: 	my $display_part=&get_display_part($partid,$symb);
 3300: 	if ($display =~ /^Partial Credit Factor/) {
 3301: 	    $result.='<th>'.
 3302: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3303: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3304: 	    next;
 3305: 	    
 3306: 	} else {
 3307: 	    if ($display =~ /Problem Status/) {
 3308: 		my $grade_status_mt = &mt('Grade Status');
 3309: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3310: 	    }
 3311: 	    my $part_mt = &mt('Part:');
 3312: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3313: 	}
 3314: 
 3315: 	$result.='<th>'.$display.'</th>'."\n";
 3316:     }
 3317:     $result.=&Apache::loncommon::end_data_table_header_row();
 3318: 
 3319:     my %last_resets = 
 3320: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3321: 
 3322:     #get info for each student
 3323:     #list all the students - with points and grade status
 3324:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3325:     my $ctr = 0;
 3326:     foreach (sort 
 3327: 	     {
 3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3330: 		 }
 3331: 		 return $a cmp $b;
 3332: 	     } (keys(%$fullname))) {
 3333: 	$ctr++;
 3334: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3335: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3336:     }
 3337:     $result.=&Apache::loncommon::end_data_table();
 3338:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3339:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3340: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3341:     if (scalar(%$fullname) eq 0) {
 3342: 	my $colspan=3+scalar(@parts);
 3343: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3344:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3345: 	$result='<span class="LC_warning">'.
 3346: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3347: 	        $section_display, $stu_status).
 3348: 	    '</span>';
 3349:     }
 3350:     $result.=&show_grading_menu_form($symb);
 3351:     return $result;
 3352: }
 3353: 
 3354: #--- call by previous routine to display each student
 3355: sub viewstudentgrade {
 3356:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3357:     my ($uname,$udom) = split(/:/,$student);
 3358:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3359:     my %aggregates = (); 
 3360:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3361: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3362: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3363: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3364: 	'\');" target="_self">'.$fullname.'</a> '.
 3365: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3366:     $student=~s/:/_/; # colon doen't work in javascript for names
 3367:     foreach my $apart (@$parts) {
 3368: 	my ($part,$type) = &split_part_type($apart);
 3369: 	my $score=$record{"resource.$part.$type"};
 3370:         $result.='<td align="center">';
 3371:         my ($aggtries,$totaltries);
 3372:         unless (exists($aggregates{$part})) {
 3373: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3374: 
 3375: 	    $aggtries = $totaltries;
 3376:             if ($$last_resets{$part}) {  
 3377:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3378: 					   $part);
 3379:             }
 3380:             $result.='<input type="hidden" name="'.
 3381:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3382:             $result.='<input type="hidden" name="'.
 3383:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3384:             $aggregates{$part} = 1;
 3385:         }
 3386: 	if ($type eq 'awarded') {
 3387: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3388: 	    $result.='<input type="hidden" name="'.
 3389: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3390: 	    $result.='<input type="text" name="'.
 3391: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3392: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3393: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3394: 	} elsif ($type eq 'solved') {
 3395: 	    my ($status,$foo)=split(/_/,$score,2);
 3396: 	    $status = 'nothing' if ($status eq '');
 3397: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3398: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3399: 	    $result.='&nbsp;<select name="'.
 3400: 		'GD_'.$student.'_'.$part.'_solved" '.
 3401: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3402: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3403: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3404: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3405: 	    $result.="</select>&nbsp;</td>\n";
 3406: 	} else {
 3407: 	    $result.='<input type="hidden" name="'.
 3408: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3409: 		    "\n";
 3410: 	    $result.='<input type="text" name="'.
 3411: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3412: 		'value="'.$score.'" size="4" /></td>'."\n";
 3413: 	}
 3414:     }
 3415:     $result.=&Apache::loncommon::end_data_table_row();
 3416:     return $result;
 3417: }
 3418: 
 3419: #--- change scores for all the students in a section/class
 3420: #    record does not get update if unchanged
 3421: sub editgrades {
 3422:     my ($request) = @_;
 3423: 
 3424:     my $symb=&get_symb($request);
 3425:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3426:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3427:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3428:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3429: 
 3430:     my $result= &Apache::loncommon::start_data_table().
 3431: 	&Apache::loncommon::start_data_table_header_row().
 3432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3434:     my %scoreptr = (
 3435: 		    'correct'  =>'correct_by_override',
 3436: 		    'incorrect'=>'incorrect_by_override',
 3437: 		    'excused'  =>'excused',
 3438: 		    'ungraded' =>'ungraded_attempted',
 3439: 		    'nothing'  => '',
 3440: 		    );
 3441:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3442: 
 3443:     my (@partid);
 3444:     my %weight = ();
 3445:     my %columns = ();
 3446:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3447: 
 3448:     my (@parts) = sort(&getpartlist($symb));
 3449:     my $header;
 3450:     while ($ctr < $env{'form.totalparts'}) {
 3451: 	my $partid = $env{'form.partid_'.$ctr};
 3452: 	push(@partid,$partid);
 3453: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3454: 	$ctr++;
 3455:     }
 3456:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3457:     foreach my $partid (@partid) {
 3458: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3459: 	    '<th align="center">'.&mt('New Score').'</th>';
 3460: 	$columns{$partid}=2;
 3461: 	foreach my $stores (@parts) {
 3462: 	    my ($part,$type) = &split_part_type($stores);
 3463: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3464: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3465: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3466: 	    $display =~ s/\[Part: (\w)+\]//;
 3467: 	    $display =~ s/Number of Attempts/Tries/;
 3468: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3469: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3470: 	    $columns{$partid}+=2;
 3471: 	}
 3472:     }
 3473:     foreach my $partid (@partid) {
 3474: 	my $display_part=&get_display_part($partid,$symb);
 3475: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3476: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3477: 	    '</th>';
 3478: 
 3479:     }
 3480:     $result .= &Apache::loncommon::end_data_table_header_row().
 3481: 	&Apache::loncommon::start_data_table_header_row().
 3482: 	$header.
 3483: 	&Apache::loncommon::end_data_table_header_row();
 3484:     my @noupdate;
 3485:     my ($updateCtr,$noupdateCtr) = (1,1);
 3486:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3487: 	my $line;
 3488: 	my $user = $env{'form.ctr'.$i};
 3489: 	my ($uname,$udom)=split(/:/,$user);
 3490: 	my %newrecord;
 3491: 	my $updateflag = 0;
 3492: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3493: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3494: 	if (!&canmodify($usec)) {
 3495: 	    my $numcols=scalar(@partid)*4+2;
 3496: 	    push(@noupdate,
 3497: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3498: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3499: 	    next;
 3500: 	}
 3501:         my %aggregate = ();
 3502:         my $aggregateflag = 0;
 3503: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3504: 	foreach (@partid) {
 3505: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3506: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3507: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3508: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3509: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3510: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3511: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3512: 	    my $score;
 3513: 	    if ($partial eq '') {
 3514: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3515: 	    } elsif ($partial > 0) {
 3516: 		$score = 'correct_by_override';
 3517: 	    } elsif ($partial == 0) {
 3518: 		$score = 'incorrect_by_override';
 3519: 	    }
 3520: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3521: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3522: 
 3523: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3524: 		"$env{'user.name'}:$env{'user.domain'}";
 3525: 	    if ($dropMenu eq 'reset status' &&
 3526: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3527: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3528: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3529: 		$newrecord{'resource.'.$_.'.award'} = '';
 3530: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3531: 		$updateflag = 1;
 3532:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3533:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3534:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3535:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3536:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3537:                     $aggregateflag = 1;
 3538:                 }
 3539: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3540: 		$updateflag = 1;
 3541: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3542: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3543: 		$rec_update++;
 3544: 	    }
 3545: 
 3546: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3547: 		'<td align="center">'.$awarded.
 3548: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3549: 
 3550: 
 3551: 	    my $partid=$_;
 3552: 	    foreach my $stores (@parts) {
 3553: 		my ($part,$type) = &split_part_type($stores);
 3554: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3555: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3556: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3557: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3558: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3559: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3560: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3561: 		    $updateflag=1;
 3562: 		}
 3563: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3564: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3565: 	    }
 3566: 	}
 3567: 	$line.="\n";
 3568: 
 3569: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3570: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3571: 
 3572: 	if ($updateflag) {
 3573: 	    $count++;
 3574: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3575: 				    $udom,$uname);
 3576: 
 3577: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3578: 					      $cnum,$udom,$uname)) {
 3579: 		# need to figure out if should be in queue.
 3580: 		my %record =  
 3581: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3582: 					     $udom,$uname);
 3583: 		my $all_graded = 1;
 3584: 		my $none_graded = 1;
 3585: 		foreach my $part (@parts) {
 3586: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3587: 			$all_graded = 0;
 3588: 		    } else {
 3589: 			$none_graded = 0;
 3590: 		    }
 3591: 		}
 3592: 
 3593: 		if ($all_graded || $none_graded) {
 3594: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3595: 							   $symb,$cdom,$cnum,
 3596: 							   $udom,$uname);
 3597: 		}
 3598: 	    }
 3599: 
 3600: 	    $result.=&Apache::loncommon::start_data_table_row().
 3601: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3602: 		&Apache::loncommon::end_data_table_row();
 3603: 	    $updateCtr++;
 3604: 	} else {
 3605: 	    push(@noupdate,
 3606: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3607: 	    $noupdateCtr++;
 3608: 	}
 3609:         if ($aggregateflag) {
 3610:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3611: 				  $cdom,$cnum);
 3612:         }
 3613:     }
 3614:     if (@noupdate) {
 3615: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3616: 	my $numcols=scalar(@partid)*4+2;
 3617: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3618: 	    '<td align="center" colspan="'.$numcols.'">'.
 3619: 	    &mt('No Changes Occurred For the Students Below').
 3620: 	    '</td>'.
 3621: 	    &Apache::loncommon::end_data_table_row();
 3622: 	foreach my $line (@noupdate) {
 3623: 	    $result.=
 3624: 		&Apache::loncommon::start_data_table_row().
 3625: 		$line.
 3626: 		&Apache::loncommon::end_data_table_row();
 3627: 	}
 3628:     }
 3629:     $result .= &Apache::loncommon::end_data_table().
 3630: 	&show_grading_menu_form($symb);
 3631:     my $msg = '<p><b>'.
 3632: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3633: 	    $rec_update,$count).'</b><br />'.
 3634: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3635: 	'</b></p>';
 3636:     return $title.$msg.$result;
 3637: }
 3638: 
 3639: sub split_part_type {
 3640:     my ($partstr) = @_;
 3641:     my ($temp,@allparts)=split(/_/,$partstr);
 3642:     my $type=pop(@allparts);
 3643:     my $part=join('_',@allparts);
 3644:     return ($part,$type);
 3645: }
 3646: 
 3647: #------------- end of section for handling grading by section/class ---------
 3648: #
 3649: #----------------------------------------------------------------------------
 3650: 
 3651: 
 3652: #----------------------------------------------------------------------------
 3653: #
 3654: #-------------------------- Next few routines handles grading by csv upload
 3655: #
 3656: #--- Javascript to handle csv upload
 3657: sub csvupload_javascript_reverse_associate {
 3658:     my $error1=&mt('You need to specify the username or ID');
 3659:     my $error2=&mt('You need to specify at least one grading field');
 3660:   return(<<ENDPICK);
 3661:   function verify(vf) {
 3662:     var foundsomething=0;
 3663:     var founduname=0;
 3664:     var foundID=0;
 3665:     for (i=0;i<=vf.nfields.value;i++) {
 3666:       tw=eval('vf.f'+i+'.selectedIndex');
 3667:       if (i==0 && tw!=0) { foundID=1; }
 3668:       if (i==1 && tw!=0) { founduname=1; }
 3669:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3670:     }
 3671:     if (founduname==0 && foundID==0) {
 3672: 	alert('$error1');
 3673: 	return;
 3674:     }
 3675:     if (foundsomething==0) {
 3676: 	alert('$error2');
 3677: 	return;
 3678:     }
 3679:     vf.submit();
 3680:   }
 3681:   function flip(vf,tf) {
 3682:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3683:     var i;
 3684:     for (i=0;i<=vf.nfields.value;i++) {
 3685:       //can not pick the same destination field for both name and domain
 3686:       if (((i ==0)||(i ==1)) && 
 3687:           ((tf==0)||(tf==1)) && 
 3688:           (i!=tf) &&
 3689:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3690:         eval('vf.f'+i+'.selectedIndex=0;')
 3691:       }
 3692:     }
 3693:   }
 3694: ENDPICK
 3695: }
 3696: 
 3697: sub csvupload_javascript_forward_associate {
 3698:     my $error1=&mt('You need to specify the username or ID');
 3699:     my $error2=&mt('You need to specify at least one grading field');
 3700:   return(<<ENDPICK);
 3701:   function verify(vf) {
 3702:     var foundsomething=0;
 3703:     var founduname=0;
 3704:     var foundID=0;
 3705:     for (i=0;i<=vf.nfields.value;i++) {
 3706:       tw=eval('vf.f'+i+'.selectedIndex');
 3707:       if (tw==1) { foundID=1; }
 3708:       if (tw==2) { founduname=1; }
 3709:       if (tw>3) { foundsomething=1; }
 3710:     }
 3711:     if (founduname==0 && foundID==0) {
 3712: 	alert('$error1');
 3713: 	return;
 3714:     }
 3715:     if (foundsomething==0) {
 3716: 	alert('$error2');
 3717: 	return;
 3718:     }
 3719:     vf.submit();
 3720:   }
 3721:   function flip(vf,tf) {
 3722:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3723:     var i;
 3724:     //can not pick the same destination field twice
 3725:     for (i=0;i<=vf.nfields.value;i++) {
 3726:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3727:         eval('vf.f'+i+'.selectedIndex=0;')
 3728:       }
 3729:     }
 3730:   }
 3731: ENDPICK
 3732: }
 3733: 
 3734: sub csvuploadmap_header {
 3735:     my ($request,$symb,$datatoken,$distotal)= @_;
 3736:     my $javascript;
 3737:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3738: 	$javascript=&csvupload_javascript_reverse_associate();
 3739:     } else {
 3740: 	$javascript=&csvupload_javascript_forward_associate();
 3741:     }
 3742: 
 3743:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3744:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3745:     my $ignore=&mt('Ignore First Line');
 3746:     $symb = &Apache::lonenc::check_encrypt($symb);
 3747:     $request->print(<<ENDPICK);
 3748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3749: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3750: $result
 3751: <hr />
 3752: <h3>Identify fields</h3>
 3753: Total number of records found in file: $distotal <hr />
 3754: Enter as many fields as you can. The system will inform you and bring you back
 3755: to this page if the data selected is insufficient to run your class.<hr />
 3756: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3757: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3758: <input type="hidden" name="associate"  value="" />
 3759: <input type="hidden" name="phase"      value="three" />
 3760: <input type="hidden" name="datatoken"  value="$datatoken" />
 3761: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3762: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3763: <input type="hidden" name="upfile_associate" 
 3764:                                        value="$env{'form.upfile_associate'}" />
 3765: <input type="hidden" name="symb"       value="$symb" />
 3766: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3767: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3768: <input type="hidden" name="command"    value="csvuploadoptions" />
 3769: <hr />
 3770: <script type="text/javascript" language="Javascript">
 3771: $javascript
 3772: </script>
 3773: ENDPICK
 3774:     return '';
 3775: 
 3776: }
 3777: 
 3778: sub csvupload_fields {
 3779:     my ($symb) = @_;
 3780:     my (@parts) = &getpartlist($symb);
 3781:     my @fields=(['ID','Student ID'],
 3782: 		['username','Student Username'],
 3783: 		['domain','Student Domain']);
 3784:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3785:     foreach my $part (sort(@parts)) {
 3786: 	my @datum;
 3787: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3788: 	my $name=$part;
 3789: 	if  (!$display) { $display = $name; }
 3790: 	@datum=($name,$display);
 3791: 	if ($name=~/^stores_(.*)_awarded/) {
 3792: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3793: 	}
 3794: 	push(@fields,\@datum);
 3795:     }
 3796:     return (@fields);
 3797: }
 3798: 
 3799: sub csvuploadmap_footer {
 3800:     my ($request,$i,$keyfields) =@_;
 3801:     $request->print(<<ENDPICK);
 3802: </table>
 3803: <input type="hidden" name="nfields" value="$i" />
 3804: <input type="hidden" name="keyfields" value="$keyfields" />
 3805: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3806: </form>
 3807: ENDPICK
 3808: }
 3809: 
 3810: sub checkforfile_js {
 3811:     my $result =<<CSVFORMJS;
 3812: <script type="text/javascript" language="javascript">
 3813:     function checkUpload(formname) {
 3814: 	if (formname.upfile.value == "") {
 3815: 	    alert("Please use the browse button to select a file from your local directory.");
 3816: 	    return false;
 3817: 	}
 3818: 	formname.submit();
 3819:     }
 3820:     </script>
 3821: CSVFORMJS
 3822:     return $result;
 3823: }
 3824: 
 3825: sub upcsvScores_form {
 3826:     my ($request) = shift;
 3827:     my ($symb)=&get_symb($request);
 3828:     if (!$symb) {return '';}
 3829:     my $result=&checkforfile_js();
 3830:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3831:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3832:     $result.=$table;
 3833:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3834:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3835:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3836: 	'.</b></td></tr>'."\n";
 3837:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3838:     my $upload=&mt("Upload Scores");
 3839:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3840:     my $ignore=&mt('Ignore First Line');
 3841:     $symb = &Apache::lonenc::check_encrypt($symb);
 3842:     $result.=<<ENDUPFORM;
 3843: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3844: <input type="hidden" name="symb" value="$symb" />
 3845: <input type="hidden" name="command" value="csvuploadmap" />
 3846: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3847: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3848: $upfile_select
 3849: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3850: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3851: </form>
 3852: ENDUPFORM
 3853:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3854:                            &mt("How do I create a CSV file from a spreadsheet"))
 3855:     .'</td></tr></table>'."\n";
 3856:     $result.='</td></tr></table><br /><br />'."\n";
 3857:     $result.=&show_grading_menu_form($symb);
 3858:     return $result;
 3859: }
 3860: 
 3861: 
 3862: sub csvuploadmap {
 3863:     my ($request)= @_;
 3864:     my ($symb)=&get_symb($request);
 3865:     if (!$symb) {return '';}
 3866: 
 3867:     my $datatoken;
 3868:     if (!$env{'form.datatoken'}) {
 3869: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3870:     } else {
 3871: 	$datatoken=$env{'form.datatoken'};
 3872: 	&Apache::loncommon::load_tmp_file($request);
 3873:     }
 3874:     my @records=&Apache::loncommon::upfile_record_sep();
 3875:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3876:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3877:     my ($i,$keyfields);
 3878:     if (@records) {
 3879: 	my @fields=&csvupload_fields($symb);
 3880: 
 3881: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3882: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3883: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3884: 							  \@fields);
 3885: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3886: 	    chop($keyfields);
 3887: 	} else {
 3888: 	    unshift(@fields,['none','']);
 3889: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3890: 							    \@fields);
 3891:             foreach my $rec (@records) {
 3892:                 my %temp = &Apache::loncommon::record_sep($rec);
 3893:                 if (%temp) {
 3894:                     $keyfields=join(',',sort(keys(%temp)));
 3895:                     last;
 3896:                 }
 3897:             }
 3898: 	}
 3899:     }
 3900:     &csvuploadmap_footer($request,$i,$keyfields);
 3901:     $request->print(&show_grading_menu_form($symb));
 3902: 
 3903:     return '';
 3904: }
 3905: 
 3906: sub csvuploadoptions {
 3907:     my ($request)= @_;
 3908:     my ($symb)=&get_symb($request);
 3909:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3910:     my $ignore=&mt('Ignore First Line');
 3911:     $request->print(<<ENDPICK);
 3912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3913: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3914: <input type="hidden" name="command"    value="csvuploadassign" />
 3915: <!--
 3916: <p>
 3917: <label>
 3918:    <input type="checkbox" name="show_full_results" />
 3919:    Show a table of all changes
 3920: </label>
 3921: </p>
 3922: -->
 3923: <p>
 3924: <label>
 3925:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3926:    Overwrite any existing score
 3927: </label>
 3928: </p>
 3929: ENDPICK
 3930:     my %fields=&get_fields();
 3931:     if (!defined($fields{'domain'})) {
 3932: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3933: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3934:     }
 3935:     foreach my $key (sort(keys(%env))) {
 3936: 	if ($key !~ /^form\.(.*)$/) { next; }
 3937: 	my $cleankey=$1;
 3938: 	if ($cleankey eq 'command') { next; }
 3939: 	$request->print('<input type="hidden" name="'.$cleankey.
 3940: 			'"  value="'.$env{$key}.'" />'."\n");
 3941:     }
 3942:     # FIXME do a check for any duplicated user ids...
 3943:     # FIXME do a check for any invalid user ids?...
 3944:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3945: <hr /></form>'."\n");
 3946:     $request->print(&show_grading_menu_form($symb));
 3947:     return '';
 3948: }
 3949: 
 3950: sub get_fields {
 3951:     my %fields;
 3952:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3953:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3954: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3955: 	    if ($env{'form.f'.$i} ne 'none') {
 3956: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3957: 	    }
 3958: 	} else {
 3959: 	    if ($env{'form.f'.$i} ne 'none') {
 3960: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3961: 	    }
 3962: 	}
 3963:     }
 3964:     return %fields;
 3965: }
 3966: 
 3967: sub csvuploadassign {
 3968:     my ($request)= @_;
 3969:     my ($symb)=&get_symb($request);
 3970:     if (!$symb) {return '';}
 3971:     my $error_msg = '';
 3972:     &Apache::loncommon::load_tmp_file($request);
 3973:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3974:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3975:     my %fields=&get_fields();
 3976:     $request->print('<h3>Assigning Grades</h3>');
 3977:     my $courseid=$env{'request.course.id'};
 3978:     my ($classlist) = &getclasslist('all',0);
 3979:     my @notallowed;
 3980:     my @skipped;
 3981:     my $countdone=0;
 3982:     foreach my $grade (@gradedata) {
 3983: 	my %entries=&Apache::loncommon::record_sep($grade);
 3984: 	my $domain;
 3985: 	if ($entries{$fields{'domain'}}) {
 3986: 	    $domain=$entries{$fields{'domain'}};
 3987: 	} else {
 3988: 	    $domain=$env{'form.default_domain'};
 3989: 	}
 3990: 	$domain=~s/\s//g;
 3991: 	my $username=$entries{$fields{'username'}};
 3992: 	$username=~s/\s//g;
 3993: 	if (!$username) {
 3994: 	    my $id=$entries{$fields{'ID'}};
 3995: 	    $id=~s/\s//g;
 3996: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3997: 	    $username=$ids{$id};
 3998: 	}
 3999: 	if (!exists($$classlist{"$username:$domain"})) {
 4000: 	    my $id=$entries{$fields{'ID'}};
 4001: 	    $id=~s/\s//g;
 4002: 	    if ($id) {
 4003: 		push(@skipped,"$id:$domain");
 4004: 	    } else {
 4005: 		push(@skipped,"$username:$domain");
 4006: 	    }
 4007: 	    next;
 4008: 	}
 4009: 	my $usec=$classlist->{"$username:$domain"}[5];
 4010: 	if (!&canmodify($usec)) {
 4011: 	    push(@notallowed,"$username:$domain");
 4012: 	    next;
 4013: 	}
 4014: 	my %points;
 4015: 	my %grades;
 4016: 	foreach my $dest (keys(%fields)) {
 4017: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4018: 		$dest eq 'domain') { next; }
 4019: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4020: 	    if ($dest=~/stores_(.*)_points/) {
 4021: 		my $part=$1;
 4022: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4023: 					      $symb,$domain,$username);
 4024:                 if ($wgt) {
 4025:                     $entries{$fields{$dest}}=~s/\s//g;
 4026:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4027:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4028:                                           : 'correct_by_override';
 4029:                     $grades{"resource.$part.awarded"}=$pcr;
 4030:                     $grades{"resource.$part.solved"}=$award;
 4031:                     $points{$part}=1;
 4032:                 } else {
 4033:                     $error_msg = "<br />" .
 4034:                         &mt("Some point values were assigned"
 4035:                             ." for problems with a weight "
 4036:                             ."of zero. These values were "
 4037:                             ."ignored.");
 4038:                 }
 4039: 	    } else {
 4040: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4041: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4042: 		my $store_key=$dest;
 4043: 		$store_key=~s/^stores/resource/;
 4044: 		$store_key=~s/_/\./g;
 4045: 		$grades{$store_key}=$entries{$fields{$dest}};
 4046: 	    }
 4047: 	}
 4048: 	if (! %grades) { 
 4049:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4050:         } else {
 4051: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4052: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4053: 					   $env{'request.course.id'},
 4054: 					   $domain,$username);
 4055: 	   if ($result eq 'ok') {
 4056: 	      $request->print('.');
 4057: 	   } else {
 4058: 	      $request->print("<p><span class=\"LC_error\">".
 4059:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4060:                                   "$username:$domain",$result)."</span></p>");
 4061: 	   }
 4062: 	   $request->rflush();
 4063: 	   $countdone++;
 4064:         }
 4065:     }
 4066:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4067:     if (@skipped) {
 4068: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4069: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4070:     }
 4071:     if (@notallowed) {
 4072: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4073: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4074:     }
 4075:     $request->print("<br />\n");
 4076:     $request->print(&show_grading_menu_form($symb));
 4077:     return $error_msg;
 4078: }
 4079: #------------- end of section for handling csv file upload ---------
 4080: #
 4081: #-------------------------------------------------------------------
 4082: #
 4083: #-------------- Next few routines handle grading by page/sequence
 4084: #
 4085: #--- Select a page/sequence and a student to grade
 4086: sub pickStudentPage {
 4087:     my ($request) = shift;
 4088: 
 4089:     $request->print(<<LISTJAVASCRIPT);
 4090: <script type="text/javascript" language="javascript">
 4091: 
 4092: function checkPickOne(formname) {
 4093:     if (radioSelection(formname.student) == null) {
 4094: 	alert("Please select the student you wish to grade.");
 4095: 	return;
 4096:     }
 4097:     ptr = pullDownSelection(formname.selectpage);
 4098:     formname.page.value = formname["page"+ptr].value;
 4099:     formname.title.value = formname["title"+ptr].value;
 4100:     formname.submit();
 4101: }
 4102: 
 4103: </script>
 4104: LISTJAVASCRIPT
 4105:     &commonJSfunctions($request);
 4106:     my ($symb) = &get_symb($request);
 4107:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4108:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4109:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4110: 
 4111:     my $result='<h3><span class="LC_info">&nbsp;'.
 4112: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4113: 
 4114:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4115:     my ($titles,$symbx) = &getSymbMap();
 4116:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4117: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4118: #    my $type=($curpage =~ /\.(page|sequence)/);
 4119:     my $select = '<select name="selectpage">'."\n";
 4120:     my $ctr=0;
 4121:     foreach (@$titles) {
 4122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4123: 	$select.='<option value="'.$ctr.'" '.
 4124: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4125: 	    '>'.$showtitle.'</option>'."\n";
 4126: 	$ctr++;
 4127:     }
 4128:     $select.= '</select>';
 4129:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4130: 
 4131:     $ctr=0;
 4132:     foreach (@$titles) {
 4133: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4134: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4135: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4136: 	$ctr++;
 4137:     }
 4138:     $result.='<input type="hidden" name="page" />'."\n".
 4139: 	'<input type="hidden" name="title" />'."\n";
 4140: 
 4141:     my $options =
 4142: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4143: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4144:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4145: 
 4146:     $options =
 4147: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4148: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4149: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4150:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4151:     
 4152:     $result.=&build_section_inputs();
 4153:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4154:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4155: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4156: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4157: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4158: 
 4159:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4160: 			  '<input type="text" name="CODE" value="" />').
 4161: 			      '<br />'."\n";
 4162: 
 4163:     $result.='&nbsp;<input type="button" '.
 4164: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4165: 
 4166:     $request->print($result);
 4167: 
 4168:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4169: 	&Apache::loncommon::start_data_table().
 4170: 	&Apache::loncommon::start_data_table_header_row().
 4171: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4172: 	'<th>'.&nameUserString('header').'</th>'.
 4173: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4174: 	'<th>'.&nameUserString('header').'</th>'.
 4175: 	&Apache::loncommon::end_data_table_header_row();
 4176:  
 4177:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4178:     my $ptr = 1;
 4179:     foreach my $student (sort 
 4180: 			 {
 4181: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4182: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4183: 			     }
 4184: 			     return $a cmp $b;
 4185: 			 } (keys(%$fullname))) {
 4186: 	my ($uname,$udom) = split(/:/,$student);
 4187: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4188:                                   : '</td>');
 4189: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4190: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4191: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4192: 	$studentTable.=
 4193: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4194:                          : '');
 4195: 	$ptr++;
 4196:     }
 4197:     if ($ptr%2 == 0) {
 4198: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4199: 	    &Apache::loncommon::end_data_table_row();
 4200:     }
 4201:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4202:     $studentTable.='<input type="button" '.
 4203: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4204: 
 4205:     $studentTable.=&show_grading_menu_form($symb);
 4206:     $request->print($studentTable);
 4207: 
 4208:     return '';
 4209: }
 4210: 
 4211: sub getSymbMap {
 4212:     my $navmap = Apache::lonnavmaps::navmap->new();
 4213: 
 4214:     my %symbx = ();
 4215:     my @titles = ();
 4216:     my $minder = 0;
 4217: 
 4218:     # Gather every sequence that has problems.
 4219:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4220: 					       1,0,1);
 4221:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4222: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4223: 	    my $title = $minder.'.'.
 4224: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4225: 	    push(@titles, $title); # minder in case two titles are identical
 4226: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4227: 	    $minder++;
 4228: 	}
 4229:     }
 4230:     return \@titles,\%symbx;
 4231: }
 4232: 
 4233: #
 4234: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4235: sub displayPage {
 4236:     my ($request) = shift;
 4237: 
 4238:     my ($symb) = &get_symb($request);
 4239:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4240:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4241:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4242:     my $pageTitle = $env{'form.page'};
 4243:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4244:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4245:     my $usec=$classlist->{$env{'form.student'}}[5];
 4246: 
 4247:     #need to make sure we have the correct data for later EXT calls, 
 4248:     #thus invalidate the cache
 4249:     &Apache::lonnet::devalidatecourseresdata(
 4250:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4251:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4252:     &Apache::lonnet::clear_EXT_cache_status();
 4253: 
 4254:     if (!&canview($usec)) {
 4255: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4256: 	$request->print(&show_grading_menu_form($symb));
 4257: 	return;
 4258:     }
 4259:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4260:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4261: 	'</h3>'."\n";
 4262:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4263:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4264: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4265:     } else {
 4266: 	delete($env{'form.CODE'});
 4267:     }
 4268:     &sub_page_js($request);
 4269:     $request->print($result);
 4270: 
 4271:     my $navmap = Apache::lonnavmaps::navmap->new();
 4272:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4273:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4274:     if (!$map) {
 4275: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4276: 	$request->print(&show_grading_menu_form($symb));
 4277: 	return; 
 4278:     }
 4279:     my $iterator = $navmap->getIterator($map->map_start(),
 4280: 					$map->map_finish());
 4281: 
 4282:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4283: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4284: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4285: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4286: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4287: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4288: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4289: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4290: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4291: 
 4292:     if (defined($env{'form.CODE'})) {
 4293: 	$studentTable.=
 4294: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4295:     }
 4296:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4297: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4298: 
 4299:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4300: 	&Apache::loncommon::start_data_table().
 4301: 	&Apache::loncommon::start_data_table_header_row().
 4302: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4303: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4304: 	&Apache::loncommon::end_data_table_header_row();
 4305: 
 4306:     &Apache::lonxml::clear_problem_counter();
 4307:     my ($depth,$question,$prob) = (1,1,1);
 4308:     $iterator->next(); # skip the first BEGIN_MAP
 4309:     my $curRes = $iterator->next(); # for "current resource"
 4310:     while ($depth > 0) {
 4311:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4312:         if($curRes == $iterator->END_MAP) { $depth--; }
 4313: 
 4314:         if (ref($curRes) && $curRes->is_problem()) {
 4315: 	    my $parts = $curRes->parts();
 4316:             my $title = $curRes->compTitle();
 4317: 	    my $symbx = $curRes->symb();
 4318: 	    $studentTable.=
 4319: 		&Apache::loncommon::start_data_table_row().
 4320: 		'<td align="center" valign="top" >'.$prob.
 4321: 		(scalar(@{$parts}) == 1 ? '' 
 4322: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4323: 							scalar(@{$parts}))
 4324: 		 ).
 4325: 		 '</td>';
 4326: 	    $studentTable.='<td valign="top">';
 4327: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4328: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4329: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4330: 					     undef,'both',\%form);
 4331: 	    } else {
 4332: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4333: 		$companswer =~ s|<form(.*?)>||g;
 4334: 		$companswer =~ s|</form>||g;
 4335: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4336: #		    $companswer =~ s/$1/ /ms;
 4337: #		    $request->print('match='.$1."<br />\n");
 4338: #		}
 4339: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4340: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4341: 	    }
 4342: 
 4343: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4344: 
 4345: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4346: 		if ($record{'version'} eq '') {
 4347: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4348: 		} else {
 4349: 		    my %responseType = ();
 4350: 		    foreach my $partid (@{$parts}) {
 4351: 			my @responseIds =$curRes->responseIds($partid);
 4352: 			my @responseType =$curRes->responseType($partid);
 4353: 			my %responseIds;
 4354: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4355: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4356: 			}
 4357: 			$responseType{$partid} = \%responseIds;
 4358: 		    }
 4359: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4360: 
 4361: 		}
 4362: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4363: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4364: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4365: 									$env{'request.course.id'},
 4366: 									'','.submission');
 4367:  
 4368: 	    }
 4369: 	    if (&canmodify($usec)) {
 4370: 		foreach my $partid (@{$parts}) {
 4371: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4372: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4373: 		    $question++;
 4374: 		}
 4375: 		$prob++;
 4376: 	    }
 4377: 	    $studentTable.='</td></tr>';
 4378: 
 4379: 	}
 4380:         $curRes = $iterator->next();
 4381:     }
 4382: 
 4383:     $studentTable.='</table>'."\n".
 4384: 	'<input type="button" value="'.&mt('Save').'" '.
 4385: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4386: 	'</form>'."\n";
 4387:     $studentTable.=&show_grading_menu_form($symb);
 4388:     $request->print($studentTable);
 4389: 
 4390:     return '';
 4391: }
 4392: 
 4393: sub displaySubByDates {
 4394:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4395:     my $isCODE=0;
 4396:     my $isTask = ($symb =~/\.task$/);
 4397:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4398:     my $studentTable=&Apache::loncommon::start_data_table().
 4399: 	&Apache::loncommon::start_data_table_header_row().
 4400: 	'<th>'.&mt('Date/Time').'</th>'.
 4401: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4402: 	'<th>'.&mt('Submission').'</th>'.
 4403: 	'<th>'.&mt('Status').'</th>'.
 4404: 	&Apache::loncommon::end_data_table_header_row();
 4405:     my ($version);
 4406:     my %mark;
 4407:     my %orders;
 4408:     $mark{'correct_by_student'} = $checkIcon;
 4409:     if (!exists($$record{'1:timestamp'})) {
 4410: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4411:     }
 4412: 
 4413:     my $interaction;
 4414:     my $no_increment = 1;
 4415:     for ($version=1;$version<=$$record{'version'};$version++) {
 4416: 	my $timestamp = 
 4417: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4418: 	if (exists($$record{$version.':resource.0.version'})) {
 4419: 	    $interaction = $$record{$version.':resource.0.version'};
 4420: 	}
 4421: 
 4422: 	my $where = ($isTask ? "$version:resource.$interaction"
 4423: 		             : "$version:resource");
 4424: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4425: 	    '<td>'.$timestamp.'</td>';
 4426: 	if ($isCODE) {
 4427: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4428: 	}
 4429: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4430: 	my @displaySub = ();
 4431: 	foreach my $partid (@{$parts}) {
 4432: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4433: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4434: 	    
 4435: 
 4436: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4437: 	    my $display_part=&get_display_part($partid,$symb);
 4438: 	    foreach my $matchKey (@matchKey) {
 4439: 		if (exists($$record{$version.':'.$matchKey}) &&
 4440: 		    $$record{$version.':'.$matchKey} ne '') {
 4441: 
 4442: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4443: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4444: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4445: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4446: 			$responseId.')</span>&nbsp;<b>';
 4447: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4448: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4449: 		    } else {
 4450: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4451: 					    $$record{"$where.$partid.tries"});
 4452: 		    }
 4453: 		    my $responseType=($isTask ? 'Task'
 4454:                                               : $responseType->{$partid}->{$responseId});
 4455: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4456: 		    if (!exists($orders{$partid}->{$responseId})) {
 4457: 			$orders{$partid}->{$responseId}=
 4458: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4459:                                        $no_increment);
 4460: 		    }
 4461: 		    $displaySub[0].='</b>&nbsp; '.
 4462: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4463: 		}
 4464: 	    }
 4465: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4466: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4467: 				    $$record{"$where.$partid.checkedin"},
 4468: 				    $$record{"$where.$partid.checkedin.slot"}).
 4469: 					'<br />';
 4470: 	    }
 4471: 	    if (exists $$record{"$where.$partid.award"}) {
 4472: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4473: 		    lc($$record{"$where.$partid.award"}).' '.
 4474: 		    $mark{$$record{"$where.$partid.solved"}}.
 4475: 		    '<br />';
 4476: 	    }
 4477: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4478: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4479: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4480: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4481: 		$displaySub[2].=
 4482: 		    $$record{"$version:resource.$partid.regrader"}.
 4483: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4484: 	    }
 4485: 	}
 4486: 	# needed because old essay regrader has not parts info
 4487: 	if (exists $$record{"$version:resource.regrader"}) {
 4488: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4489: 	}
 4490: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4491: 	if ($displaySub[2]) {
 4492: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4493: 	}
 4494: 	$studentTable.='&nbsp;</td>'.
 4495: 	    &Apache::loncommon::end_data_table_row();
 4496:     }
 4497:     $studentTable.=&Apache::loncommon::end_data_table();
 4498:     return $studentTable;
 4499: }
 4500: 
 4501: sub updateGradeByPage {
 4502:     my ($request) = shift;
 4503: 
 4504:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4505:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4506:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4507:     my $pageTitle = $env{'form.page'};
 4508:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4509:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4510:     my $usec=$classlist->{$env{'form.student'}}[5];
 4511:     if (!&canmodify($usec)) {
 4512: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4513: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4514: 	return;
 4515:     }
 4516:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4517:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4518: 	'</h3>'."\n";
 4519: 
 4520:     $request->print($result);
 4521: 
 4522:     my $navmap = Apache::lonnavmaps::navmap->new();
 4523:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4524:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4525:     if (!$map) {
 4526: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl').'</span>');
 4527: 	my ($symb)=&get_symb($request);
 4528: 	$request->print(&show_grading_menu_form($symb));
 4529: 	return; 
 4530:     }
 4531:     my $iterator = $navmap->getIterator($map->map_start(),
 4532: 					$map->map_finish());
 4533: 
 4534:     my $studentTable=
 4535: 	&Apache::loncommon::start_data_table().
 4536: 	&Apache::loncommon::start_data_table_header_row().
 4537: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4538: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4539: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4540: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4541: 	&Apache::loncommon::end_data_table_header_row();
 4542: 
 4543:     $iterator->next(); # skip the first BEGIN_MAP
 4544:     my $curRes = $iterator->next(); # for "current resource"
 4545:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4546:     while ($depth > 0) {
 4547:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4548:         if($curRes == $iterator->END_MAP) { $depth--; }
 4549: 
 4550:         if (ref($curRes) && $curRes->is_problem()) {
 4551: 	    my $parts = $curRes->parts();
 4552:             my $title = $curRes->compTitle();
 4553: 	    my $symbx = $curRes->symb();
 4554: 	    $studentTable.=
 4555: 		&Apache::loncommon::start_data_table_row().
 4556: 		'<td align="center" valign="top" >'.$prob.
 4557: 		(scalar(@{$parts}) == 1 ? '' 
 4558:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4559: 		.')').'</td>';
 4560: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4561: 
 4562: 	    my %newrecord=();
 4563: 	    my @displayPts=();
 4564:             my %aggregate = ();
 4565:             my $aggregateflag = 0;
 4566: 	    foreach my $partid (@{$parts}) {
 4567: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4568: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4569: 
 4570: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4571: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4572: 		my $partial = $newpts/$wgt;
 4573: 		my $score;
 4574: 		if ($partial > 0) {
 4575: 		    $score = 'correct_by_override';
 4576: 		} elsif ($newpts ne '') { #empty is taken as 0
 4577: 		    $score = 'incorrect_by_override';
 4578: 		}
 4579: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4580: 		if ($dropMenu eq 'excused') {
 4581: 		    $partial = '';
 4582: 		    $score = 'excused';
 4583: 		} elsif ($dropMenu eq 'reset status'
 4584: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4585: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4586: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4587: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4588: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4589: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4590: 		    $changeflag++;
 4591: 		    $newpts = '';
 4592:                     
 4593:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4594:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4595:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4596:                     if ($aggtries > 0) {
 4597:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4598:                         $aggregateflag = 1;
 4599:                     }
 4600: 		}
 4601: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4602: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4603: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4604: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4605: 		    '&nbsp;<br />';
 4606: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4607: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4608: 		    '&nbsp;<br />';
 4609: 		$question++;
 4610: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4611: 
 4612: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4613: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4614: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4615: 		    if (scalar(keys(%newrecord)) > 0);
 4616: 
 4617: 		$changeflag++;
 4618: 	    }
 4619: 	    if (scalar(keys(%newrecord)) > 0) {
 4620: 		my %record = 
 4621: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4622: 					     $udom,$uname);
 4623: 
 4624: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4625: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4626: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4627: 		    $newrecord{'resource.CODE'} = '';
 4628: 		}
 4629: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4630: 					$udom,$uname);
 4631: 		%record = &Apache::lonnet::restore($symbx,
 4632: 						   $env{'request.course.id'},
 4633: 						   $udom,$uname);
 4634: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4635: 					     $cdom,$cnum,$udom,$uname);
 4636: 	    }
 4637: 	    
 4638:             if ($aggregateflag) {
 4639:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4640:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4641:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4642:             }
 4643: 
 4644: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4645: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4646: 		&Apache::loncommon::end_data_table_row();
 4647: 
 4648: 	    $prob++;
 4649: 	}
 4650:         $curRes = $iterator->next();
 4651:     }
 4652: 
 4653:     $studentTable.=&Apache::loncommon::end_data_table();
 4654:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4655:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4656: 		  &mt('The scores were changed for [quant,_1,problem].',
 4657: 		  $changeflag));
 4658:     $request->print($grademsg.$studentTable);
 4659: 
 4660:     return '';
 4661: }
 4662: 
 4663: #-------- end of section for handling grading by page/sequence ---------
 4664: #
 4665: #-------------------------------------------------------------------
 4666: 
 4667: #--------------------Scantron Grading-----------------------------------
 4668: #
 4669: #------ start of section for handling grading by page/sequence ---------
 4670: 
 4671: =pod
 4672: 
 4673: =head1 Bubble sheet grading routines
 4674: 
 4675:   For this documentation:
 4676: 
 4677:    'scanline' refers to the full line of characters
 4678:    from the file that we are parsing that represents one entire sheet
 4679: 
 4680:    'bubble line' refers to the data
 4681:    representing the line of bubbles that are on the physical bubble sheet
 4682: 
 4683: 
 4684: The overall process is that a scanned in bubble sheet data is uploaded
 4685: into a course. When a user wants to grade, they select a
 4686: sequence/folder of resources, a file of bubble sheet info, and pick
 4687: one of the predefined configurations for what each scanline looks
 4688: like.
 4689: 
 4690: Next each scanline is checked for any errors of either 'missing
 4691: bubbles' (it's an error because it may have been mis-scanned
 4692: because too light bubbling), 'double bubble' (each bubble line should
 4693: have no more that one letter picked), invalid or duplicated CODE,
 4694: invalid student ID
 4695: 
 4696: If the CODE option is used that determines the randomization of the
 4697: homework problems, either way the student ID is looked up into a
 4698: username:domain.
 4699: 
 4700: During the validation phase the instructor can choose to skip scanlines. 
 4701: 
 4702: After the validation phase, there are now 3 bubble sheet files
 4703: 
 4704:   scantron_original_filename (unmodified original file)
 4705:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4706:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4707: 
 4708: Also there is a separate hash nohist_scantrondata that contains extra
 4709: correction information that isn't representable in the bubble sheet
 4710: file (see &scantron_getfile() for more information)
 4711: 
 4712: After all scanlines are either valid, marked as valid or skipped, then
 4713: foreach line foreach problem in the picked sequence, an ssi request is
 4714: made that simulates a user submitting their selected letter(s) against
 4715: the homework problem.
 4716: 
 4717: =over 4
 4718: 
 4719: 
 4720: 
 4721: =item defaultFormData
 4722: 
 4723:   Returns html hidden inputs used to hold context/default values.
 4724: 
 4725:  Arguments:
 4726:   $symb - $symb of the current resource 
 4727: 
 4728: =cut
 4729: 
 4730: sub defaultFormData {
 4731:     my ($symb)=@_;
 4732:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4733:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4734:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4735: }
 4736: 
 4737: 
 4738: =pod 
 4739: 
 4740: =item getSequenceDropDown
 4741: 
 4742:    Return html dropdown of possible sequences to grade
 4743:  
 4744:  Arguments:
 4745:    $symb - $symb of the current resource 
 4746: 
 4747: =cut
 4748: 
 4749: sub getSequenceDropDown {
 4750:     my ($symb)=@_;
 4751:     my $result='<select name="selectpage">'."\n";
 4752:     my ($titles,$symbx) = &getSymbMap();
 4753:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4754:     my $ctr=0;
 4755:     foreach (@$titles) {
 4756: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4757: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4758: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4759: 	    '>'.$showtitle.'</option>'."\n";
 4760: 	$ctr++;
 4761:     }
 4762:     $result.= '</select>';
 4763:     return $result;
 4764: }
 4765: 
 4766: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4767:                                    # index is "symb.part_id"
 4768: 
 4769: my %first_bubble_line;             # First bubble line no. for each bubble.
 4770: 
 4771: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4772:                                    # matchresponse or rankresponse, where 
 4773:                                    # an individual response can have multiple 
 4774:                                    # lines
 4775: 
 4776: my %responsetype_per_response;     # responsetype for each response
 4777: 
 4778: # Save and restore the bubble lines array to the form env.
 4779: 
 4780: 
 4781: sub save_bubble_lines {
 4782:     foreach my $line (keys(%bubble_lines_per_response)) {
 4783: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4784: 	$env{"form.scantron.first_bubble_line.$line"} =
 4785: 	    $first_bubble_line{$line};
 4786:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4787:             $subdivided_bubble_lines{$line};
 4788:         $env{"form.scantron.responsetype.$line"} =
 4789:             $responsetype_per_response{$line};
 4790:     }
 4791: }
 4792: 
 4793: 
 4794: sub restore_bubble_lines {
 4795:     my $line = 0;
 4796:     %bubble_lines_per_response = ();
 4797:     while ($env{"form.scantron.bubblelines.$line"}) {
 4798: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4799: 	$bubble_lines_per_response{$line} = $value;
 4800: 	$first_bubble_line{$line}  =
 4801: 	    $env{"form.scantron.first_bubble_line.$line"};
 4802:         $subdivided_bubble_lines{$line} =
 4803:             $env{"form.scantron.sub_bubblelines.$line"};
 4804:         $responsetype_per_response{$line} =
 4805:             $env{"form.scantron.responsetype.$line"};
 4806: 	$line++;
 4807:     }
 4808: 
 4809: }
 4810: 
 4811: #  Given the parsed scanline, get the response for 
 4812: #  'answer' number n:
 4813: 
 4814: sub get_response_bubbles {
 4815:     my ($parsed_line, $response)  = @_;
 4816: 
 4817: 
 4818:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4819:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4820:     
 4821:     my $selected = "";
 4822: 
 4823:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4824: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4825: 	$bubble_line++;
 4826:     }
 4827:     return $selected;
 4828: }
 4829: 
 4830: =pod 
 4831: 
 4832: =item scantron_filenames
 4833: 
 4834:    Returns a list of the scantron files in the current course 
 4835: 
 4836: =cut
 4837: 
 4838: sub scantron_filenames {
 4839:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4840:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4841:     my $getpropath = 1;
 4842:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4843:                                        $getpropath);
 4844:     my @possiblenames;
 4845:     foreach my $filename (sort(@files)) {
 4846: 	($filename)=split(/&/,$filename);
 4847: 	if ($filename!~/^scantron_orig_/) { next ; }
 4848: 	$filename=~s/^scantron_orig_//;
 4849: 	push(@possiblenames,$filename);
 4850:     }
 4851:     return @possiblenames;
 4852: }
 4853: 
 4854: =pod 
 4855: 
 4856: =item scantron_uploads
 4857: 
 4858:    Returns  html drop-down list of scantron files in current course.
 4859: 
 4860:  Arguments:
 4861:    $file2grade - filename to set as selected in the dropdown
 4862: 
 4863: =cut
 4864: 
 4865: sub scantron_uploads {
 4866:     my ($file2grade) = @_;
 4867:     my $result=	'<select name="scantron_selectfile">';
 4868:     $result.="<option></option>";
 4869:     foreach my $filename (sort(&scantron_filenames())) {
 4870: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4871:     }
 4872:     $result.="</select>";
 4873:     return $result;
 4874: }
 4875: 
 4876: =pod 
 4877: 
 4878: =item scantron_scantab
 4879: 
 4880:   Returns html drop down of the scantron formats in the scantronformat.tab
 4881:   file.
 4882: 
 4883: =cut
 4884: 
 4885: sub scantron_scantab {
 4886:     my $result='<select name="scantron_format">'."\n";
 4887:     $result.='<option></option>'."\n";
 4888:     my @lines = &get_scantronformat_file();
 4889:     if (@lines > 0) {
 4890:         foreach my $line (@lines) {
 4891:             next if (($line =~ /^\#/) || ($line eq ''));
 4892: 	    my ($name,$descrip)=split(/:/,$line);
 4893: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4894:         }
 4895:     }
 4896:     $result.='</select>'."\n";
 4897:     return $result;
 4898: }
 4899: 
 4900: =pod
 4901: 
 4902: =item get_scantronformat_file
 4903: 
 4904:   Returns an array containing lines from the scantron format file for
 4905:   the domain of the course.
 4906: 
 4907:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4908:   lines are from this file.
 4909: 
 4910:   Otherwise, if a default.tab has been published in RES space by the 
 4911:   domainconfig user, lines are from this file.
 4912: 
 4913:   Otherwise, fall back to getting lines from the legacy file on the
 4914:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4915: 
 4916: =cut
 4917: 
 4918: sub get_scantronformat_file {
 4919:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4920:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4921:     my $gottab = 0;
 4922:     my @lines;
 4923:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4924:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4925:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4926:             if ($formatfile ne '-1') {
 4927:                 @lines = split("\n",$formatfile,-1);
 4928:                 $gottab = 1;
 4929:             }
 4930:         }
 4931:     }
 4932:     if (!$gottab) {
 4933:         my $confname = $cdom.'-domainconfig';
 4934:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4935:         my $formatfile =  &Apache::lonnet::getfile($default);
 4936:         if ($formatfile ne '-1') {
 4937:             @lines = split("\n",$formatfile,-1);
 4938:             $gottab = 1;
 4939:         }
 4940:     }
 4941:     if (!$gottab) {
 4942:         my @domains = &Apache::lonnet::current_machine_domains();
 4943:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4944:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4945:             @lines = <$fh>;
 4946:             close($fh);
 4947:         } else {
 4948:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4949:             @lines = <$fh>;
 4950:             close($fh);
 4951:         }
 4952:     }
 4953:     return @lines;
 4954: }
 4955: 
 4956: =pod 
 4957: 
 4958: =item scantron_CODElist
 4959: 
 4960:   Returns html drop down of the saved CODE lists from current course,
 4961:   generated from earlier printings.
 4962: 
 4963: =cut
 4964: 
 4965: sub scantron_CODElist {
 4966:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4967:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4968:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4969:     my $namechoice='<option></option>';
 4970:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4971: 	if ($name =~ /^error: 2 /) { next; }
 4972: 	if ($name =~ /^type\0/) { next; }
 4973: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4974:     }
 4975:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4976:     return $namechoice;
 4977: }
 4978: 
 4979: =pod 
 4980: 
 4981: =item scantron_CODEunique
 4982: 
 4983:   Returns the html for "Each CODE to be used once" radio.
 4984: 
 4985: =cut
 4986: 
 4987: sub scantron_CODEunique {
 4988:     my $result='<span style="white-space: nowrap;">
 4989:                  <label><input type="radio" name="scantron_CODEunique"
 4990:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4991:                 </span>
 4992:                 <span style="white-space: nowrap;">
 4993:                  <label><input type="radio" name="scantron_CODEunique"
 4994:                         value="no" />'.&mt('No').' </label>
 4995:                 </span>';
 4996:     return $result;
 4997: }
 4998: 
 4999: =pod 
 5000: 
 5001: =item scantron_selectphase
 5002: 
 5003:   Generates the initial screen to start the bubble sheet process.
 5004:   Allows for - starting a grading run.
 5005:              - downloading existing scan data (original, corrected
 5006:                                                 or skipped info)
 5007: 
 5008:              - uploading new scan data
 5009: 
 5010:  Arguments:
 5011:   $r          - The Apache request object
 5012:   $file2grade - name of the file that contain the scanned data to score
 5013: 
 5014: =cut
 5015: 
 5016: sub scantron_selectphase {
 5017:     my ($r,$file2grade) = @_;
 5018:     my ($symb)=&get_symb($r);
 5019:     if (!$symb) {return '';}
 5020:     my $sequence_selector=&getSequenceDropDown($symb);
 5021:     my $default_form_data=&defaultFormData($symb);
 5022:     my $grading_menu_button=&show_grading_menu_form($symb);
 5023:     my $file_selector=&scantron_uploads($file2grade);
 5024:     my $format_selector=&scantron_scantab();
 5025:     my $CODE_selector=&scantron_CODElist();
 5026:     my $CODE_unique=&scantron_CODEunique();
 5027:     my $result;
 5028: 
 5029:     $ssi_error = 0;
 5030: 
 5031:     # Chunk of form to prompt for a file to grade and how:
 5032: 
 5033:     $result.= '
 5034:     <br />
 5035:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5036:     <input type="hidden" name="command" value="scantron_warning" />
 5037:     '.$default_form_data.'
 5038:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5039:        '.&Apache::loncommon::start_data_table_header_row().'
 5040:             <th colspan="2">
 5041:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5042:             </th>
 5043:        '.&Apache::loncommon::end_data_table_header_row().'
 5044:        '.&Apache::loncommon::start_data_table_row().'
 5045:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5046:        '.&Apache::loncommon::end_data_table_row().'
 5047:        '.&Apache::loncommon::start_data_table_row().'
 5048:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5049:        '.&Apache::loncommon::end_data_table_row().'
 5050:        '.&Apache::loncommon::start_data_table_row().'
 5051:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5052:        '.&Apache::loncommon::end_data_table_row().'
 5053:        '.&Apache::loncommon::start_data_table_row().'
 5054:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5055:        '.&Apache::loncommon::end_data_table_row().'
 5056:        '.&Apache::loncommon::start_data_table_row().'
 5057:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5058:        '.&Apache::loncommon::end_data_table_row().'
 5059:        '.&Apache::loncommon::start_data_table_row().'
 5060: 	    <td> '.&mt('Options:').' </td>
 5061:             <td>
 5062: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5063:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5064:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5065: 	    </td>
 5066:        '.&Apache::loncommon::end_data_table_row().'
 5067:        '.&Apache::loncommon::start_data_table_row().'
 5068:             <td colspan="2">
 5069:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5070:             </td>
 5071:        '.&Apache::loncommon::end_data_table_row().'
 5072:     '.&Apache::loncommon::end_data_table().'
 5073:     </form>
 5074: ';
 5075:    
 5076:     $r->print($result);
 5077: 
 5078:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5079:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5080: 
 5081: 	# Chunk of form to prompt for a scantron file upload.
 5082: 
 5083:         $r->print('
 5084:     <br />
 5085:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5086:        '.&Apache::loncommon::start_data_table_header_row().'
 5087:             <th>
 5088:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5089:             </th>
 5090:        '.&Apache::loncommon::end_data_table_header_row().'
 5091:        '.&Apache::loncommon::start_data_table_row().'
 5092:             <td>
 5093: ');
 5094:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5095:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5096:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5097:     $r->print('
 5098:               <script type="text/javascript" language="javascript">
 5099:     function checkUpload(formname) {
 5100: 	if (formname.upfile.value == "") {
 5101: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5102: 	    return false;
 5103: 	}
 5104: 	formname.submit();
 5105:     }
 5106:               </script>
 5107: 
 5108:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5109:                 '.$default_form_data.'
 5110:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5111:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5112:                 <input name="command" value="scantronupload_save" type="hidden" />
 5113:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5114:                 <br />
 5115:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5116:               </form>
 5117: ');
 5118: 
 5119:         $r->print('
 5120:             </td>
 5121:        '.&Apache::loncommon::end_data_table_row().'
 5122:        '.&Apache::loncommon::end_data_table().'
 5123: ');
 5124:     }
 5125: 
 5126:     # Chunk of the form that prompts to view a scoring office file,
 5127:     # corrected file, skipped records in a file.
 5128: 
 5129:     $r->print('
 5130:    <br />
 5131:    <form action="/adm/grades" name="scantron_download">
 5132:      '.$default_form_data.'
 5133:      <input type="hidden" name="command" value="scantron_download" />
 5134:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5135:        '.&Apache::loncommon::start_data_table_header_row().'
 5136:               <th>
 5137:                 &nbsp;'.&mt('Download a scoring office file').'
 5138:               </th>
 5139:        '.&Apache::loncommon::end_data_table_header_row().'
 5140:        '.&Apache::loncommon::start_data_table_row().'
 5141:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5142:                 <br />
 5143:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5144:        '.&Apache::loncommon::end_data_table_row().'
 5145:      '.&Apache::loncommon::end_data_table().'
 5146:    </form>
 5147:    <br />
 5148: ');
 5149: 
 5150:     &Apache::lonpickcode::code_list($r,2);
 5151: 
 5152:     $r>print('<br /><form method="post" name="checkscantron">'.
 5153:              $default_form_data."\n".
 5154:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5155:              &Apache::loncommon::start_data_table_header_row()."\n".
 5156:              '<th colspan="2">
 5157:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5158:              '</th>'."\n".
 5159:               &Apache::loncommon::end_data_table_header_row()."\n".
 5160:               &Apache::loncommon::start_data_table_row()."\n".
 5161:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5162:               '<td> '.$sequence_selector.' </td>'.
 5163:               &Apache::loncommon::end_data_table_row()."\n".
 5164:               &Apache::loncommon::start_data_table_row()."\n".
 5165:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5166:               '<td> '.$file_selector.' </td>'."\n".
 5167:               &Apache::loncommon::end_data_table_row()."\n".
 5168:               &Apache::loncommon::start_data_table_row()."\n".
 5169:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5170:               '<td> '.$format_selector.' </td>'."\n".
 5171:               &Apache::loncommon::end_data_table_row()."\n".
 5172:               &Apache::loncommon::start_data_table_row()."\n".
 5173:               '<td colspan="2">'."\n".
 5174:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5175:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5176:               '</td>'."\n".
 5177:               &Apache::loncommon::end_data_table_row()."\n".
 5178:               &Apache::loncommon::end_data_table()."\n".
 5179:               '</form><br />');
 5180:     $r->print($grading_menu_button);
 5181:     return;
 5182: }
 5183: 
 5184: =pod
 5185: 
 5186: =item get_scantron_config
 5187: 
 5188:    Parse and return the scantron configuration line selected as a
 5189:    hash of configuration file fields.
 5190: 
 5191:  Arguments:
 5192:     which - the name of the configuration to parse from the file.
 5193: 
 5194: 
 5195:  Returns:
 5196:             If the named configuration is not in the file, an empty
 5197:             hash is returned.
 5198:     a hash with the fields
 5199:       name         - internal name for the this configuration setup
 5200:       description  - text to display to operator that describes this config
 5201:       CODElocation - if 0 or the string 'none'
 5202:                           - no CODE exists for this config
 5203:                      if -1 || the string 'letter'
 5204:                           - a CODE exists for this config and is
 5205:                             a string of letters
 5206:                      Unsupported value (but planned for future support)
 5207:                           if a positive integer
 5208:                                - The CODE exists as the first n items from
 5209:                                  the question section of the form
 5210:                           if the string 'number'
 5211:                                - The CODE exists for this config and is
 5212:                                  a string of numbers
 5213:       CODEstart   - (only matter if a CODE exists) column in the line where
 5214:                      the CODE starts
 5215:       CODElength  - length of the CODE
 5216:       IDstart     - column where the student ID number starts
 5217:       IDlength    - length of the student ID info
 5218:       Qstart      - column where the information from the bubbled
 5219:                     'questions' start
 5220:       Qlength     - number of columns comprising a single bubble line from
 5221:                     the sheet. (usually either 1 or 10)
 5222:       Qon         - either a single character representing the character used
 5223:                     to signal a bubble was chosen in the positional setup, or
 5224:                     the string 'letter' if the letter of the chosen bubble is
 5225:                     in the final, or 'number' if a number representing the
 5226:                     chosen bubble is in the file (1->A 0->J)
 5227:       Qoff        - the character used to represent that a bubble was
 5228:                     left blank
 5229:       PaperID     - if the scanning process generates a unique number for each
 5230:                     sheet scanned the column that this ID number starts in
 5231:       PaperIDlength - number of columns that comprise the unique ID number
 5232:                       for the sheet of paper
 5233:       FirstName   - column that the first name starts in
 5234:       FirstNameLength - number of columns that the first name spans
 5235:  
 5236:       LastName    - column that the last name starts in
 5237:       LastNameLength - number of columns that the last name spans
 5238: 
 5239: =cut
 5240: 
 5241: sub get_scantron_config {
 5242:     my ($which) = @_;
 5243:     my @lines = &get_scantronformat_file();
 5244:     my %config;
 5245:     #FIXME probably should move to XML it has already gotten a bit much now
 5246:     foreach my $line (@lines) {
 5247: 	my ($name,$descrip)=split(/:/,$line);
 5248: 	if ($name ne $which ) { next; }
 5249: 	chomp($line);
 5250: 	my @config=split(/:/,$line);
 5251: 	$config{'name'}=$config[0];
 5252: 	$config{'description'}=$config[1];
 5253: 	$config{'CODElocation'}=$config[2];
 5254: 	$config{'CODEstart'}=$config[3];
 5255: 	$config{'CODElength'}=$config[4];
 5256: 	$config{'IDstart'}=$config[5];
 5257: 	$config{'IDlength'}=$config[6];
 5258: 	$config{'Qstart'}=$config[7];
 5259:  	$config{'Qlength'}=$config[8];
 5260: 	$config{'Qoff'}=$config[9];
 5261: 	$config{'Qon'}=$config[10];
 5262: 	$config{'PaperID'}=$config[11];
 5263: 	$config{'PaperIDlength'}=$config[12];
 5264: 	$config{'FirstName'}=$config[13];
 5265: 	$config{'FirstNamelength'}=$config[14];
 5266: 	$config{'LastName'}=$config[15];
 5267: 	$config{'LastNamelength'}=$config[16];
 5268: 	last;
 5269:     }
 5270:     return %config;
 5271: }
 5272: 
 5273: =pod 
 5274: 
 5275: =item username_to_idmap
 5276: 
 5277:     creates a hash keyed by student id with values of the corresponding
 5278:     student username:domain.
 5279: 
 5280:   Arguments:
 5281: 
 5282:     $classlist - reference to the class list hash. This is a hash
 5283:                  keyed by student name:domain  whose elements are references
 5284:                  to arrays containing various chunks of information
 5285:                  about the student. (See loncoursedata for more info).
 5286: 
 5287:   Returns
 5288:     %idmap - the constructed hash
 5289: 
 5290: =cut
 5291: 
 5292: sub username_to_idmap {
 5293:     my ($classlist)= @_;
 5294:     my %idmap;
 5295:     foreach my $student (keys(%$classlist)) {
 5296: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5297: 	    $student;
 5298:     }
 5299:     return %idmap;
 5300: }
 5301: 
 5302: =pod
 5303: 
 5304: =item scantron_fixup_scanline
 5305: 
 5306:    Process a requested correction to a scanline.
 5307: 
 5308:   Arguments:
 5309:     $scantron_config   - hash from &get_scantron_config()
 5310:     $scan_data         - hash of correction information 
 5311:                           (see &scantron_getfile())
 5312:     $line              - existing scanline
 5313:     $whichline         - line number of the passed in scanline
 5314:     $field             - type of change to process 
 5315:                          (either 
 5316:                           'ID'     -> correct the student ID number
 5317:                           'CODE'   -> correct the CODE
 5318:                           'answer' -> fixup the submitted answers)
 5319:     
 5320:    $args               - hash of additional info,
 5321:                           - 'ID' 
 5322:                                'newid' -> studentID to use in replacement
 5323:                                           of existing one
 5324:                           - 'CODE' 
 5325:                                'CODE_ignore_dup' - set to true if duplicates
 5326:                                                    should be ignored.
 5327: 	                       'CODE' - is new code or 'use_unfound'
 5328:                                         if the existing unfound code should
 5329:                                         be used as is
 5330:                           - 'answer'
 5331:                                'response' - new answer or 'none' if blank
 5332:                                'question' - the bubble line to change
 5333:                                'questionnum' - the question identifier,
 5334:                                                may include subquestion. 
 5335: 
 5336:   Returns:
 5337:     $line - the modified scanline
 5338: 
 5339:   Side effects: 
 5340:     $scan_data - may be updated
 5341: 
 5342: =cut
 5343: 
 5344: 
 5345: sub scantron_fixup_scanline {
 5346:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5347:     if ($field eq 'ID') {
 5348: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5349: 	    return ($line,1,'New value too large');
 5350: 	}
 5351: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5352: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5353: 				     $args->{'newid'});
 5354: 	}
 5355: 	substr($line,$$scantron_config{'IDstart'}-1,
 5356: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5357: 	if ($args->{'newid'}=~/^\s*$/) {
 5358: 	    &scan_data($scan_data,"$whichline.user",
 5359: 		       $args->{'username'}.':'.$args->{'domain'});
 5360: 	}
 5361:     } elsif ($field eq 'CODE') {
 5362: 	if ($args->{'CODE_ignore_dup'}) {
 5363: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5364: 	}
 5365: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5366: 	if ($args->{'CODE'} ne 'use_unfound') {
 5367: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5368: 		return ($line,1,'New CODE value too large');
 5369: 	    }
 5370: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5371: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5372: 	    }
 5373: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5374: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5375: 	}
 5376:     } elsif ($field eq 'answer') {
 5377: 	my $length=$scantron_config->{'Qlength'};
 5378: 	my $off=$scantron_config->{'Qoff'};
 5379: 	my $on=$scantron_config->{'Qon'};
 5380: 	my $answer=${off}x$length;
 5381: 	if ($args->{'response'} eq 'none') {
 5382: 	    &scan_data($scan_data,
 5383: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5384: 	} else {
 5385: 	    if ($on eq 'letter') {
 5386: 		my @alphabet=('A'..'Z');
 5387: 		$answer=$alphabet[$args->{'response'}];
 5388: 	    } elsif ($on eq 'number') {
 5389: 		$answer=$args->{'response'}+1;
 5390: 		if ($answer == 10) { $answer = '0'; }
 5391: 	    } else {
 5392: 		substr($answer,$args->{'response'},1)=$on;
 5393: 	    }
 5394: 	    &scan_data($scan_data,
 5395: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5396: 	}
 5397: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5398: 	substr($line,$where-1,$length)=$answer;
 5399:     }
 5400:     return $line;
 5401: }
 5402: 
 5403: =pod
 5404: 
 5405: =item scan_data
 5406: 
 5407:     Edit or look up  an item in the scan_data hash.
 5408: 
 5409:   Arguments:
 5410:     $scan_data  - The hash (see scantron_getfile)
 5411:     $key        - shorthand of the key to edit (actual key is
 5412:                   scantronfilename_key).
 5413:     $data        - New value of the hash entry.
 5414:     $delete      - If true, the entry is removed from the hash.
 5415: 
 5416:   Returns:
 5417:     The new value of the hash table field (undefined if deleted).
 5418: 
 5419: =cut
 5420: 
 5421: 
 5422: sub scan_data {
 5423:     my ($scan_data,$key,$value,$delete)=@_;
 5424:     my $filename=$env{'form.scantron_selectfile'};
 5425:     if (defined($value)) {
 5426: 	$scan_data->{$filename.'_'.$key} = $value;
 5427:     }
 5428:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5429:     return $scan_data->{$filename.'_'.$key};
 5430: }
 5431: 
 5432: # ----- These first few routines are general use routines.----
 5433: 
 5434: # Return the number of occurences of a pattern in a string.
 5435: 
 5436: sub occurence_count {
 5437:     my ($string, $pattern) = @_;
 5438: 
 5439:     my @matches = ($string =~ /$pattern/g);
 5440: 
 5441:     return scalar(@matches);
 5442: }
 5443: 
 5444: 
 5445: # Take a string known to have digits and convert all the
 5446: # digits into letters in the range J,A..I.
 5447: 
 5448: sub digits_to_letters {
 5449:     my ($input) = @_;
 5450: 
 5451:     my @alphabet = ('J', 'A'..'I');
 5452: 
 5453:     my @input    = split(//, $input);
 5454:     my $output ='';
 5455:     for (my $i = 0; $i < scalar(@input); $i++) {
 5456: 	if ($input[$i] =~ /\d/) {
 5457: 	    $output .= $alphabet[$input[$i]];
 5458: 	} else {
 5459: 	    $output .= $input[$i];
 5460: 	}
 5461:     }
 5462:     return $output;
 5463: }
 5464: 
 5465: =pod 
 5466: 
 5467: =item scantron_parse_scanline
 5468: 
 5469:   Decodes a scanline from the selected scantron file
 5470: 
 5471:  Arguments:
 5472:     line             - The text of the scantron file line to process
 5473:     whichline        - Line number
 5474:     scantron_config  - Hash describing the format of the scantron lines.
 5475:     scan_data        - Hash of extra information about the scanline
 5476:                        (see scantron_getfile for more information)
 5477:     just_header      - True if should not process question answers but only
 5478:                        the stuff to the left of the answers.
 5479:  Returns:
 5480:    Hash containing the result of parsing the scanline
 5481: 
 5482:    Keys are all proceeded by the string 'scantron.'
 5483: 
 5484:        CODE    - the CODE in use for this scanline
 5485:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5486:                  by the operator
 5487:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5488:                             CODEs were selected, but the usage has been
 5489:                             forced by the operator
 5490:        ID  - student ID
 5491:        PaperID - if used, the ID number printed on the sheet when the 
 5492:                  paper was scanned
 5493:        FirstName - first name from the sheet
 5494:        LastName  - last name from the sheet
 5495: 
 5496:      if just_header was not true these key may also exist
 5497: 
 5498:        missingerror - a list of bubble ranges that are considered to be answers
 5499:                       to a single question that don't have any bubbles filled in.
 5500:                       Of the form questionnumber:firstbubblenumber:count.
 5501:        doubleerror  - a list of bubble ranges that are considered to be answers
 5502:                       to a single question that have more than one bubble filled in.
 5503:                       Of the form questionnumber::firstbubblenumber:count
 5504:    
 5505:                 In the above, count is the number of bubble responses in the
 5506:                 input line needed to represent the possible answers to the question.
 5507:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5508:                 per line would have count = 2.
 5509: 
 5510:        maxquest     - the number of the last bubble line that was parsed
 5511: 
 5512:        (<number> starts at 1)
 5513:        <number>.answer - zero or more letters representing the selected
 5514:                          letters from the scanline for the bubble line 
 5515:                          <number>.
 5516:                          if blank there was either no bubble or there where
 5517:                          multiple bubbles, (consult the keys missingerror and
 5518:                          doubleerror if this is an error condition)
 5519: 
 5520: =cut
 5521: 
 5522: sub scantron_parse_scanline {
 5523:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5524: 
 5525:     my %record;
 5526:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5527:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5528:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5529: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5530: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5531: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5532: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5533: 	    $record{'scantron.CODE'}=substr($data,
 5534: 					    $$scantron_config{'CODEstart'}-1,
 5535: 					    $$scantron_config{'CODElength'});
 5536: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5537: 		$record{'scantron.useCODE'}=1;
 5538: 	    }
 5539: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5540: 		$record{'scantron.CODE_ignore_dup'}=1;
 5541: 	    }
 5542: 	} else {
 5543: 	    #FIXME interpret first N questions
 5544: 	}
 5545:     }
 5546:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5547: 				  $$scantron_config{'IDlength'});
 5548:     $record{'scantron.PaperID'}=
 5549: 	substr($data,$$scantron_config{'PaperID'}-1,
 5550: 	       $$scantron_config{'PaperIDlength'});
 5551:     $record{'scantron.FirstName'}=
 5552: 	substr($data,$$scantron_config{'FirstName'}-1,
 5553: 	       $$scantron_config{'FirstNamelength'});
 5554:     $record{'scantron.LastName'}=
 5555: 	substr($data,$$scantron_config{'LastName'}-1,
 5556: 	       $$scantron_config{'LastNamelength'});
 5557:     if ($just_header) { return \%record; }
 5558: 
 5559:     my @alphabet=('A'..'Z');
 5560:     my $questnum=0;
 5561:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5562: 
 5563:     chomp($questions);		# Get rid of any trailing \n.
 5564:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5565:     while (length($questions)) {
 5566: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5567:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5568:                              || 1;
 5569:         $questnum++;
 5570:         my $quest_id = $questnum;
 5571:         my $currentquest = substr($questions,0,$answer_length);
 5572:         $questions       = substr($questions,$answer_length);
 5573:         if (length($currentquest) < $answer_length) { next; }
 5574: 
 5575:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5576:             my $subquestnum = 1;
 5577:             my $subquestions = $currentquest;
 5578:             my @subanswers_needed = 
 5579:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5580:             foreach my $subans (@subanswers_needed) {
 5581:                 my $subans_length =
 5582:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5583:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5584:                 $subquestions   = substr($subquestions,$subans_length);
 5585:                 $quest_id = "$questnum.$subquestnum";
 5586:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5587:                     ($$scantron_config{'Qon'} eq 'number')) {
 5588:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5589:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5590:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5591:                 } else {
 5592:                     $ansnum = &scantron_validator_positional($ansnum,
 5593:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5594:                 }
 5595:                 $subquestnum ++;
 5596:             }
 5597:         } else {
 5598:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5599:                 ($$scantron_config{'Qon'} eq 'number')) {
 5600:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5601:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5602:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5603:             } else {
 5604:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5605:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5606:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5607:             }
 5608:         }
 5609:     }
 5610:     $record{'scantron.maxquest'}=$questnum;
 5611:     return \%record;
 5612: }
 5613: 
 5614: sub scantron_validator_lettnum {
 5615:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5616:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5617: 
 5618:     # Qon 'letter' implies for each slot in currquest we have:
 5619:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5620:     #    about anything else (esp. a value of Qoff) for missing
 5621:     #    bubbles.
 5622:     #
 5623:     # Qon 'number' implies each slot gives a digit that indexes the
 5624:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5625:     #    and * or ? for double bubbles on a single line.
 5626:     #
 5627: 
 5628:     my $matchon;
 5629:     if ($$scantron_config{'Qon'} eq 'letter') {
 5630:         $matchon = '[A-Z]';
 5631:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5632:         $matchon = '\d';
 5633:     }
 5634:     my $occurrences = 0;
 5635:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5636:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5637:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5638:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5639:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5640:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5641:         my @singlelines = split('',$currquest);
 5642:         foreach my $entry (@singlelines) {
 5643:             $occurrences = &occurence_count($entry,$matchon);
 5644:             if ($occurrences > 1) {
 5645:                 last;
 5646:             }
 5647:         } 
 5648:     } else {
 5649:         $occurrences = &occurence_count($currquest,$matchon); 
 5650:     }
 5651:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5652:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5653:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5654:             my $bubble = substr($currquest,$ans,1);
 5655:             if ($bubble =~ /$matchon/ ) {
 5656:                 if ($$scantron_config{'Qon'} eq 'number') {
 5657:                     if ($bubble == 0) {
 5658:                         $bubble = 10; 
 5659:                     }
 5660:                     $record->{"scantron.$ansnum.answer"} = 
 5661:                         $alphabet->[$bubble-1];
 5662:                 } else {
 5663:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5664:                 }
 5665:             } else {
 5666:                 $record->{"scantron.$ansnum.answer"}='';
 5667:             }
 5668:             $ansnum++;
 5669:         }
 5670:     } elsif (!defined($currquest)
 5671:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5672:             || (&occurence_count($currquest,$matchon) == 0)) {
 5673:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5674:             $record->{"scantron.$ansnum.answer"}='';
 5675:             $ansnum++;
 5676:         }
 5677:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5678:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5679:         }
 5680:     } else {
 5681:         if ($$scantron_config{'Qon'} eq 'number') {
 5682:             $currquest = &digits_to_letters($currquest);            
 5683:         }
 5684:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5685:             my $bubble = substr($currquest,$ans,1);
 5686:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5687:             $ansnum++;
 5688:         }
 5689:     }
 5690:     return $ansnum;
 5691: }
 5692: 
 5693: sub scantron_validator_positional {
 5694:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5695:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5696: 
 5697:     # Otherwise there's a positional notation;
 5698:     # each bubble line requires Qlength items, and there are filled in
 5699:     # bubbles for each case where there 'Qon' characters.
 5700:     #
 5701: 
 5702:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5703: 
 5704:     # If the split only gives us one element.. the full length of the
 5705:     # answer string, no bubbles are filled in:
 5706: 
 5707:     if ($answers_needed eq '') {
 5708:         return;
 5709:     }
 5710: 
 5711:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5712:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5713:             $record->{"scantron.$ansnum.answer"}='';
 5714:             $ansnum++;
 5715:         }
 5716:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5717:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5718:         }
 5719:     } elsif (scalar(@array) == 2) {
 5720:         my $location = length($array[0]);
 5721:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5722:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5723:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5724:             if ($ans eq $line_num) {
 5725:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5726:             } else {
 5727:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5728:             }
 5729:             $ansnum++;
 5730:          }
 5731:     } else {
 5732:         #  If there's more than one instance of a bubble character
 5733:         #  That's a double bubble; with positional notation we can
 5734:         #  record all the bubbles filled in as well as the
 5735:         #  fact this response consists of multiple bubbles.
 5736:         #
 5737:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5738:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5739:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5740:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5741:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5742:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5743:             my $doubleerror = 0;
 5744:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5745:                    (!$doubleerror)) {
 5746:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5747:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5748:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5749:                if (length(@currarray) > 2) {
 5750:                    $doubleerror = 1;
 5751:                } 
 5752:             }
 5753:             if ($doubleerror) {
 5754:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5755:             }
 5756:         } else {
 5757:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5758:         }
 5759:         my $item = $ansnum;
 5760:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5761:             $record->{"scantron.$item.answer"} = '';
 5762:             $item ++;
 5763:         }
 5764: 
 5765:         my @ans=@array;
 5766:         my $i=0;
 5767:         my $increment = 0;
 5768:         while ($#ans) {
 5769:             $i+=length($ans[0]) + $increment;
 5770:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5771:             my $bubble = $i%$$scantron_config{'Qlength'};
 5772:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5773:             shift(@ans);
 5774:             $increment = 1;
 5775:         }
 5776:         $ansnum += $answers_needed;
 5777:     }
 5778:     return $ansnum;
 5779: }
 5780: 
 5781: =pod
 5782: 
 5783: =item scantron_add_delay
 5784: 
 5785:    Adds an error message that occurred during the grading phase to a
 5786:    queue of messages to be shown after grading pass is complete
 5787: 
 5788:  Arguments:
 5789:    $delayqueue  - arrary ref of hash ref of error messages
 5790:    $scanline    - the scanline that caused the error
 5791:    $errormesage - the error message
 5792:    $errorcode   - a numeric code for the error
 5793: 
 5794:  Side Effects:
 5795:    updates the $delayqueue to have a new hash ref of the error
 5796: 
 5797: =cut
 5798: 
 5799: sub scantron_add_delay {
 5800:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5801:     push(@$delayqueue,
 5802: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5803: 	  'ecode' => $errorcode }
 5804: 	 );
 5805: }
 5806: 
 5807: =pod
 5808: 
 5809: =item scantron_find_student
 5810: 
 5811:    Finds the username for the current scanline
 5812: 
 5813:   Arguments:
 5814:    $scantron_record - hash result from scantron_parse_scanline
 5815:    $scan_data       - hash of correction information 
 5816:                       (see &scantron_getfile() form more information)
 5817:    $idmap           - hash from &username_to_idmap()
 5818:    $line            - number of current scanline
 5819:  
 5820:   Returns:
 5821:    Either 'username:domain' or undef if unknown
 5822: 
 5823: =cut
 5824: 
 5825: sub scantron_find_student {
 5826:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5827:     my $scanID=$$scantron_record{'scantron.ID'};
 5828:     if ($scanID =~ /^\s*$/) {
 5829:  	return &scan_data($scan_data,"$line.user");
 5830:     }
 5831:     foreach my $id (keys(%$idmap)) {
 5832:  	if (lc($id) eq lc($scanID)) {
 5833:  	    return $$idmap{$id};
 5834:  	}
 5835:     }
 5836:     return undef;
 5837: }
 5838: 
 5839: =pod
 5840: 
 5841: =item scantron_filter
 5842: 
 5843:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5844:    hidden resources was selected
 5845: 
 5846: =cut
 5847: 
 5848: sub scantron_filter {
 5849:     my ($curres)=@_;
 5850: 
 5851:     if (ref($curres) && $curres->is_problem()) {
 5852: 	# if the user has asked to not have either hidden
 5853: 	# or 'randomout' controlled resources to be graded
 5854: 	# don't include them
 5855: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5856: 	    && $curres->randomout) {
 5857: 	    return 0;
 5858: 	}
 5859: 	return 1;
 5860:     }
 5861:     return 0;
 5862: }
 5863: 
 5864: =pod
 5865: 
 5866: =item scantron_process_corrections
 5867: 
 5868:    Gets correction information out of submitted form data and corrects
 5869:    the scanline
 5870: 
 5871: =cut
 5872: 
 5873: sub scantron_process_corrections {
 5874:     my ($r) = @_;
 5875:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5876:     my ($scanlines,$scan_data)=&scantron_getfile();
 5877:     my $classlist=&Apache::loncoursedata::get_classlist();
 5878:     my $which=$env{'form.scantron_line'};
 5879:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5880:     my ($skip,$err,$errmsg);
 5881:     if ($env{'form.scantron_skip_record'}) {
 5882: 	$skip=1;
 5883:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5884: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5885: 	    $env{'form.scantron_domain'};
 5886: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5887: 	($line,$err,$errmsg)=
 5888: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5889: 				     'ID',{'newid'=>$newid,
 5890: 				    'username'=>$env{'form.scantron_username'},
 5891: 				    'domain'=>$env{'form.scantron_domain'}});
 5892:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5893: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5894: 	my $newCODE;
 5895: 	my %args;
 5896: 	if      ($resolution eq 'use_unfound') {
 5897: 	    $newCODE='use_unfound';
 5898: 	} elsif ($resolution eq 'use_found') {
 5899: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5900: 	} elsif ($resolution eq 'use_typed') {
 5901: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5902: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5903: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5904: 	}
 5905: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5906: 	    $args{'CODE_ignore_dup'}=1;
 5907: 	}
 5908: 	$args{'CODE'}=$newCODE;
 5909: 	($line,$err,$errmsg)=
 5910: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5911: 				     'CODE',\%args);
 5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5913: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5914: 	    ($line,$err,$errmsg)=
 5915: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5916: 					 $which,'answer',
 5917: 					 { 'question'=>$question,
 5918: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5919:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5920: 	    if ($err) { last; }
 5921: 	}
 5922:     }
 5923:     if ($err) {
 5924: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5925:     } else {
 5926: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5927: 	&scantron_putfile($scanlines,$scan_data);
 5928:     }
 5929: }
 5930: 
 5931: =pod
 5932: 
 5933: =item reset_skipping_status
 5934: 
 5935:    Forgets the current set of remember skipped scanlines (and thus
 5936:    reverts back to considering all lines in the
 5937:    scantron_skipped_<filename> file)
 5938: 
 5939: =cut
 5940: 
 5941: sub reset_skipping_status {
 5942:     my ($scanlines,$scan_data)=&scantron_getfile();
 5943:     &scan_data($scan_data,'remember_skipping',undef,1);
 5944:     &scantron_putfile(undef,$scan_data);
 5945: }
 5946: 
 5947: =pod
 5948: 
 5949: =item start_skipping
 5950: 
 5951:    Marks a scanline to be skipped. 
 5952: 
 5953: =cut
 5954: 
 5955: sub start_skipping {
 5956:     my ($scan_data,$i)=@_;
 5957:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5958:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5959: 	$remembered{$i}=2;
 5960:     } else {
 5961: 	$remembered{$i}=1;
 5962:     }
 5963:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5964: }
 5965: 
 5966: =pod
 5967: 
 5968: =item should_be_skipped
 5969: 
 5970:    Checks whether a scanline should be skipped.
 5971: 
 5972: =cut
 5973: 
 5974: sub should_be_skipped {
 5975:     my ($scanlines,$scan_data,$i)=@_;
 5976:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5977: 	# not redoing old skips
 5978: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5979: 	return 0;
 5980:     }
 5981:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5982: 
 5983:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5984: 	return 0;
 5985:     }
 5986:     return 1;
 5987: }
 5988: 
 5989: =pod
 5990: 
 5991: =item remember_current_skipped
 5992: 
 5993:    Discovers what scanlines are in the scantron_skipped_<filename>
 5994:    file and remembers them into scan_data for later use.
 5995: 
 5996: =cut
 5997: 
 5998: sub remember_current_skipped {
 5999:     my ($scanlines,$scan_data)=&scantron_getfile();
 6000:     my %to_remember;
 6001:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6002: 	if ($scanlines->{'skipped'}[$i]) {
 6003: 	    $to_remember{$i}=1;
 6004: 	}
 6005:     }
 6006: 
 6007:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6008:     &scantron_putfile(undef,$scan_data);
 6009: }
 6010: 
 6011: =pod
 6012: 
 6013: =item check_for_error
 6014: 
 6015:     Checks if there was an error when attempting to remove a specific
 6016:     scantron_.. bubble sheet data file. Prints out an error if
 6017:     something went wrong.
 6018: 
 6019: =cut
 6020: 
 6021: sub check_for_error {
 6022:     my ($r,$result)=@_;
 6023:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6024: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6025:     }
 6026: }
 6027: 
 6028: =pod
 6029: 
 6030: =item scantron_warning_screen
 6031: 
 6032:    Interstitial screen to make sure the operator has selected the
 6033:    correct options before we start the validation phase.
 6034: 
 6035: =cut
 6036: 
 6037: sub scantron_warning_screen {
 6038:     my ($button_text)=@_;
 6039:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6040:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6041:     my $CODElist;
 6042:     if ($scantron_config{'CODElocation'} &&
 6043: 	$scantron_config{'CODEstart'} &&
 6044: 	$scantron_config{'CODElength'}) {
 6045: 	$CODElist=$env{'form.scantron_CODElist'};
 6046: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6047: 	$CODElist=
 6048: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6049: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6050:     }
 6051:     return ('
 6052: <p>
 6053: <span class="LC_warning">
 6054: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6055: </p>
 6056: <table>
 6057: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6058: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6059: '.$CODElist.'
 6060: </table>
 6061: <br />
 6062: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6063: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6064: 
 6065: <br />
 6066: ');
 6067: }
 6068: 
 6069: =pod
 6070: 
 6071: =item scantron_do_warning
 6072: 
 6073:    Check if the operator has picked something for all required
 6074:    fields. Error out if something is missing.
 6075: 
 6076: =cut
 6077: 
 6078: sub scantron_do_warning {
 6079:     my ($r)=@_;
 6080:     my ($symb)=&get_symb($r);
 6081:     if (!$symb) {return '';}
 6082:     my $default_form_data=&defaultFormData($symb);
 6083:     $r->print(&scantron_form_start().$default_form_data);
 6084:     if ( $env{'form.selectpage'} eq '' ||
 6085: 	 $env{'form.scantron_selectfile'} eq '' ||
 6086: 	 $env{'form.scantron_format'} eq '' ) {
 6087: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6088: 	if ( $env{'form.selectpage'} eq '') {
 6089: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6090: 	} 
 6091: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6092: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6093: 	} 
 6094: 	if ( $env{'form.scantron_format'} eq '') {
 6095: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6096: 	} 
 6097:     } else {
 6098: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6099: 	$r->print('
 6100: '.$warning.'
 6101: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6102: <input type="hidden" name="command" value="scantron_validate" />
 6103: ');
 6104:     }
 6105:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6106:     return '';
 6107: }
 6108: 
 6109: =pod
 6110: 
 6111: =item scantron_form_start
 6112: 
 6113:     html hidden input for remembering all selected grading options
 6114: 
 6115: =cut
 6116: 
 6117: sub scantron_form_start {
 6118:     my ($max_bubble)=@_;
 6119:     my $result= <<SCANTRONFORM;
 6120: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6121:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6122:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6123:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6124:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6125:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6126:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6127:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6128:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6129:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6130: SCANTRONFORM
 6131: 
 6132:   my $line = 0;
 6133:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6134:        my $chunk =
 6135: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6136:        $chunk .=
 6137: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6138:        $chunk .= 
 6139:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6140:        $chunk .=
 6141:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6142:        $result .= $chunk;
 6143:        $line++;
 6144:    }
 6145:     return $result;
 6146: }
 6147: 
 6148: =pod
 6149: 
 6150: =item scantron_validate_file
 6151: 
 6152:     Dispatch routine for doing validation of a bubble sheet data file.
 6153: 
 6154:     Also processes any necessary information resets that need to
 6155:     occur before validation begins (ignore previous corrections,
 6156:     restarting the skipped records processing)
 6157: 
 6158: =cut
 6159: 
 6160: sub scantron_validate_file {
 6161:     my ($r) = @_;
 6162:     my ($symb)=&get_symb($r);
 6163:     if (!$symb) {return '';}
 6164:     my $default_form_data=&defaultFormData($symb);
 6165:     
 6166:     # do the detection of only doing skipped records first befroe we delete
 6167:     # them when doing the corrections reset
 6168:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6169: 	&reset_skipping_status();
 6170:     }
 6171:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6172: 	&remember_current_skipped();
 6173: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6174:     }
 6175: 
 6176:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6177: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6178: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6179: 	&check_for_error($r,&scantron_remove_scan_data());
 6180: 	$env{'form.scantron_options_ignore'}='done';
 6181:     }
 6182: 
 6183:     if ($env{'form.scantron_corrections'}) {
 6184: 	&scantron_process_corrections($r);
 6185:     }
 6186:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6187:     #get the student pick code ready
 6188:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6189:     my $max_bubble=&scantron_get_maxbubble();
 6190:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6191:     $r->print($result);
 6192:     
 6193:     my @validate_phases=( 'sequence',
 6194: 			  'ID',
 6195: 			  'CODE',
 6196: 			  'doublebubble',
 6197: 			  'missingbubbles');
 6198:     if (!$env{'form.validatepass'}) {
 6199: 	$env{'form.validatepass'} = 0;
 6200:     }
 6201:     my $currentphase=$env{'form.validatepass'};
 6202: 
 6203: 
 6204:     my $stop=0;
 6205:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6206: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6207: 	$r->rflush();
 6208: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6209: 	{
 6210: 	    no strict 'refs';
 6211: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6212: 	}
 6213:     }
 6214:     if (!$stop) {
 6215: 	my $warning=&scantron_warning_screen('Start Grading');
 6216: 	$r->print(&mt('Validation process complete.').'<br />
 6217: '.$warning.'
 6218: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6219: <input type="hidden" name="command" value="scantron_process" />
 6220: ');
 6221: 
 6222:     } else {
 6223: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6224: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6225:     }
 6226:     if ($stop) {
 6227: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6228: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6229: 	    $r->print(' '.&mt('this error').' <br />');
 6230: 
 6231: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6232: 	} else {
 6233:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6234: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6235:             } else {
 6236:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6237:             }
 6238: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6239: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6240: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6241: 	}
 6242:     }
 6243:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6244:     return '';
 6245: }
 6246: 
 6247: 
 6248: =pod
 6249: 
 6250: =item scantron_remove_file
 6251: 
 6252:    Removes the requested bubble sheet data file, makes sure that
 6253:    scantron_original_<filename> is never removed
 6254: 
 6255: 
 6256: =cut
 6257: 
 6258: sub scantron_remove_file {
 6259:     my ($which)=@_;
 6260:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6261:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6262:     my $file='scantron_';
 6263:     if ($which eq 'corrected' || $which eq 'skipped') {
 6264: 	$file.=$which.'_';
 6265:     } else {
 6266: 	return 'refused';
 6267:     }
 6268:     $file.=$env{'form.scantron_selectfile'};
 6269:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6270: }
 6271: 
 6272: 
 6273: =pod
 6274: 
 6275: =item scantron_remove_scan_data
 6276: 
 6277:    Removes all scan_data correction for the requested bubble sheet
 6278:    data file.  (In the case that both the are doing skipped records we need
 6279:    to remember the old skipped lines for the time being so that element
 6280:    persists for a while.)
 6281: 
 6282: =cut
 6283: 
 6284: sub scantron_remove_scan_data {
 6285:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6286:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6287:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6288:     my @todelete;
 6289:     my $filename=$env{'form.scantron_selectfile'};
 6290:     foreach my $key (@keys) {
 6291: 	if ($key=~/^\Q$filename\E_/) {
 6292: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6293: 		$key=~/remember_skipping/) {
 6294: 		next;
 6295: 	    }
 6296: 	    push(@todelete,$key);
 6297: 	}
 6298:     }
 6299:     my $result;
 6300:     if (@todelete) {
 6301: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6302: 				       \@todelete,$cdom,$cname);
 6303:     } else {
 6304: 	$result = 'ok';
 6305:     }
 6306:     return $result;
 6307: }
 6308: 
 6309: 
 6310: =pod
 6311: 
 6312: =item scantron_getfile
 6313: 
 6314:     Fetches the requested bubble sheet data file (all 3 versions), and
 6315:     the scan_data hash
 6316:   
 6317:   Arguments:
 6318:     None
 6319: 
 6320:   Returns:
 6321:     2 hash references
 6322: 
 6323:      - first one has 
 6324:          orig      -
 6325:          corrected -
 6326:          skipped   -  each of which points to an array ref of the specified
 6327:                       file broken up into individual lines
 6328:          count     - number of scanlines
 6329:  
 6330:      - second is the scan_data hash possible keys are
 6331:        ($number refers to scanline numbered $number and thus the key affects
 6332:         only that scanline
 6333:         $bubline refers to the specific bubble line element and the aspects
 6334:         refers to that specific bubble line element)
 6335: 
 6336:        $number.user - username:domain to use
 6337:        $number.CODE_ignore_dup 
 6338:                     - ignore the duplicate CODE error 
 6339:        $number.useCODE
 6340:                     - use the CODE in the scanline as is
 6341:        $number.no_bubble.$bubline
 6342:                     - it is valid that there is no bubbled in bubble
 6343:                       at $number $bubline
 6344:        remember_skipping
 6345:                     - a frozen hash containing keys of $number and values
 6346:                       of either 
 6347:                         1 - we are on a 'do skipped records pass' and plan
 6348:                             on processing this line
 6349:                         2 - we are on a 'do skipped records pass' and this
 6350:                             scanline has been marked to skip yet again
 6351: 
 6352: =cut
 6353: 
 6354: sub scantron_getfile {
 6355:     #FIXME really would prefer a scantron directory
 6356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6358:     my $lines;
 6359:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6360: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6361:     my %scanlines;
 6362:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6363:     my $temp=$scanlines{'orig'};
 6364:     $scanlines{'count'}=$#$temp;
 6365: 
 6366:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6367: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6368:     if ($lines eq '-1') {
 6369: 	$scanlines{'corrected'}=[];
 6370:     } else {
 6371: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6372:     }
 6373:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6374: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6375:     if ($lines eq '-1') {
 6376: 	$scanlines{'skipped'}=[];
 6377:     } else {
 6378: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6379:     }
 6380:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6381:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6382:     my %scan_data = @tmp;
 6383:     return (\%scanlines,\%scan_data);
 6384: }
 6385: 
 6386: =pod
 6387: 
 6388: =item lonnet_putfile
 6389: 
 6390:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6391: 
 6392:  Arguments:
 6393:    $contents - data to store
 6394:    $filename - filename to store $contents into
 6395: 
 6396:  Returns:
 6397:    result value from &Apache::lonnet::finishuserfileupload
 6398: 
 6399: =cut
 6400: 
 6401: sub lonnet_putfile {
 6402:     my ($contents,$filename)=@_;
 6403:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6404:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6405:     $env{'form.sillywaytopassafilearound'}=$contents;
 6406:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6407: 
 6408: }
 6409: 
 6410: =pod
 6411: 
 6412: =item scantron_putfile
 6413: 
 6414:     Stores the current version of the bubble sheet data files, and the
 6415:     scan_data hash. (Does not modify the original version only the
 6416:     corrected and skipped versions.
 6417: 
 6418:  Arguments:
 6419:     $scanlines - hash ref that looks like the first return value from
 6420:                  &scantron_getfile()
 6421:     $scan_data - hash ref that looks like the second return value from
 6422:                  &scantron_getfile()
 6423: 
 6424: =cut
 6425: 
 6426: sub scantron_putfile {
 6427:     my ($scanlines,$scan_data) = @_;
 6428:     #FIXME really would prefer a scantron directory
 6429:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6430:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6431:     if ($scanlines) {
 6432: 	my $prefix='scantron_';
 6433: # no need to update orig, shouldn't change
 6434: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6435: #		    $env{'form.scantron_selectfile'});
 6436: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6437: 			$prefix.'corrected_'.
 6438: 			$env{'form.scantron_selectfile'});
 6439: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6440: 			$prefix.'skipped_'.
 6441: 			$env{'form.scantron_selectfile'});
 6442:     }
 6443:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6444: }
 6445: 
 6446: =pod
 6447: 
 6448: =item scantron_get_line
 6449: 
 6450:    Returns the correct version of the scanline
 6451: 
 6452:  Arguments:
 6453:     $scanlines - hash ref that looks like the first return value from
 6454:                  &scantron_getfile()
 6455:     $scan_data - hash ref that looks like the second return value from
 6456:                  &scantron_getfile()
 6457:     $i         - number of the requested line (starts at 0)
 6458: 
 6459:  Returns:
 6460:    A scanline, (either the original or the corrected one if it
 6461:    exists), or undef if the requested scanline should be
 6462:    skipped. (Either because it's an skipped scanline, or it's an
 6463:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6464:    pass.
 6465: 
 6466: =cut
 6467: 
 6468: sub scantron_get_line {
 6469:     my ($scanlines,$scan_data,$i)=@_;
 6470:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6471:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6472:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6473:     return $scanlines->{'orig'}[$i]; 
 6474: }
 6475: 
 6476: =pod
 6477: 
 6478: =item scantron_todo_count
 6479: 
 6480:     Counts the number of scanlines that need processing.
 6481: 
 6482:  Arguments:
 6483:     $scanlines - hash ref that looks like the first return value from
 6484:                  &scantron_getfile()
 6485:     $scan_data - hash ref that looks like the second return value from
 6486:                  &scantron_getfile()
 6487: 
 6488:  Returns:
 6489:     $count - number of scanlines to process
 6490: 
 6491: =cut
 6492: 
 6493: sub get_todo_count {
 6494:     my ($scanlines,$scan_data)=@_;
 6495:     my $count=0;
 6496:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6497: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6498: 	if ($line=~/^[\s\cz]*$/) { next; }
 6499: 	$count++;
 6500:     }
 6501:     return $count;
 6502: }
 6503: 
 6504: =pod
 6505: 
 6506: =item scantron_put_line
 6507: 
 6508:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6509:     data file.
 6510: 
 6511:  Arguments:
 6512:     $scanlines - hash ref that looks like the first return value from
 6513:                  &scantron_getfile()
 6514:     $scan_data - hash ref that looks like the second return value from
 6515:                  &scantron_getfile()
 6516:     $i         - line number to update
 6517:     $newline   - contents of the updated scanline
 6518:     $skip      - if true make the line for skipping and update the
 6519:                  'skipped' file
 6520: 
 6521: =cut
 6522: 
 6523: sub scantron_put_line {
 6524:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6525:     if ($skip) {
 6526: 	$scanlines->{'skipped'}[$i]=$newline;
 6527: 	&start_skipping($scan_data,$i);
 6528: 	return;
 6529:     }
 6530:     $scanlines->{'corrected'}[$i]=$newline;
 6531: }
 6532: 
 6533: =pod
 6534: 
 6535: =item scantron_clear_skip
 6536: 
 6537:    Remove a line from the 'skipped' file
 6538: 
 6539:  Arguments:
 6540:     $scanlines - hash ref that looks like the first return value from
 6541:                  &scantron_getfile()
 6542:     $scan_data - hash ref that looks like the second return value from
 6543:                  &scantron_getfile()
 6544:     $i         - line number to update
 6545: 
 6546: =cut
 6547: 
 6548: sub scantron_clear_skip {
 6549:     my ($scanlines,$scan_data,$i)=@_;
 6550:     if (exists($scanlines->{'skipped'}[$i])) {
 6551: 	undef($scanlines->{'skipped'}[$i]);
 6552: 	return 1;
 6553:     }
 6554:     return 0;
 6555: }
 6556: 
 6557: =pod
 6558: 
 6559: =item scantron_filter_not_exam
 6560: 
 6561:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6562:    filter out resources that are not marked as 'exam' mode
 6563: 
 6564: =cut
 6565: 
 6566: sub scantron_filter_not_exam {
 6567:     my ($curres)=@_;
 6568:     
 6569:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6570: 	# if the user has asked to not have either hidden
 6571: 	# or 'randomout' controlled resources to be graded
 6572: 	# don't include them
 6573: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6574: 	    && $curres->randomout) {
 6575: 	    return 0;
 6576: 	}
 6577: 	return 1;
 6578:     }
 6579:     return 0;
 6580: }
 6581: 
 6582: =pod
 6583: 
 6584: =item scantron_validate_sequence
 6585: 
 6586:     Validates the selected sequence, checking for resource that are
 6587:     not set to exam mode.
 6588: 
 6589: =cut
 6590: 
 6591: sub scantron_validate_sequence {
 6592:     my ($r,$currentphase) = @_;
 6593: 
 6594:     my $navmap=Apache::lonnavmaps::navmap->new();
 6595:     my (undef,undef,$sequence)=
 6596: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6597: 
 6598:     my $map=$navmap->getResourceByUrl($sequence);
 6599: 
 6600:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6601:                                     value="ignore" />');
 6602:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6603: 	my @resources=
 6604: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6605: 	if (@resources) {
 6606: 	    $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>");
 6607: 	    return (1,$currentphase);
 6608: 	}
 6609:     }
 6610: 
 6611:     return (0,$currentphase+1);
 6612: }
 6613: 
 6614: =pod
 6615: 
 6616: =item scantron_validate_ID
 6617: 
 6618:    Validates all scanlines in the selected file to not have any
 6619:    invalid or underspecified student IDs
 6620: 
 6621: =cut
 6622: 
 6623: sub scantron_validate_ID {
 6624:     my ($r,$currentphase) = @_;
 6625:     
 6626:     #get student info
 6627:     my $classlist=&Apache::loncoursedata::get_classlist();
 6628:     my %idmap=&username_to_idmap($classlist);
 6629: 
 6630:     #get scantron line setup
 6631:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6632:     my ($scanlines,$scan_data)=&scantron_getfile();
 6633:     
 6634:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6635: 
 6636:     my %found=('ids'=>{},'usernames'=>{});
 6637:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6638: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6639: 	if ($line=~/^[\s\cz]*$/) { next; }
 6640: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6641: 						 $scan_data);
 6642: 	my $id=$$scan_record{'scantron.ID'};
 6643: 	my $found;
 6644: 	foreach my $checkid (keys(%idmap)) {
 6645: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6646: 	}
 6647: 	if ($found) {
 6648: 	    my $username=$idmap{$found};
 6649: 	    if ($found{'ids'}{$found}) {
 6650: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6651: 					 $line,'duplicateID',$found);
 6652: 		return(1,$currentphase);
 6653: 	    } elsif ($found{'usernames'}{$username}) {
 6654: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6655: 					 $line,'duplicateID',$username);
 6656: 		return(1,$currentphase);
 6657: 	    }
 6658: 	    #FIXME store away line we previously saw the ID on to use above
 6659: 	    $found{'ids'}{$found}++;
 6660: 	    $found{'usernames'}{$username}++;
 6661: 	} else {
 6662: 	    if ($id =~ /^\s*$/) {
 6663: 		my $username=&scan_data($scan_data,"$i.user");
 6664: 		if (defined($username) && $found{'usernames'}{$username}) {
 6665: 		    &scantron_get_correction($r,$i,$scan_record,
 6666: 					     \%scantron_config,
 6667: 					     $line,'duplicateID',$username);
 6668: 		    return(1,$currentphase);
 6669: 		} elsif (!defined($username)) {
 6670: 		    &scantron_get_correction($r,$i,$scan_record,
 6671: 					     \%scantron_config,
 6672: 					     $line,'incorrectID');
 6673: 		    return(1,$currentphase);
 6674: 		}
 6675: 		$found{'usernames'}{$username}++;
 6676: 	    } else {
 6677: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6678: 					 $line,'incorrectID');
 6679: 		return(1,$currentphase);
 6680: 	    }
 6681: 	}
 6682:     }
 6683: 
 6684:     return (0,$currentphase+1);
 6685: }
 6686: 
 6687: =pod
 6688: 
 6689: =item scantron_get_correction
 6690: 
 6691:    Builds the interface screen to interact with the operator to fix a
 6692:    specific error condition in a specific scanline
 6693: 
 6694:  Arguments:
 6695:     $r           - Apache request object
 6696:     $i           - number of the current scanline
 6697:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6698:     $scan_config - hash ref as returned from &get_scantron_config()
 6699:     $line        - full contents of the current scanline
 6700:     $error       - error condition, valid values are
 6701:                    'incorrectCODE', 'duplicateCODE',
 6702:                    'doublebubble', 'missingbubble',
 6703:                    'duplicateID', 'incorrectID'
 6704:     $arg         - extra information needed
 6705:        For errors:
 6706:          - duplicateID   - paper number that this studentID was seen before on
 6707:          - duplicateCODE - array ref of the paper numbers this CODE was
 6708:                            seen on before
 6709:          - incorrectCODE - current incorrect CODE 
 6710:          - doublebubble  - array ref of the bubble lines that have double
 6711:                            bubble errors
 6712:          - missingbubble - array ref of the bubble lines that have missing
 6713:                            bubble errors
 6714: 
 6715: =cut
 6716: 
 6717: sub scantron_get_correction {
 6718:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6719: #FIXME in the case of a duplicated ID the previous line, probably need
 6720: #to show both the current line and the previous one and allow skipping
 6721: #the previous one or the current one
 6722: 
 6723:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6724: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6725: 			    " for PaperID <tt>[_1]</tt>",
 6726: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6727:     } else {
 6728: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6729: 			    " in scanline [_1] <pre>[_2]</pre>",
 6730: 			    $i,$line)."</p> \n");
 6731:     }
 6732:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6733: 			  "The name on the paper is [_2],[_3]",
 6734: 			  $$scan_record{'scantron.ID'},
 6735: 			  $$scan_record{'scantron.LastName'},
 6736: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6737: 
 6738:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6739:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6740:                            # Array populated for doublebubble or
 6741:     my @lines_to_correct;  # missingbubble errors to build javascript
 6742:                            # to validate radio button checking   
 6743: 
 6744:     if ($error =~ /ID$/) {
 6745: 	if ($error eq 'incorrectID') {
 6746: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6747: 		      "</p>\n");
 6748: 	} elsif ($error eq 'duplicateID') {
 6749: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6750: 	}
 6751: 	$r->print($message);
 6752: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6753: 	$r->print("\n<ul><li> ");
 6754: 	#FIXME it would be nice if this sent back the user ID and
 6755: 	#could do partial userID matches
 6756: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6757: 				       'scantron_username','scantron_domain'));
 6758: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6759: 	$r->print("\n@".
 6760: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6761: 
 6762: 	$r->print('</li>');
 6763:     } elsif ($error =~ /CODE$/) {
 6764: 	if ($error eq 'incorrectCODE') {
 6765: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6766: 	} elsif ($error eq 'duplicateCODE') {
 6767: 	    $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");
 6768: 	}
 6769: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6770: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6771: 	$r->print($message);
 6772: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6773: 	$r->print("\n<br /> ");
 6774: 	my $i=0;
 6775: 	if ($error eq 'incorrectCODE' 
 6776: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6777: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6778: 	    if ($closest > 0) {
 6779: 		foreach my $testcode (@{$closest}) {
 6780: 		    my $checked='';
 6781: 		    if (!$i) { $checked=' checked="checked" '; }
 6782: 		    $r->print("
 6783:    <label>
 6784:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6785:        ".&mt("Use the similar CODE [_1] instead.",
 6786: 	    "<b><tt>".$testcode."</tt></b>")."
 6787:     </label>
 6788:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6789: 		    $r->print("\n<br />");
 6790: 		    $i++;
 6791: 		}
 6792: 	    }
 6793: 	}
 6794: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6795: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6796: 	    $r->print("
 6797:     <label>
 6798:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6799:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6800: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6801:     </label>");
 6802: 	    $r->print("\n<br />");
 6803: 	}
 6804: 
 6805: 	$r->print(<<ENDSCRIPT);
 6806: <script type="text/javascript">
 6807: function change_radio(field) {
 6808:     var slct=document.scantronupload.scantron_CODE_resolution;
 6809:     var i;
 6810:     for (i=0;i<slct.length;i++) {
 6811:         if (slct[i].value==field) { slct[i].checked=true; }
 6812:     }
 6813: }
 6814: </script>
 6815: ENDSCRIPT
 6816: 	my $href="/adm/pickcode?".
 6817: 	   "form=".&escape("scantronupload").
 6818: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6819: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6820: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6821: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6822: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6823: 	    $r->print("
 6824:     <label>
 6825:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6826:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6827: 	     "<a target='_blank' href='$href'>","</a>")."
 6828:     </label> 
 6829:     ".&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')\" />"));
 6830: 	    $r->print("\n<br />");
 6831: 	}
 6832: 	$r->print("
 6833:     <label>
 6834:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6835:        ".&mt("Use [_1] as the CODE.",
 6836: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6837: 	$r->print("\n<br /><br />");
 6838:     } elsif ($error eq 'doublebubble') {
 6839: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6840: 
 6841: 	# The form field scantron_questions is acutally a list of line numbers.
 6842: 	# represented by this form so:
 6843: 
 6844: 	my $line_list = &questions_to_line_list($arg);
 6845: 
 6846: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6847: 		  $line_list.'" />');
 6848: 	$r->print($message);
 6849: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6850: 	foreach my $question (@{$arg}) {
 6851: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6852:                                                    $scan_record, $error);
 6853:             push(@lines_to_correct,@linenums);
 6854: 	}
 6855:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6856:     } elsif ($error eq 'missingbubble') {
 6857: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6858: 	$r->print($message);
 6859: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6860: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6861: 
 6862: 	# The form field scantron_questions is actually a list of line numbers not
 6863: 	# a list of question numbers. Therefore:
 6864: 	#
 6865: 	
 6866: 	my $line_list = &questions_to_line_list($arg);
 6867: 
 6868: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6869: 		  $line_list.'" />');
 6870: 	foreach my $question (@{$arg}) {
 6871: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6872:                                                    $scan_record, $error);
 6873:             push(@lines_to_correct,@linenums);
 6874: 	}
 6875:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6876:     } else {
 6877: 	$r->print("\n<ul>");
 6878:     }
 6879:     $r->print("\n</li></ul>");
 6880: }
 6881: 
 6882: sub verify_bubbles_checked {
 6883:     my (@ansnums) = @_;
 6884:     my $ansnumstr = join('","',@ansnums);
 6885:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6886:     my $output = (<<ENDSCRIPT);
 6887: <script type="text/javascript">
 6888: function verify_bubble_radio(form) {
 6889:     var ansnumArray = new Array ("$ansnumstr");
 6890:     var need_bubble_count = 0;
 6891:     for (var i=0; i<ansnumArray.length; i++) {
 6892:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6893:             var bubble_picked = 0; 
 6894:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6895:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6896:                     bubble_picked = 1;
 6897:                 }
 6898:             }
 6899:             if (bubble_picked == 0) {
 6900:                 need_bubble_count ++;
 6901:             }
 6902:         }
 6903:     }
 6904:     if (need_bubble_count) {
 6905:         alert("$warning");
 6906:         return;
 6907:     }
 6908:     form.submit(); 
 6909: }
 6910: </script>
 6911: ENDSCRIPT
 6912:     return $output;
 6913: }
 6914: 
 6915: =pod
 6916: 
 6917: =item  questions_to_line_list
 6918: 
 6919: Converts a list of questions into a string of comma separated
 6920: line numbers in the answer sheet used by the questions.  This is
 6921: used to fill in the scantron_questions form field.
 6922: 
 6923:   Arguments:
 6924:      questions    - Reference to an array of questions.
 6925: 
 6926: =cut
 6927: 
 6928: 
 6929: sub questions_to_line_list {
 6930:     my ($questions) = @_;
 6931:     my @lines;
 6932: 
 6933:     foreach my $item (@{$questions}) {
 6934:         my $question = $item;
 6935:         my ($first,$count,$last);
 6936:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6937:             $question = $1;
 6938:             my $subquestion = $2;
 6939:             $first = $first_bubble_line{$question-1} + 1;
 6940:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6941:             my $subcount = 1;
 6942:             while ($subcount<$subquestion) {
 6943:                 $first += $subans[$subcount-1];
 6944:                 $subcount ++;
 6945:             }
 6946:             $count = $subans[$subquestion-1];
 6947:         } else {
 6948: 	    $first   = $first_bubble_line{$question-1} + 1;
 6949: 	    $count   = $bubble_lines_per_response{$question-1};
 6950:         }
 6951:         $last = $first+$count-1;
 6952:         push(@lines, ($first..$last));
 6953:     }
 6954:     return join(',', @lines);
 6955: }
 6956: 
 6957: =pod 
 6958: 
 6959: =item prompt_for_corrections
 6960: 
 6961: Prompts for a potentially multiline correction to the
 6962: user's bubbling (factors out common code from scantron_get_correction
 6963: for multi and missing bubble cases).
 6964: 
 6965:  Arguments:
 6966:    $r           - Apache request object.
 6967:    $question    - The question number to prompt for.
 6968:    $scan_config - The scantron file configuration hash.
 6969:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6970:    $error       - Type of error
 6971: 
 6972:  Implicit inputs:
 6973:    %bubble_lines_per_response   - Starting line numbers for each question.
 6974:                                   Numbered from 0 (but question numbers are from
 6975:                                   1.
 6976:    %first_bubble_line           - Starting bubble line for each question.
 6977:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6978:                                   type problems render as separate sub-questions, 
 6979:                                   in exam mode. This hash contains a 
 6980:                                   comma-separated list of the lines per 
 6981:                                   sub-question.
 6982:    %responsetype_per_response   - essayresponse, formularesponse,
 6983:                                   stringresponse, imageresponse, reactionresponse,
 6984:                                   and organicresponse type problem parts can have
 6985:                                   multiple lines per response if the weight
 6986:                                   assigned exceeds 10.  In this case, only
 6987:                                   one bubble per line is permitted, but more 
 6988:                                   than one line might contain bubbles, e.g.
 6989:                                   bubbling of: line 1 - J, line 2 - J, 
 6990:                                   line 3 - B would assign 22 points.  
 6991: 
 6992: =cut
 6993: 
 6994: sub prompt_for_corrections {
 6995:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6996:     my ($current_line,$lines);
 6997:     my @linenums;
 6998:     my $questionnum = $question;
 6999:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7000:         $question = $1;
 7001:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7002:         my $subquestion = $2;
 7003:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7004:         my $subcount = 1;
 7005:         while ($subcount<$subquestion) {
 7006:             $current_line += $subans[$subcount-1];
 7007:             $subcount ++;
 7008:         }
 7009:         $lines = $subans[$subquestion-1];
 7010:     } else {
 7011:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7012:         $lines        = $bubble_lines_per_response{$question-1};
 7013:     }
 7014:     if ($lines > 1) {
 7015:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7016:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7017:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7018:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7019:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7020:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7021:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7022:             $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 />');
 7023:         } else {
 7024:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7025:         }
 7026:     }
 7027:     for (my $i =0; $i < $lines; $i++) {
 7028:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7029: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7030: 	        		  $questionnum,$error,split('', $selected));
 7031:         push(@linenums,$current_line);
 7032: 	$current_line++;
 7033:     }
 7034:     if ($lines > 1) {
 7035: 	$r->print("<hr /><br />");
 7036:     }
 7037:     return @linenums;
 7038: }
 7039: 
 7040: =pod
 7041: 
 7042: =item scantron_bubble_selector
 7043:   
 7044:    Generates the html radiobuttons to correct a single bubble line
 7045:    possibly showing the existing the selected bubbles if known
 7046: 
 7047:  Arguments:
 7048:     $r           - Apache request object
 7049:     $scan_config - hash from &get_scantron_config()
 7050:     $line        - Number of the line being displayed.
 7051:     $questionnum - Question number (may include subquestion)
 7052:     $error       - Type of error.
 7053:     @selected    - Array of bubbles picked on this line.
 7054: 
 7055: =cut
 7056: 
 7057: sub scantron_bubble_selector {
 7058:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7059:     my $max=$$scan_config{'Qlength'};
 7060: 
 7061:     my $scmode=$$scan_config{'Qon'};
 7062:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7063: 
 7064:     my @alphabet=('A'..'Z');
 7065:     $r->print(&Apache::loncommon::start_data_table().
 7066:               &Apache::loncommon::start_data_table_row());
 7067:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7068:     for (my $i=0;$i<$max+1;$i++) {
 7069: 	$r->print("\n".'<td align="center">');
 7070: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7071: 	else { $r->print('&nbsp;'); }
 7072: 	$r->print('</td>');
 7073:     }
 7074:     $r->print(&Apache::loncommon::end_data_table_row().
 7075:               &Apache::loncommon::start_data_table_row());
 7076:     for (my $i=0;$i<$max;$i++) {
 7077: 	$r->print("\n".
 7078: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7079: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7080:     }
 7081:     my $nobub_checked = ' ';
 7082:     if ($error eq 'missingbubble') {
 7083:         $nobub_checked = ' checked = "checked" ';
 7084:     }
 7085:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7086: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7087:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7088:               $line.'" value="'.$questionnum.'" /></td>');
 7089:     $r->print(&Apache::loncommon::end_data_table_row().
 7090:               &Apache::loncommon::end_data_table());
 7091: }
 7092: 
 7093: =pod
 7094: 
 7095: =item num_matches
 7096: 
 7097:    Counts the number of characters that are the same between the two arguments.
 7098: 
 7099:  Arguments:
 7100:    $orig - CODE from the scanline
 7101:    $code - CODE to match against
 7102: 
 7103:  Returns:
 7104:    $count - integer count of the number of same characters between the
 7105:             two arguments
 7106: 
 7107: =cut
 7108: 
 7109: sub num_matches {
 7110:     my ($orig,$code) = @_;
 7111:     my @code=split(//,$code);
 7112:     my @orig=split(//,$orig);
 7113:     my $same=0;
 7114:     for (my $i=0;$i<scalar(@code);$i++) {
 7115: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7116:     }
 7117:     return $same;
 7118: }
 7119: 
 7120: =pod
 7121: 
 7122: =item scantron_get_closely_matching_CODEs
 7123: 
 7124:    Cycles through all CODEs and finds the set that has the greatest
 7125:    number of same characters as the provided CODE
 7126: 
 7127:  Arguments:
 7128:    $allcodes - hash ref returned by &get_codes()
 7129:    $CODE     - CODE from the current scanline
 7130: 
 7131:  Returns:
 7132:    2 element list
 7133:     - first elements is number of how closely matching the best fit is 
 7134:       (5 means best set has 5 matching characters)
 7135:     - second element is an arrary ref containing the set of valid CODEs
 7136:       that best fit the passed in CODE
 7137: 
 7138: =cut
 7139: 
 7140: sub scantron_get_closely_matching_CODEs {
 7141:     my ($allcodes,$CODE)=@_;
 7142:     my @CODEs;
 7143:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7144: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7145:     }
 7146: 
 7147:     return ($#CODEs,$CODEs[-1]);
 7148: }
 7149: 
 7150: =pod
 7151: 
 7152: =item get_codes
 7153: 
 7154:    Builds a hash which has keys of all of the valid CODEs from the selected
 7155:    set of remembered CODEs.
 7156: 
 7157:  Arguments:
 7158:   $old_name - name of the set of remembered CODEs
 7159:   $cdom     - domain of the course
 7160:   $cnum     - internal course name
 7161: 
 7162:  Returns:
 7163:   %allcodes - keys are the valid CODEs, values are all 1
 7164: 
 7165: =cut
 7166: 
 7167: sub get_codes {
 7168:     my ($old_name, $cdom, $cnum) = @_;
 7169:     if (!$old_name) {
 7170: 	$old_name=$env{'form.scantron_CODElist'};
 7171:     }
 7172:     if (!$cdom) {
 7173: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7174:     }
 7175:     if (!$cnum) {
 7176: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7177:     }
 7178:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7179: 				    $cdom,$cnum);
 7180:     my %allcodes;
 7181:     if ($result{"type\0$old_name"} eq 'number') {
 7182: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7183:     } else {
 7184: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7185:     }
 7186:     return %allcodes;
 7187: }
 7188: 
 7189: =pod
 7190: 
 7191: =item scantron_validate_CODE
 7192: 
 7193:    Validates all scanlines in the selected file to not have any
 7194:    invalid or underspecified CODEs and that none of the codes are
 7195:    duplicated if this was requested.
 7196: 
 7197: =cut
 7198: 
 7199: sub scantron_validate_CODE {
 7200:     my ($r,$currentphase) = @_;
 7201:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7202:     if ($scantron_config{'CODElocation'} &&
 7203: 	$scantron_config{'CODEstart'} &&
 7204: 	$scantron_config{'CODElength'}) {
 7205: 	if (!defined($env{'form.scantron_CODElist'})) {
 7206: 	    &FIXME_blow_up()
 7207: 	}
 7208:     } else {
 7209: 	return (0,$currentphase+1);
 7210:     }
 7211:     
 7212:     my %usedCODEs;
 7213: 
 7214:     my %allcodes=&get_codes();
 7215: 
 7216:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7217: 
 7218:     my ($scanlines,$scan_data)=&scantron_getfile();
 7219:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7220: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7221: 	if ($line=~/^[\s\cz]*$/) { next; }
 7222: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7223: 						 $scan_data);
 7224: 	my $CODE=$$scan_record{'scantron.CODE'};
 7225: 	my $error=0;
 7226: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7227: 	    &scantron_get_correction($r,$i,$scan_record,
 7228: 				     \%scantron_config,
 7229: 				     $line,'incorrectCODE',\%allcodes);
 7230: 	    return(1,$currentphase);
 7231: 	}
 7232: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7233: 	    && !$$scan_record{'scantron.useCODE'}) {
 7234: 	    &scantron_get_correction($r,$i,$scan_record,
 7235: 				     \%scantron_config,
 7236: 				     $line,'incorrectCODE',\%allcodes);
 7237: 	    return(1,$currentphase);
 7238: 	}
 7239: 	if (exists($usedCODEs{$CODE}) 
 7240: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7241: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7242: 	    &scantron_get_correction($r,$i,$scan_record,
 7243: 				     \%scantron_config,
 7244: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7245: 	    return(1,$currentphase);
 7246: 	}
 7247: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7248:     }
 7249:     return (0,$currentphase+1);
 7250: }
 7251: 
 7252: =pod
 7253: 
 7254: =item scantron_validate_doublebubble
 7255: 
 7256:    Validates all scanlines in the selected file to not have any
 7257:    bubble lines with multiple bubbles marked.
 7258: 
 7259: =cut
 7260: 
 7261: sub scantron_validate_doublebubble {
 7262:     my ($r,$currentphase) = @_;
 7263:     #get student info
 7264:     my $classlist=&Apache::loncoursedata::get_classlist();
 7265:     my %idmap=&username_to_idmap($classlist);
 7266: 
 7267:     #get scantron line setup
 7268:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7269:     my ($scanlines,$scan_data)=&scantron_getfile();
 7270:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7271: 
 7272:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7273: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7274: 	if ($line=~/^[\s\cz]*$/) { next; }
 7275: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7276: 						 $scan_data);
 7277: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7278: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7279: 				 'doublebubble',
 7280: 				 $$scan_record{'scantron.doubleerror'});
 7281:     	return (1,$currentphase);
 7282:     }
 7283:     return (0,$currentphase+1);
 7284: }
 7285: 
 7286: =pod
 7287: 
 7288: =item scantron_get_maxbubble
 7289: 
 7290:    Returns the maximum number of bubble lines that are expected to
 7291:    occur. Does this by walking the selected sequence rendering the
 7292:    resource and then checking &Apache::lonxml::get_problem_counter()
 7293:    for what the current value of the problem counter is.
 7294: 
 7295:    Caches the results to $env{'form.scantron_maxbubble'},
 7296:    $env{'form.scantron.bubble_lines.n'}, 
 7297:    $env{'form.scantron.first_bubble_line.n'} and
 7298:    $env{"form.scantron.sub_bubblelines.n"}
 7299:    which are the total number of bubble, lines, the number of bubble
 7300:    lines for response n and number of the first bubble line for response n,
 7301:    and a comma separated list of numbers of bubble lines for sub-questions
 7302:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7303: 
 7304: =cut
 7305: 
 7306: sub scantron_get_maxbubble {
 7307:     if (defined($env{'form.scantron_maxbubble'}) &&
 7308: 	$env{'form.scantron_maxbubble'}) {
 7309: 	&restore_bubble_lines();
 7310: 	return $env{'form.scantron_maxbubble'};
 7311:     }
 7312: 
 7313:     my (undef, undef, $sequence) =
 7314: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7315: 
 7316:     my $navmap=Apache::lonnavmaps::navmap->new();
 7317:     my $map=$navmap->getResourceByUrl($sequence);
 7318:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7319: 
 7320:     &Apache::lonxml::clear_problem_counter();
 7321: 
 7322:     my $uname       = $env{'form.student'};
 7323:     my $udom        = $env{'form.userdom'};
 7324:     my $cid         = $env{'request.course.id'};
 7325:     my $total_lines = 0;
 7326:     %bubble_lines_per_response = ();
 7327:     %first_bubble_line         = ();
 7328:     %subdivided_bubble_lines   = ();
 7329:     %responsetype_per_response = ();
 7330:   
 7331:     my $response_number = 0;
 7332:     my $bubble_line     = 0;
 7333:     foreach my $resource (@resources) {
 7334:         my $symb = $resource->symb();
 7335: 
 7336:         my (@parts,@allparts,@possible_parts);
 7337: 
 7338:         # Need to retrieve part IDs and response IDs because essayresponse,
 7339:         # reactionresponse and organicresponse items are not included in 
 7340:         # $analysis{'parts'} from lonnet::ssi.  
 7341:         if (ref($resource->parts()) eq 'ARRAY') {
 7342:             foreach my $part (@{$resource->parts()}) {
 7343:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
 7344:                     my @resp_ids = $resource->responseIds($part);
 7345:                     foreach my $id (@resp_ids) {
 7346:                         my $part_id = $part.'.'.$id;
 7347:                         push(@possible_parts,$part_id);
 7348:                     }
 7349:                 }
 7350:             }
 7351:         }
 7352: 
 7353:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7354:                                         ('symb' => $symb,
 7355:                                          'grade_target' => 'analyze',
 7356:                                          'grade_courseid' => $cid,
 7357:                                          'grade_domain' => $udom,
 7358:                                          'grade_username' => $uname));
 7359:         my (undef, $an) =
 7360:             split(/_HASH_REF__/,$result, 2);
 7361: 
 7362: 	my %analysis = &Apache::lonnet::str2hash($an);
 7363: 
 7364:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7365:             foreach my $part (@{$analysis{'parts'}}) {
 7366:                 my ($id,$respid) = split(/\./,$part);
 7367:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7368:                     push(@parts,$part);
 7369:                 }
 7370:             }
 7371:         }
 7372:         # Add part_ids for any essayresponse, reactionresponse or 
 7373:         # organicresponse items. 
 7374:         foreach my $part_id (@possible_parts) {
 7375:             if (grep(/^\Q$part_id\E$/,@parts)) {
 7376:                 push(@allparts,$part_id);
 7377:             } else {
 7378:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
 7379:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
 7380:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
 7381:                     push(@allparts,$part_id);
 7382:                 }
 7383:             }
 7384:         }
 7385: 
 7386: 	foreach my $part_id (@allparts) {
 7387:             my $lines;
 7388: 
 7389: 	    # TODO - make this a persistent hash not an array.
 7390: 
 7391:             # optionresponse, matchresponse and rankresponse type items 
 7392:             # render as separate sub-questions in exam mode.
 7393:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
 7394:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
 7395:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
 7396:                 my ($numbub,$numshown);
 7397:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
 7398:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
 7399:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
 7400:                     }
 7401:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
 7402:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
 7403:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
 7404:                     }
 7405:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
 7406:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
 7407:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
 7408:                     }
 7409:                 }
 7410:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
 7411:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
 7412:                 }
 7413:                 my $bubbles_per_line = 10;
 7414:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7415:                 if (($numbub % $bubbles_per_line) != 0) {
 7416:                     $inner_bubble_lines++;
 7417:                 }
 7418:                 for (my $i=0; $i<$numshown; $i++) {
 7419:                     $subdivided_bubble_lines{$response_number} .= 
 7420:                         $inner_bubble_lines.',';
 7421:                 }
 7422:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7423:                 $lines = $numshown * $inner_bubble_lines;
 7424:             } else {
 7425:                 $lines = $analysis{"$part_id.bubble_lines"};
 7426:             } 
 7427: 
 7428:             $first_bubble_line{$response_number} = $bubble_line;
 7429: 	    $bubble_lines_per_response{$response_number} = $lines;
 7430:             $responsetype_per_response{$response_number} = 
 7431:                 $analysis{$part_id.'.type'};
 7432: 	    $response_number++;
 7433: 
 7434: 	    $bubble_line +=  $lines;
 7435: 	    $total_lines +=  $lines;
 7436: 	}
 7437: 
 7438:     }
 7439:     &Apache::lonnet::delenv('scantron\.');
 7440: 
 7441:     &save_bubble_lines();
 7442:     $env{'form.scantron_maxbubble'} =
 7443: 	$total_lines;
 7444:     return $env{'form.scantron_maxbubble'};
 7445: }
 7446: 
 7447: =pod
 7448: 
 7449: =item scantron_validate_missingbubbles
 7450: 
 7451:    Validates all scanlines in the selected file to not have any
 7452:     answers that don't have bubbles that have not been verified
 7453:     to be bubble free.
 7454: 
 7455: =cut
 7456: 
 7457: sub scantron_validate_missingbubbles {
 7458:     my ($r,$currentphase) = @_;
 7459:     #get student info
 7460:     my $classlist=&Apache::loncoursedata::get_classlist();
 7461:     my %idmap=&username_to_idmap($classlist);
 7462: 
 7463:     #get scantron line setup
 7464:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7465:     my ($scanlines,$scan_data)=&scantron_getfile();
 7466:     my $max_bubble=&scantron_get_maxbubble();
 7467:     if (!$max_bubble) { $max_bubble=2**31; }
 7468:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7469: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7470: 	if ($line=~/^[\s\cz]*$/) { next; }
 7471: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7472: 						 $scan_data);
 7473: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7474: 	my @to_correct;
 7475: 	
 7476: 	# Probably here's where the error is...
 7477: 
 7478: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7479:             my $lastbubble;
 7480:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7481:                my $question = $1;
 7482:                my $subquestion = $2;
 7483:                if (!defined($first_bubble_line{$question -1})) { next; }
 7484:                my $first = $first_bubble_line{$question-1};
 7485:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7486:                my $subcount = 1;
 7487:                while ($subcount<$subquestion) {
 7488:                    $first += $subans[$subcount-1];
 7489:                    $subcount ++;
 7490:                }
 7491:                my $count = $subans[$subquestion-1];
 7492:                $lastbubble = $first + $count;
 7493:             } else {
 7494:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7495:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7496:             }
 7497:             if ($lastbubble > $max_bubble) { next; }
 7498: 	    push(@to_correct,$missing);
 7499: 	}
 7500: 	if (@to_correct) {
 7501: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7502: 				     $line,'missingbubble',\@to_correct);
 7503: 	    return (1,$currentphase);
 7504: 	}
 7505: 
 7506:     }
 7507:     return (0,$currentphase+1);
 7508: }
 7509: 
 7510: =pod
 7511: 
 7512: =item scantron_process_students
 7513: 
 7514:    Routine that does the actual grading of the bubble sheet information.
 7515: 
 7516:    The parsed scanline hash is added to %env 
 7517: 
 7518:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7519:    foreach resource , with the form data of
 7520: 
 7521: 	'submitted'     =>'scantron' 
 7522: 	'grade_target'  =>'grade',
 7523: 	'grade_username'=> username of student
 7524: 	'grade_domain'  => domain of student
 7525: 	'grade_courseid'=> of course
 7526: 	'grade_symb'    => symb of resource to grade
 7527: 
 7528:     This triggers a grading pass. The problem grading code takes care
 7529:     of converting the bubbled letter information (now in %env) into a
 7530:     valid submission.
 7531: 
 7532: =cut
 7533: 
 7534: sub scantron_process_students {
 7535:     my ($r) = @_;
 7536: 
 7537:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7538:     my ($symb)=&get_symb($r);
 7539:     if (!$symb) {
 7540: 	return '';
 7541:     }
 7542:     my $default_form_data=&defaultFormData($symb);
 7543: 
 7544:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7545:     my ($scanlines,$scan_data)=&scantron_getfile();
 7546:     my $classlist=&Apache::loncoursedata::get_classlist();
 7547:     my %idmap=&username_to_idmap($classlist);
 7548:     my $navmap=Apache::lonnavmaps::navmap->new();
 7549:     my $map=$navmap->getResourceByUrl($sequence);
 7550:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7551: #    $r->print("geto ".scalar(@resources)."<br />");
 7552:     my $result= <<SCANTRONFORM;
 7553: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7554:   <input type="hidden" name="command" value="scantron_configphase" />
 7555:   $default_form_data
 7556: SCANTRONFORM
 7557:     $r->print($result);
 7558: 
 7559:     my @delayqueue;
 7560:     my %completedstudents;
 7561:     
 7562:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7563:     my $count=&get_todo_count($scanlines,$scan_data);
 7564:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7565:  				    'Scantron Progress',$count,
 7566: 				    'inline',undef,'scantronupload');
 7567:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7568: 					  'Processing first student');
 7569:     my $start=&Time::HiRes::time();
 7570:     my $i=-1;
 7571:     my ($uname,$udom,$started);
 7572: 
 7573:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7574:     
 7575: 
 7576:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7577:     # the user and return.
 7578: 
 7579:     if ($ssi_error) {
 7580: 	$r->print("</form>");
 7581: 	&ssi_print_error($r);
 7582: 	$r->print(&show_grading_menu_form($symb));
 7583:         &Apache::lonnet::remove_lock($lock);
 7584: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7585:     }
 7586: 
 7587:     while ($i<$scanlines->{'count'}) {
 7588:  	($uname,$udom)=('','');
 7589:  	$i++;
 7590:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7591:  	if ($line=~/^[\s\cz]*$/) { next; }
 7592: 	if ($started) {
 7593: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7594: 						     'last student');
 7595: 	}
 7596: 	$started=1;
 7597:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7598:  						 $scan_data);
 7599:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7600:  					      \%idmap,$i)) {
 7601:   	    &scantron_add_delay(\@delayqueue,$line,
 7602:  				'Unable to find a student that matches',1);
 7603:  	    next;
 7604:   	}
 7605:  	if (exists $completedstudents{$uname}) {
 7606:  	    &scantron_add_delay(\@delayqueue,$line,
 7607:  				'Student '.$uname.' has multiple sheets',2);
 7608:  	    next;
 7609:  	}
 7610:   	($uname,$udom)=split(/:/,$uname);
 7611: 
 7612: 	&Apache::lonxml::clear_problem_counter();
 7613:   	&Apache::lonnet::appenv($scan_record);
 7614: 
 7615: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7616: 	    &scantron_putfile($scanlines,$scan_data);
 7617: 	}
 7618: 	
 7619: 	my $i=0;
 7620: 	foreach my $resource (@resources) {
 7621: 	    $i++;
 7622: 	    my %form=('submitted'     =>'scantron',
 7623: 		      'grade_target'  =>'grade',
 7624: 		      'grade_username'=>$uname,
 7625: 		      'grade_domain'  =>$udom,
 7626: 		      'grade_courseid'=>$env{'request.course.id'},
 7627: 		      'grade_symb'    =>$resource->symb());
 7628: 	    if (exists($scan_record->{'scantron.CODE'})
 7629: 		&& 
 7630: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 7631: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 7632: 	    } else {
 7633: 		$form{'CODE'}='';
 7634: 	    } 
 7635: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
 7636: 	    if ($ssi_error) {
 7637: 		$ssi_error = 0;	# So end of handler error message does not trigger.
 7638: 		$r->print("</form>");
 7639: 		&ssi_print_error($r);
 7640: 		$r->print(&show_grading_menu_form($symb));
 7641:                 &Apache::lonnet::remove_lock($lock);
 7642: 		return '';	# Why return ''?  Beats me.
 7643: 	    }
 7644: 
 7645: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 7646: 	}
 7647: 	$completedstudents{$uname}={'line'=>$line};
 7648: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7649:     } continue {
 7650: 	&Apache::lonxml::clear_problem_counter();
 7651: 	&Apache::lonnet::delenv('scantron\.');
 7652:     }
 7653:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7654:     &Apache::lonnet::remove_lock($lock);
 7655: #    my $lasttime = &Time::HiRes::time()-$start;
 7656: #    $r->print("<p>took $lasttime</p>");
 7657: 
 7658:     $r->print("</form>");
 7659:     $r->print(&show_grading_menu_form($symb));
 7660:     return '';
 7661: }
 7662: 
 7663: =pod
 7664: 
 7665: =item scantron_upload_scantron_data
 7666: 
 7667:     Creates the screen for adding a new bubble sheet data file to a course.
 7668: 
 7669: =cut
 7670: 
 7671: sub scantron_upload_scantron_data {
 7672:     my ($r)=@_;
 7673:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7674:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7675: 							  'domainid',
 7676: 							  'coursename');
 7677:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7678: 						   'domainid');
 7679:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7680:     $r->print('
 7681: <script type="text/javascript" language="javascript">
 7682:     function checkUpload(formname) {
 7683: 	if (formname.upfile.value == "") {
 7684: 	    alert("Please use the browse button to select a file from your local directory.");
 7685: 	    return false;
 7686: 	}
 7687: 	formname.submit();
 7688:     }
 7689: </script>
 7690: 
 7691: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7692: '.$default_form_data.'
 7693: <table>
 7694: <tr><td>'.$select_link.'                             </td></tr>
 7695: <tr><td>'.&mt('Course ID:').'     </td>
 7696:     <td><input name="courseid"   type="text" />      </td></tr>
 7697: <tr><td>'.&mt('Course Name:').'   </td>
 7698:     <td><input name="coursename" type="text" />      </td></tr>
 7699: <tr><td>'.&mt('Domain:').'        </td>
 7700:     <td>'.$domsel.'                                  </td></tr>
 7701: <tr><td>'.&mt('File to upload:').'</td>
 7702:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7703: </table>
 7704: <input name="command" value="scantronupload_save" type="hidden" />
 7705: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7706: </form>
 7707: ');
 7708:     return '';
 7709: }
 7710: 
 7711: =pod
 7712: 
 7713: =item scantron_upload_scantron_data_save
 7714: 
 7715:    Adds a provided bubble information data file to the course if user
 7716:    has the correct privileges to do so.  
 7717: 
 7718: =cut
 7719: 
 7720: sub scantron_upload_scantron_data_save {
 7721:     my($r)=@_;
 7722:     my ($symb)=&get_symb($r,1);
 7723:     my $doanotherupload=
 7724: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7725: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7726: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7727: 	'</form>'."\n";
 7728:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7729: 	!&Apache::lonnet::allowed('usc',
 7730: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7731: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7732: 	if ($symb) {
 7733: 	    $r->print(&show_grading_menu_form($symb));
 7734: 	} else {
 7735: 	    $r->print($doanotherupload);
 7736: 	}
 7737: 	return '';
 7738:     }
 7739:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7740:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7741:     my $fname=$env{'form.upfile.filename'};
 7742:     #FIXME
 7743:     #copied from lonnet::userfileupload()
 7744:     #make that function able to target a specified course
 7745:     # Replace Windows backslashes by forward slashes
 7746:     $fname=~s/\\/\//g;
 7747:     # Get rid of everything but the actual filename
 7748:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7749:     # Replace spaces by underscores
 7750:     $fname=~s/\s+/\_/g;
 7751:     # Replace all other weird characters by nothing
 7752:     $fname=~s/[^\w\.\-]//g;
 7753:     # See if there is anything left
 7754:     unless ($fname) { return 'error: no uploaded file'; }
 7755:     my $uploadedfile=$fname;
 7756:     $fname='scantron_orig_'.$fname;
 7757:     if (length($env{'form.upfile'}) < 2) {
 7758: 	$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>"));
 7759:     } else {
 7760: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7761: 	if ($result =~ m|^/uploaded/|) {
 7762: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7763: 			  (length($env{'form.upfile'})-1),
 7764: 			  '<span class="LC_filename">'.$result."</span>"));
 7765: 	} else {
 7766: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7767: 			  $result,
 7768: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7769: 
 7770: 	}
 7771:     }
 7772:     if ($symb) {
 7773: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7774:     } else {
 7775: 	$r->print($doanotherupload);
 7776:     }
 7777:     return '';
 7778: }
 7779: 
 7780: =pod
 7781: 
 7782: =item valid_file
 7783: 
 7784:    Validates that the requested bubble data file exists in the course.
 7785: 
 7786: =cut
 7787: 
 7788: sub valid_file {
 7789:     my ($requested_file)=@_;
 7790:     foreach my $filename (sort(&scantron_filenames())) {
 7791: 	if ($requested_file eq $filename) { return 1; }
 7792:     }
 7793:     return 0;
 7794: }
 7795: 
 7796: =pod
 7797: 
 7798: =item scantron_download_scantron_data
 7799: 
 7800:    Shows a list of the three internal files (original, corrected,
 7801:    skipped) for a specific bubble sheet data file that exists in the
 7802:    course.
 7803: 
 7804: =cut
 7805: 
 7806: sub scantron_download_scantron_data {
 7807:     my ($r)=@_;
 7808:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7809:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7810:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7811:     my $file=$env{'form.scantron_selectfile'};
 7812:     if (! &valid_file($file)) {
 7813: 	$r->print('
 7814: 	<p>
 7815: 	    '.&mt('The requested file name was invalid.').'
 7816:         </p>
 7817: ');
 7818: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7819: 	return;
 7820:     }
 7821:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7822:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7823:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7824:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7825:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7826:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7827:     $r->print('
 7828:     <p>
 7829: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7830: 	      '<a href="'.$orig.'">','</a>').'
 7831:     </p>
 7832:     <p>
 7833: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7834: 	      '<a href="'.$corrected.'">','</a>').'
 7835:     </p>
 7836:     <p>
 7837: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7838: 	      '<a href="'.$skipped.'">','</a>').'
 7839:     </p>
 7840: ');
 7841:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7842:     return '';
 7843: }
 7844: 
 7845: sub checkscantron_results {
 7846:     my ($r) = @_;
 7847:     my ($symb)=&get_symb($r);
 7848:     if (!$symb) {return '';}
 7849:     my $grading_menu_button=&show_grading_menu_form($symb);
 7850:     my $cid = $env{'request.course.id'};
 7851:     my %lettdig = (
 7852:                     A => 1,
 7853:                     B => 2,
 7854:                     C => 3,
 7855:                     D => 4,
 7856:                     E => 5,
 7857:                     F => 6,
 7858:                     G => 7,
 7859:                     H => 8,
 7860:                     I => 9,
 7861:                     J => 0,
 7862:                   );
 7863:     my $numletts = scalar(keys(%lettdig));
 7864:     my $cnum = $env{'course.'.$cid.'.num'};
 7865:     my $cdom = $env{'course.'.$cid.'.domain'};
 7866:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7867:     my %record;
 7868:     my %scantron_config =
 7869:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7870:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7871:     my $classlist=&Apache::loncoursedata::get_classlist();
 7872:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7873:     my $navmap=Apache::lonnavmaps::navmap->new();
 7874:     my $map=$navmap->getResourceByUrl($sequence);
 7875:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7876:     my (%scandata,%lastname,%bylast);
 7877:     $r->print('
 7878: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7879: 
 7880:     my @delayqueue;
 7881:     my %completedstudents;
 7882: 
 7883:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7884:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7885:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7886:                                     'inline',undef,'checkscantron');
 7887:     my ($username,$domain,$uname,$started);
 7888: 
 7889:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7890: 
 7891:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7892:                                           'Processing first student');
 7893:     my $start=&Time::HiRes::time();
 7894:     my $i=-1;
 7895: 
 7896:     while ($i<$scanlines->{'count'}) {
 7897:         ($username,$domain,$uname)=('','','');
 7898:         $i++;
 7899:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7900:         if ($line=~/^[\s\cz]*$/) { next; }
 7901:         if ($started) {
 7902:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7903:                                                      'last student');
 7904:         }
 7905:         $started=1;
 7906:         my $scan_record=
 7907:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7908:                                                      $scan_data);
 7909:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7910:                                                               \%idmap,$i)) {
 7911:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7912:                                 'Unable to find a student that matches',1);
 7913:             next;
 7914:         }
 7915:         if (exists $completedstudents{$uname}) {
 7916:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7917:                                 'Student '.$uname.' has multiple sheets',2);
 7918:             next;
 7919:         }
 7920:         my $pid = $scan_record->{'scantron.ID'};
 7921:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7922:         push(@{$bylast{$lastname{$pid}}},$pid);
 7923:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7924:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7925:         chomp($scandata{$pid});
 7926:         $scandata{$pid} =~ s/\r$//;
 7927:         ($username,$domain)=split(/:/,$uname);
 7928:         my $counter = -1;
 7929:         my (%expected,%startpos);
 7930:         foreach my $resource (@resources) {
 7931:             next if (!$resource->is_problem());
 7932:             my $symb = $resource->symb();
 7933:             my $partsref = $resource->parts();
 7934:             my @parts;
 7935:             my @part_ids = ();
 7936:             if (ref($partsref) eq 'ARRAY') {
 7937:                @parts = @{$partsref};
 7938:                foreach my $part (@parts) {
 7939:                    my @resp_ids = $resource->responseIds($part);
 7940:                    foreach my $resp (@resp_ids) {
 7941:                        $counter ++;
 7942:                        my $part_id = $part.'.'.$resp;
 7943:                        $expected{$part_id} = 0;
 7944:                        push(@part_ids,$part_id);
 7945:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7946:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7947:                            foreach my $item (@sub_lines) {
 7948:                                $expected{$part_id} += $item;
 7949:                            }
 7950:                        } else {
 7951:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7952:                        }
 7953:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7954:                    }
 7955:                 }
 7956:             }
 7957:             if ($symb) {
 7958:                 my %recorded;
 7959:                 my (%returnhash) =
 7960:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7961:                 if ($returnhash{'version'}) {
 7962:                     my %lasthash=();
 7963:                     my $version;
 7964:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
 7965:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7966:                             $lasthash{$key}=$returnhash{$version.':'.$key};
 7967:                         }
 7968:                     }
 7969:                     foreach my $key (keys(%lasthash)) {
 7970:                         if ($key =~ /\.scantron$/) {
 7971:                             my $value = &unescape($lasthash{$key});
 7972:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7973:                             if ($value eq '') {
 7974:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 7975:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
 7976:                                         $recorded{$part_id} .= $;
 7977:                                     }
 7978:                                 }
 7979:                             } else {
 7980:                                 my @tocheck;
 7981:                                 my @items = split(//,$value);
 7982:                                 if (($scantron_config{'Qon'} eq 'letter') ||
 7983:                                     ($scantron_config{'Qon'} eq 'number')) {
 7984:                                     if (@items < $expected{$part_id}) {
 7985:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
 7986:                                         my @singles = split(//,$fragment);
 7987:                                         foreach my $pos (@singles) {
 7988:                                             if ($pos eq ' ') {
 7989:                                                 push(@tocheck,$pos);
 7990:                                             } else {
 7991:                                                 my $next = shift(@items);
 7992:                                                 push(@tocheck,$next);
 7993:                                             }
 7994:                                         }
 7995:                                     } else {
 7996:                                         @tocheck = @items;
 7997:                                     }
 7998:                                     foreach my $letter (@tocheck) {
 7999:                                         if ($scantron_config{'Qon'} eq 'letter') {
 8000:                                             if ($letter !~ /^[A-J]$/) {
 8001:                                                 $letter = $scantron_config{'Qoff'};
 8002:                                             }
 8003:                                             $recorded{$part_id} .= $letter;
 8004:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
 8005:                                             my $digit;
 8006:                                             if ($letter !~ /^[A-J]$/) {
 8007:                                                 $digit = $scantron_config{'Qoff'};
 8008:                                             } else {
 8009:                                                 $digit = $lettdig{$letter};
 8010:                                             }
 8011:                                             $recorded{$part_id} .= $digit;
 8012:                                         }
 8013:                                     }
 8014:                                 } else {
 8015:                                     @tocheck = @items;
 8016:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
 8017:                                         my $curr_sub = shift(@tocheck);
 8018:                                         my $digit;
 8019:                                         if ($curr_sub =~ /^[A-J]$/) {
 8020:                                             $digit = $lettdig{$curr_sub}-1;
 8021:                                         }
 8022:                                         if ($curr_sub eq 'J') {
 8023:                                             $digit += scalar($numletts);
 8024:                                         }
 8025:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8026:                                             if ($j == $digit) {
 8027:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
 8028:                                             } else {
 8029:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8030:                                             }
 8031:                                         }
 8032:                                     }
 8033:                                 }
 8034:                             }
 8035:                         }
 8036:                     }
 8037:                 }
 8038:                 foreach my $part_id (@part_ids) {
 8039:                     if ($recorded{$part_id} eq '') {
 8040:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8041:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8042:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8043:                             }
 8044:                         }
 8045:                     }
 8046:                     $record{$pid} .= $recorded{$part_id};
 8047:                 }
 8048:             }
 8049:         }
 8050:     }
 8051:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8052:     $r->print('<br />');
 8053:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8054:     $passed = 0;
 8055:     $failed = 0;
 8056:     $numstudents = 0;
 8057:     foreach my $last (sort(keys(%bylast))) {
 8058:         if (ref($bylast{$last}) eq 'ARRAY') {
 8059:             foreach my $pid (sort(@{$bylast{$last}})) {
 8060:                 my $showscandata = $scandata{$pid};
 8061:                 my $showrecord = $record{$pid};
 8062:                 $showscandata =~ s/\s/&nbsp;/g;
 8063:                 $showrecord =~ s/\s/&nbsp;/g;
 8064:                 if ($scandata{$pid} eq $record{$pid}) {
 8065:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8066:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8067: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8068: '</tr>'."\n".
 8069: '<tr class="'.$css_class.'">'."\n".
 8070: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8071:                     $passed ++;
 8072:                 } else {
 8073:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8074:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8075: '</tr>'."\n".
 8076: '<tr class="'.$css_class.'">'."\n".
 8077: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8078: '</tr>'."\n";
 8079:                     $failed ++;
 8080:                 }
 8081:                 $numstudents ++;
 8082:             }
 8083:         }
 8084:     }
 8085:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8086:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8087:     if ($passed) {
 8088:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8089:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8090:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8091:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8092:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8093:                  $okstudents."\n".
 8094:                  &Apache::loncommon::end_data_table().'<br />');
 8095:     }
 8096:     if ($failed) {
 8097:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8098:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8099:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8100:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8101:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8102:                  $badstudents."\n".
 8103:                  &Apache::loncommon::end_data_table()).'<br />'.
 8104:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 8105:     }
 8106:     $r->print('</form><br />'.$grading_menu_button);
 8107:     return;
 8108: }
 8109: 
 8110: =pod
 8111: 
 8112: =back
 8113: 
 8114: =cut
 8115: 
 8116: #-------- end of section for handling grading scantron forms -------
 8117: #
 8118: #-------------------------------------------------------------------
 8119: 
 8120: #-------------------------- Menu interface -------------------------
 8121: #
 8122: #--- Show a Grading Menu button - Calls the next routine ---
 8123: sub show_grading_menu_form {
 8124:     my ($symb)=@_;
 8125:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8126: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8127: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8128: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8129: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8130: 	'</form>'."\n";
 8131:     return $result;
 8132: }
 8133: 
 8134: # -- Retrieve choices for grading form
 8135: sub savedState {
 8136:     my %savedState = ();
 8137:     if ($env{'form.saveState'}) {
 8138: 	foreach (split(/:/,$env{'form.saveState'})) {
 8139: 	    my ($key,$value) = split(/=/,$_,2);
 8140: 	    $savedState{$key} = $value;
 8141: 	}
 8142:     }
 8143:     return \%savedState;
 8144: }
 8145: 
 8146: sub grading_menu {
 8147:     my ($request) = @_;
 8148:     my ($symb)=&get_symb($request);
 8149:     if (!$symb) {return '';}
 8150:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8151:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8152: 
 8153:     $request->print($table);
 8154:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8155:                   'handgrade'=>$hdgrade,
 8156:                   'probTitle'=>$probTitle,
 8157:                   'command'=>'submit_options',
 8158:                   'saveState'=>"",
 8159:                   'gradingMenu'=>1,
 8160:                   'showgrading'=>"yes");
 8161:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8162:     my @menu = ({ url => $url,
 8163:                      name => &mt('Manual Grading/View Submissions'),
 8164:                      short_description => 
 8165:     &mt('Start the process of hand grading submissions.'),
 8166:                  });
 8167:     $fields{'command'} = 'csvform';
 8168:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8169:     push(@menu, { url => $url,
 8170:                    name => &mt('Upload Scores'),
 8171:                    short_description => 
 8172:             &mt('Specify a file containing the class scores for current resource.')});
 8173:     $fields{'command'} = 'processclicker';
 8174:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8175:     push(@menu, { url => $url,
 8176:                    name => &mt('Process Clicker'),
 8177:                    short_description => 
 8178:             &mt('Specify a file containing the clicker information for this resource.')});
 8179:     $fields{'command'} = 'scantron_selectphase';
 8180:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8181:     push(@menu, { url => $url,
 8182:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8183:                    short_description => 
 8184:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8185:     $fields{'command'} = 'verify';
 8186:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8187:     push(@menu, { url => "",
 8188:                    name => &mt('Verify Receipt'),
 8189:                    short_description => 
 8190:             &mt('')});
 8191:     #
 8192:     # Create the menu
 8193:     my $Str;
 8194:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8195:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8196:     $Str .= '<input type="hidden" name="command" value="" />'.
 8197:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8198: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8199: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8200: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8201: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8202: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8203: 
 8204:     foreach my $menudata (@menu) {
 8205:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8206:             $Str .='    <h3><a '.
 8207:                 $menudata->{'jscript'}.
 8208:                 ' href="'.
 8209:                 $menudata->{'url'}.'" >'.
 8210:                 $menudata->{'name'}."</a></h3>\n";
 8211:         } else {
 8212:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8213:                 $menudata->{'jscript'}.
 8214:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8215:                 ' /> '.
 8216: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8217:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8218:         }
 8219:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8220:             "\n";
 8221:     }
 8222:     $Str .="</form>\n";
 8223:     $request->print(<<GRADINGMENUJS);
 8224: <script type="text/javascript" language="javascript">
 8225:     function checkChoice(formname,val,cmdx) {
 8226: 	if (val <= 2) {
 8227: 	    var cmd = radioSelection(formname.radioChoice);
 8228: 	    var cmdsave = cmd;
 8229: 	} else {
 8230: 	    cmd = cmdx;
 8231: 	    cmdsave = 'submission';
 8232: 	}
 8233: 	formname.command.value = cmd;
 8234: 	if (val < 5) formname.submit();
 8235: 	if (val == 5) {
 8236: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8237: 	        return false;
 8238: 	    } else {
 8239: 	        formname.submit();
 8240: 	    }
 8241: 	}
 8242:     }
 8243: 
 8244:     function checkReceiptNo(formname,nospace) {
 8245: 	var receiptNo = formname.receipt.value;
 8246: 	var checkOpt = false;
 8247: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8248: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8249: 	if (checkOpt) {
 8250: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8251: 	    formname.receipt.value = "";
 8252: 	    formname.receipt.focus();
 8253: 	    return false;
 8254: 	}
 8255: 	return true;
 8256:     }
 8257: </script>
 8258: GRADINGMENUJS
 8259:     &commonJSfunctions($request);
 8260:     return $Str;    
 8261: }
 8262: 
 8263: 
 8264: #--- Displays the submissions first page -------
 8265: sub submit_options {
 8266:     my ($request) = @_;
 8267:     my ($symb)=&get_symb($request);
 8268:     if (!$symb) {return '';}
 8269:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8270: 
 8271:     $request->print(<<GRADINGMENUJS);
 8272: <script type="text/javascript" language="javascript">
 8273:     function checkChoice(formname,val,cmdx) {
 8274: 	if (val <= 2) {
 8275: 	    var cmd = radioSelection(formname.radioChoice);
 8276: 	    var cmdsave = cmd;
 8277: 	} else {
 8278: 	    cmd = cmdx;
 8279: 	    cmdsave = 'submission';
 8280: 	}
 8281: 	formname.command.value = cmd;
 8282: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8283: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8284: 	if (val < 5) formname.submit();
 8285: 	if (val == 5) {
 8286: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8287: 	    formname.submit();
 8288: 	}
 8289: 	if (val < 7) formname.submit();
 8290:     }
 8291: 
 8292:     function checkReceiptNo(formname,nospace) {
 8293: 	var receiptNo = formname.receipt.value;
 8294: 	var checkOpt = false;
 8295: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8296: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8297: 	if (checkOpt) {
 8298: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8299: 	    formname.receipt.value = "";
 8300: 	    formname.receipt.focus();
 8301: 	    return false;
 8302: 	}
 8303: 	return true;
 8304:     }
 8305: </script>
 8306: GRADINGMENUJS
 8307:     &commonJSfunctions($request);
 8308:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8309:     my $result;
 8310:     my (undef,$sections) = &getclasslist('all','0');
 8311:     my $savedState = &savedState();
 8312:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8313:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8314:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8315:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8316: 
 8317:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8318: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8319: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8320: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8321: 	'<input type="hidden" name="command"     value="" />'."\n".
 8322: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8323: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8324: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8325: 
 8326:     $result.='
 8327:     <div class="LC_grade_select_mode">
 8328:       <div class="LC_grade_select_mode_current">
 8329:         <h2>
 8330:           '.&mt('Grade Current Resource').'
 8331:         </h2>
 8332:         <div class="LC_grade_select_mode_body">
 8333:           <div class="LC_grades_resource_info">
 8334:            '.$table.'
 8335:           </div>
 8336:           <div class="LC_grade_select_mode_selector">
 8337:              <div class="LC_grade_select_mode_selector_header">
 8338:                 '.&mt('Sections').'
 8339:              </div>
 8340:              <div class="LC_grade_select_mode_selector_body">
 8341: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8342:     if (ref($sections)) {
 8343: 	foreach my $section (sort(@$sections)) {
 8344: 	    $result.='<option value="'.$section.'" '.
 8345: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8346: 	}
 8347:     }
 8348:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8349:     $result.='
 8350:              </div>
 8351:           </div>
 8352:           <div class="LC_grade_select_mode_selector">
 8353:              <div class="LC_grade_select_mode_selector_header">
 8354:                 '.&mt('Groups').'
 8355:              </div>
 8356:              <div class="LC_grade_select_mode_selector_body">
 8357:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8358:              </div>
 8359:           </div>
 8360:           <div class="LC_grade_select_mode_selector">
 8361:              <div class="LC_grade_select_mode_selector_header">
 8362:                 '.&mt('Access Status').'
 8363:              </div>
 8364:              <div class="LC_grade_select_mode_selector_body">
 8365:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8366:              </div>
 8367:           </div>
 8368:           <div class="LC_grade_select_mode_selector">
 8369:              <div class="LC_grade_select_mode_selector_header">
 8370:                 '.&mt('Submission Status').'
 8371:              </div>
 8372:              <div class="LC_grade_select_mode_selector_body">
 8373:                <select name="submitonly" size="5">
 8374: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8375: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8376: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8377: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8378:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8379:                </select>
 8380:              </div>
 8381:           </div>
 8382:           <div class="LC_grade_select_mode_type_body">
 8383:             <div class="LC_grade_select_mode_type">
 8384:               <label>
 8385:                 <input type="radio" name="radioChoice" value="submission" '.
 8386:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8387:              &mt('Select individual students to grade and view submissions.').'
 8388: 	      </label> 
 8389:             </div>
 8390:             <div class="LC_grade_select_mode_type">
 8391: 	      <label>
 8392:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8393:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8394:                     &mt('Grade all selected students in a grading table.').'
 8395:               </label>
 8396:             </div>
 8397:             <div class="LC_grade_select_mode_type">
 8398: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8399:             </div>
 8400:           </div>
 8401:         </div>
 8402:       </div>
 8403:       <div class="LC_grade_select_mode_page">
 8404:         <h2>
 8405:          '.&mt('Grade Complete Folder for One Student').'
 8406:         </h2>
 8407:         <div class="LC_grades_select_mode_body">
 8408:           <div class="LC_grade_select_mode_type_body">
 8409:             <div class="LC_grade_select_mode_type">
 8410:               <label>
 8411:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8412: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8413:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8414:               </label>
 8415:             </div>
 8416:             <div class="LC_grade_select_mode_type">
 8417: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8418:             </div>
 8419:           </div>
 8420:         </div>
 8421:       </div>
 8422:     </div>
 8423:   </form>';
 8424:     $result .= &show_grading_menu_form($symb);
 8425:     return $result;
 8426: }
 8427: 
 8428: sub reset_perm {
 8429:     undef(%perm);
 8430: }
 8431: 
 8432: sub init_perm {
 8433:     &reset_perm();
 8434:     foreach my $test_perm ('vgr','mgr','opa') {
 8435: 
 8436: 	my $scope = $env{'request.course.id'};
 8437: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8438: 
 8439: 	    $scope .= '/'.$env{'request.course.sec'};
 8440: 	    if ( $perm{$test_perm}=
 8441: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8442: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8443: 	    } else {
 8444: 		delete($perm{$test_perm});
 8445: 	    }
 8446: 	}
 8447:     }
 8448: }
 8449: 
 8450: sub gather_clicker_ids {
 8451:     my %clicker_ids;
 8452: 
 8453:     my $classlist = &Apache::loncoursedata::get_classlist();
 8454: 
 8455:     # Set up a couple variables.
 8456:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8457:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8458:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8459: 
 8460:     foreach my $student (keys(%$classlist)) {
 8461:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8462:         my $username = $classlist->{$student}->[$username_idx];
 8463:         my $domain   = $classlist->{$student}->[$domain_idx];
 8464:         my $clickers =
 8465: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8466:         foreach my $id (split(/\,/,$clickers)) {
 8467:             $id=~s/^[\#0]+//;
 8468:             $id=~s/[\-\:]//g;
 8469:             if (exists($clicker_ids{$id})) {
 8470: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8471:             } else {
 8472: 		$clicker_ids{$id}=$username.':'.$domain;
 8473:             }
 8474:         }
 8475:     }
 8476:     return %clicker_ids;
 8477: }
 8478: 
 8479: sub gather_adv_clicker_ids {
 8480:     my %clicker_ids;
 8481:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8482:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8483:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8484:     foreach my $element (sort(keys(%coursepersonnel))) {
 8485:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8486:             my ($puname,$pudom)=split(/\:/,$person);
 8487:             my $clickers =
 8488: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8489:             foreach my $id (split(/\,/,$clickers)) {
 8490: 		$id=~s/^[\#0]+//;
 8491:                 $id=~s/[\-\:]//g;
 8492: 		if (exists($clicker_ids{$id})) {
 8493: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8494: 		} else {
 8495: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8496: 		}
 8497:             }
 8498:         }
 8499:     }
 8500:     return %clicker_ids;
 8501: }
 8502: 
 8503: sub clicker_grading_parameters {
 8504:     return ('gradingmechanism' => 'scalar',
 8505:             'upfiletype' => 'scalar',
 8506:             'specificid' => 'scalar',
 8507:             'pcorrect' => 'scalar',
 8508:             'pincorrect' => 'scalar');
 8509: }
 8510: 
 8511: sub process_clicker {
 8512:     my ($r)=@_;
 8513:     my ($symb)=&get_symb($r);
 8514:     if (!$symb) {return '';}
 8515:     my $result=&checkforfile_js();
 8516:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8517:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8518:     $result.=$table;
 8519:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8520:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8521:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8522:         '.</b></td></tr>'."\n";
 8523:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8524: # Attempt to restore parameters from last session, set defaults if not present
 8525:     my %Saveable_Parameters=&clicker_grading_parameters();
 8526:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8527:                                                  \%Saveable_Parameters);
 8528:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8529:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8530:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8531:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8532: 
 8533:     my %checked;
 8534:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8535:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8536:           $checked{$gradingmechanism}="checked='checked'";
 8537:        }
 8538:     }
 8539: 
 8540:     my $upload=&mt("Upload File");
 8541:     my $type=&mt("Type");
 8542:     my $attendance=&mt("Award points just for participation");
 8543:     my $personnel=&mt("Correctness determined from response by course personnel");
 8544:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8545:     my $given=&mt("Correctness determined from given list of answers").' '.
 8546:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8547:     my $pcorrect=&mt("Percentage points for correct solution");
 8548:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8549:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8550: 						   ('iclicker' => 'i>clicker',
 8551:                                                     'interwrite' => 'interwrite PRS'));
 8552:     $symb = &Apache::lonenc::check_encrypt($symb);
 8553:     $result.=<<ENDUPFORM;
 8554: <script type="text/javascript">
 8555: function sanitycheck() {
 8556: // Accept only integer percentages
 8557:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8558:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8559: // Find out grading choice
 8560:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8561:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8562:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8563:       }
 8564:    }
 8565: // By default, new choice equals user selection
 8566:    newgradingchoice=gradingchoice;
 8567: // Not good to give more points for false answers than correct ones
 8568:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8569:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8570:    }
 8571: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8572:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8573:       document.forms.gradesupload.pcorrect.value=100;
 8574:       document.forms.gradesupload.pincorrect.value=100;
 8575:    }
 8576: // If the values are different, cannot be attendance only
 8577:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8578:        (gradingchoice=='attendance')) {
 8579:        newgradingchoice='personnel';
 8580:    }
 8581: // Change grading choice to new one
 8582:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8583:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8584:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8585:       } else {
 8586:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8587:       }
 8588:    }
 8589: // Remember the old state
 8590:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8591: }
 8592: </script>
 8593: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8594: <input type="hidden" name="symb" value="$symb" />
 8595: <input type="hidden" name="command" value="processclickerfile" />
 8596: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8597: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8598: <input type="file" name="upfile" size="50" />
 8599: <br /><label>$type: $selectform</label>
 8600: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8601: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8602: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8603: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8604: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8605: <br />&nbsp;&nbsp;&nbsp;
 8606: <input type="text" name="givenanswer" size="50" />
 8607: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8608: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8609: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8610: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8611: </form>
 8612: ENDUPFORM
 8613:     $result.='</td></tr></table>'."\n".
 8614:              '</td></tr></table><br /><br />'."\n";
 8615:     $result.=&show_grading_menu_form($symb);
 8616:     return $result;
 8617: }
 8618: 
 8619: sub process_clicker_file {
 8620:     my ($r)=@_;
 8621:     my ($symb)=&get_symb($r);
 8622:     if (!$symb) {return '';}
 8623: 
 8624:     my %Saveable_Parameters=&clicker_grading_parameters();
 8625:     &Apache::loncommon::store_course_settings('grades_clicker',
 8626:                                               \%Saveable_Parameters);
 8627: 
 8628:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8629:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8630: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8631: 	return $result.&show_grading_menu_form($symb);
 8632:     }
 8633:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8634:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8635:         return $result.&show_grading_menu_form($symb);
 8636:     }
 8637:     my $foundgiven=0;
 8638:     if ($env{'form.gradingmechanism'} eq 'given') {
 8639:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8640:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8641:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8642:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8643:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8644:         $foundgiven=$#answers+1;
 8645:     }
 8646:     my %clicker_ids=&gather_clicker_ids();
 8647:     my %correct_ids;
 8648:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8649: 	%correct_ids=&gather_adv_clicker_ids();
 8650:     }
 8651:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8652: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8653: 	   $correct_id=~tr/a-z/A-Z/;
 8654: 	   $correct_id=~s/\s//gs;
 8655: 	   $correct_id=~s/^[\#0]+//;
 8656:            $correct_id=~s/[\-\:]//g;
 8657:            if ($correct_id) {
 8658: 	      $correct_ids{$correct_id}='specified';
 8659:            }
 8660:         }
 8661:     }
 8662:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8663: 	$result.=&mt('Score based on attendance only');
 8664:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8665:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8666:     } else {
 8667: 	my $number=0;
 8668: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8669: 	foreach my $id (sort(keys(%correct_ids))) {
 8670: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8671: 	    if ($correct_ids{$id} eq 'specified') {
 8672: 		$result.=&mt('specified');
 8673: 	    } else {
 8674: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8675: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8676: 	    }
 8677: 	    $number++;
 8678: 	}
 8679:         $result.="</p>\n";
 8680: 	if ($number==0) {
 8681: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8682: 	    return $result.&show_grading_menu_form($symb);
 8683: 	}
 8684:     }
 8685:     if (length($env{'form.upfile'}) < 2) {
 8686:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8687: 		     '<span class="LC_error">',
 8688: 		     '</span>',
 8689: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8690:         return $result.&show_grading_menu_form($symb);
 8691:     }
 8692: 
 8693: # Were able to get all the info needed, now analyze the file
 8694: 
 8695:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8696:     $symb = &Apache::lonenc::check_encrypt($symb);
 8697:     my $heading=&mt('Scanning clicker file');
 8698:     $result.=(<<ENDHEADER);
 8699: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8700: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8701: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8702: <form method="post" action="/adm/grades" name="clickeranalysis">
 8703: <input type="hidden" name="symb" value="$symb" />
 8704: <input type="hidden" name="command" value="assignclickergrades" />
 8705: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8706: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8707: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8708: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8709: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8710: ENDHEADER
 8711:     if ($env{'form.gradingmechanism'} eq 'given') {
 8712:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8713:     } 
 8714:     my %responses;
 8715:     my @questiontitles;
 8716:     my $errormsg='';
 8717:     my $number=0;
 8718:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8719: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8720:     }
 8721:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8722:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8723:     }
 8724:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8725:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8726:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8727:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8728:              '<br />';
 8729:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8730:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8731:        return $result.&show_grading_menu_form($symb);
 8732:     } 
 8733: # Remember Question Titles
 8734: # FIXME: Possibly need delimiter other than ":"
 8735:     for (my $i=0;$i<$number;$i++) {
 8736:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8737:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8738:     }
 8739:     my $correct_count=0;
 8740:     my $student_count=0;
 8741:     my $unknown_count=0;
 8742: # Match answers with usernames
 8743: # FIXME: Possibly need delimiter other than ":"
 8744:     foreach my $id (keys(%responses)) {
 8745:        if ($correct_ids{$id}) {
 8746:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8747:           $correct_count++;
 8748:        } elsif ($clicker_ids{$id}) {
 8749:           if ($clicker_ids{$id}=~/\,/) {
 8750: # More than one user with the same clicker!
 8751:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8752:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8753:                            "<select name='multi".$id."'>";
 8754:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8755:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8756:              }
 8757:              $result.='</select>';
 8758:              $unknown_count++;
 8759:           } else {
 8760: # Good: found one and only one user with the right clicker
 8761:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8762:              $student_count++;
 8763:           }
 8764:        } else {
 8765:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8766:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8767:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8768:                    "\n".&mt("Domain").": ".
 8769:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8770:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8771:           $unknown_count++;
 8772:        }
 8773:     }
 8774:     $result.='<hr />'.
 8775:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8776:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8777:        if ($correct_count==0) {
 8778:           $errormsg.="Found no correct answers answers for grading!";
 8779:        } elsif ($correct_count>1) {
 8780:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8781:        }
 8782:     }
 8783:     if ($number<1) {
 8784:        $errormsg.="Found no questions.";
 8785:     }
 8786:     if ($errormsg) {
 8787:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8788:     } else {
 8789:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8790:     }
 8791:     $result.='</form></td></tr></table>'."\n".
 8792:              '</td></tr></table><br /><br />'."\n";
 8793:     return $result.&show_grading_menu_form($symb);
 8794: }
 8795: 
 8796: sub iclicker_eval {
 8797:     my ($questiontitles,$responses)=@_;
 8798:     my $number=0;
 8799:     my $errormsg='';
 8800:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8801:         my %components=&Apache::loncommon::record_sep($line);
 8802:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8803: 	if ($entries[0] eq 'Question') {
 8804: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8805: 		$$questiontitles[$number]=$entries[$i];
 8806: 		$number++;
 8807: 	    }
 8808: 	}
 8809: 	if ($entries[0]=~/^\#/) {
 8810: 	    my $id=$entries[0];
 8811: 	    my @idresponses;
 8812: 	    $id=~s/^[\#0]+//;
 8813: 	    for (my $i=0;$i<$number;$i++) {
 8814: 		my $idx=3+$i*6;
 8815: 		push(@idresponses,$entries[$idx]);
 8816: 	    }
 8817: 	    $$responses{$id}=join(',',@idresponses);
 8818: 	}
 8819:     }
 8820:     return ($errormsg,$number);
 8821: }
 8822: 
 8823: sub interwrite_eval {
 8824:     my ($questiontitles,$responses)=@_;
 8825:     my $number=0;
 8826:     my $errormsg='';
 8827:     my $skipline=1;
 8828:     my $questionnumber=0;
 8829:     my %idresponses=();
 8830:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8831:         my %components=&Apache::loncommon::record_sep($line);
 8832:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8833:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8834:         if ($entries[1] eq 'Response') { $skipline=1; }
 8835:         next if $skipline;
 8836:         if ($entries[0]!=$questionnumber) {
 8837:            $questionnumber=$entries[0];
 8838:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8839:            $number++;
 8840:         }
 8841:         my $id=$entries[4];
 8842:         $id=~s/^[\#0]+//;
 8843:         $id=~s/^v\d*\://i;
 8844:         $id=~s/[\-\:]//g;
 8845:         $idresponses{$id}[$number]=$entries[6];
 8846:     }
 8847:     foreach my $id (keys(%idresponses)) {
 8848:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8849:        $$responses{$id}=~s/^\s*\,//;
 8850:     }
 8851:     return ($errormsg,$number);
 8852: }
 8853: 
 8854: sub assign_clicker_grades {
 8855:     my ($r)=@_;
 8856:     my ($symb)=&get_symb($r);
 8857:     if (!$symb) {return '';}
 8858: # See which part we are saving to
 8859:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8860: # FIXME: This should probably look for the first handgradeable part
 8861:     my $part=$$partlist[0];
 8862: # Start screen output
 8863:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8864: 
 8865:     my $heading=&mt('Assigning grades based on clicker file');
 8866:     $result.=(<<ENDHEADER);
 8867: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8868: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8869: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8870: ENDHEADER
 8871: # Get correct result
 8872: # FIXME: Possibly need delimiter other than ":"
 8873:     my @correct=();
 8874:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8875:     my $number=$env{'form.number'};
 8876:     if ($gradingmechanism ne 'attendance') {
 8877:        foreach my $key (keys(%env)) {
 8878:           if ($key=~/^form\.correct\:/) {
 8879:              my @input=split(/\,/,$env{$key});
 8880:              for (my $i=0;$i<=$#input;$i++) {
 8881:                  if (($correct[$i]) && ($input[$i]) &&
 8882:                      ($correct[$i] ne $input[$i])) {
 8883:                     $result.='<br /><span class="LC_warning">'.
 8884:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8885:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8886:                  } elsif ($input[$i]) {
 8887:                     $correct[$i]=$input[$i];
 8888:                  }
 8889:              }
 8890:           }
 8891:        }
 8892:        for (my $i=0;$i<$number;$i++) {
 8893:           if (!$correct[$i]) {
 8894:              $result.='<br /><span class="LC_error">'.
 8895:                       &mt('No correct result given for question "[_1]"!',
 8896:                           $env{'form.question:'.$i}).'</span>';
 8897:           }
 8898:        }
 8899:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8900:     }
 8901: # Start grading
 8902:     my $pcorrect=$env{'form.pcorrect'};
 8903:     my $pincorrect=$env{'form.pincorrect'};
 8904:     my $storecount=0;
 8905:     foreach my $key (keys(%env)) {
 8906:        my $user='';
 8907:        if ($key=~/^form\.student\:(.*)$/) {
 8908:           $user=$1;
 8909:        }
 8910:        if ($key=~/^form\.unknown\:(.*)$/) {
 8911:           my $id=$1;
 8912:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8913:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8914:           } elsif ($env{'form.multi'.$id}) {
 8915:              $user=$env{'form.multi'.$id};
 8916:           }
 8917:        }
 8918:        if ($user) { 
 8919:           my @answer=split(/\,/,$env{$key});
 8920:           my $sum=0;
 8921:           my $realnumber=$number;
 8922:           for (my $i=0;$i<$number;$i++) {
 8923:              if ($answer[$i]) {
 8924:                 if ($gradingmechanism eq 'attendance') {
 8925:                    $sum+=$pcorrect;
 8926:                 } elsif ($answer[$i] eq '*') {
 8927:                    $sum+=$pcorrect;
 8928:                 } elsif ($answer[$i] eq '-') {
 8929:                    $realnumber--;
 8930:                 } else {
 8931:                    if ($answer[$i] eq $correct[$i]) {
 8932:                       $sum+=$pcorrect;
 8933:                    } else {
 8934:                       $sum+=$pincorrect;
 8935:                    }
 8936:                 }
 8937:              }
 8938:           }
 8939:           my $ave=$sum/(100*$realnumber);
 8940: # Store
 8941:           my ($username,$domain)=split(/\:/,$user);
 8942:           my %grades=();
 8943:           $grades{"resource.$part.solved"}='correct_by_override';
 8944:           $grades{"resource.$part.awarded"}=$ave;
 8945:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8946:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8947:                                                  $env{'request.course.id'},
 8948:                                                  $domain,$username);
 8949:           if ($returncode ne 'ok') {
 8950:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8951:           } else {
 8952:              $storecount++;
 8953:           }
 8954:        }
 8955:     }
 8956: # We are done
 8957:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8958:              '</td></tr></table>'."\n".
 8959:              '</td></tr></table><br /><br />'."\n";
 8960:     return $result.&show_grading_menu_form($symb);
 8961: }
 8962: 
 8963: sub handler {
 8964:     my $request=$_[0];
 8965:     &reset_caches();
 8966:     if ($env{'browser.mathml'}) {
 8967: 	&Apache::loncommon::content_type($request,'text/xml');
 8968:     } else {
 8969: 	&Apache::loncommon::content_type($request,'text/html');
 8970:     }
 8971:     $request->send_http_header;
 8972:     return '' if $request->header_only;
 8973:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8974:     my $symb=&get_symb($request,1);
 8975:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8976:     my $command=$commands[0];
 8977: 
 8978:     if ($#commands > 0) {
 8979: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8980:     }
 8981: 
 8982:     $ssi_error = 0;
 8983:     $request->print(&Apache::loncommon::start_page('Grading'));
 8984:     if ($symb eq '' && $command eq '') {
 8985: 	if ($env{'user.adv'}) {
 8986: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8987: 		($env{'form.codethree'})) {
 8988: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8989: 		    $env{'form.codethree'};
 8990: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8991: 		    &Apache::lonnet::checkin($token);
 8992: 		if ($tsymb) {
 8993: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8994: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8995: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8996: 					  ('grade_username' => $tuname,
 8997: 					   'grade_domain' => $tudom,
 8998: 					   'grade_courseid' => $tcrsid,
 8999: 					   'grade_symb' => $tsymb)));
 9000: 		    } else {
 9001: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9002: 		    }
 9003: 		} else {
 9004: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9005: 		}
 9006: 	    } else {
 9007: 		$request->print(&Apache::lonxml::tokeninputfield());
 9008: 	    }
 9009: 	}
 9010:     } else {
 9011: 	&init_perm();
 9012: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9013: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9014: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9015: 	    &pickStudentPage($request);
 9016: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9017: 	    &displayPage($request);
 9018: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9019: 	    &updateGradeByPage($request);
 9020: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9021: 	    &processGroup($request);
 9022: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9023: 	    $request->print(&grading_menu($request));
 9024: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9025: 	    $request->print(&submit_options($request));
 9026: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9027: 	    $request->print(&viewgrades($request));
 9028: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9029: 	    $request->print(&processHandGrade($request));
 9030: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9031: 	    $request->print(&editgrades($request));
 9032: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9033: 	    $request->print(&verifyreceipt($request));
 9034:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9035:             $request->print(&process_clicker($request));
 9036:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9037:             $request->print(&process_clicker_file($request));
 9038:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9039:             $request->print(&assign_clicker_grades($request));
 9040: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9041: 	    $request->print(&upcsvScores_form($request));
 9042: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9043: 	    $request->print(&csvupload($request));
 9044: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9045: 	    $request->print(&csvuploadmap($request));
 9046: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9047: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9048: 		$request->print(&csvuploadoptions($request));
 9049: 	    } else {
 9050: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9051: 		    $env{'form.upfile_associate'} = 'reverse';
 9052: 		} else {
 9053: 		    $env{'form.upfile_associate'} = 'forward';
 9054: 		}
 9055: 		$request->print(&csvuploadmap($request));
 9056: 	    }
 9057: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9058: 	    $request->print(&csvuploadassign($request));
 9059: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9060: 	    $request->print(&scantron_selectphase($request));
 9061:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9062:  	    $request->print(&scantron_do_warning($request));
 9063: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9064: 	    $request->print(&scantron_validate_file($request));
 9065: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9066: 	    $request->print(&scantron_process_students($request));
 9067:  	} elsif ($command eq 'scantronupload' && 
 9068:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9069: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9070:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9071:  	} elsif ($command eq 'scantronupload_save' &&
 9072:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9073: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9074:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9075:  	} elsif ($command eq 'scantron_download' &&
 9076: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9077:  	    $request->print(&scantron_download_scantron_data($request));
 9078:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9079:             $request->print(&checkscantron_results($request));     
 9080: 	} elsif ($command) {
 9081: 	    $request->print("Access Denied ($command)");
 9082: 	}
 9083:     }
 9084:     if ($ssi_error) {
 9085: 	&ssi_print_error($request);
 9086:     }
 9087:     $request->print(&Apache::loncommon::end_page());
 9088:     &reset_caches();
 9089:     return '';
 9090: }
 9091: 
 9092: 1;
 9093: 
 9094: __END__;

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