File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.514: download - view: text, annotated - select for diffs
Wed Mar 12 02:46:52 2008 UTC (16 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Change arguments accepted by lonnet::appenv() to:
1. reference to hash
2. (optional) reference to array.

Change all instances where lonnet::appenv() is called to replace first argument passed (originally a hash) to a reference to the hash.

- Modify lonnet.pm rev 1.35 code intended to prevent "dangerous" modifications of the environment, so it will actually do this.
- Allow these modifications to be made in certain instances:
   DC switching to adhoc role
   CC switching to a different course role in the current course.
   user self-enrolling as a student

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.514 2008/03/12 02:46:52 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 occured.  
   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 occured this becomes true.
   93: #                               It is up to the caller to initialize this to false
   94: #                               if desired.
   95: #    ssi_last_error_resource  - If an unrecoverable error occured, this is the value
   96: #                               of the resource that could not be rendered by the ssi
   97: #                               call.
   98: #    ssi_last_error           - 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:     $r->print('<h2>Unrecoverable network error</h2>');
  120:     $r->print('<p>Unable to perform a resource fetch from a server: <br />');
  121:     $r->print("Resource: $ssi_error_resource <br />");
  122:     $r->print("Error: $ssi_error_message <br /> Try again later.");
  123:     $r->print('If errors persist, contact LonCAPA support for assistance</p>');
  124: }
  125: 
  126: #
  127: # --- Retrieve the parts from the metadata file.---
  128: sub getpartlist {
  129:     my ($symb) = @_;
  130: 
  131:     my $navmap   = Apache::lonnavmaps::navmap->new();
  132:     my $res      = $navmap->getBySymb($symb);
  133:     my $partlist = $res->parts();
  134:     my $url      = $res->src();
  135:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  136: 
  137:     my @stores;
  138:     foreach my $part (@{ $partlist }) {
  139: 	foreach my $key (@metakeys) {
  140: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  141: 	}
  142:     }
  143:     return @stores;
  144: }
  145: 
  146: # --- Get the symbolic name of a problem and the url
  147: sub get_symb {
  148:     my ($request,$silent) = @_;
  149:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  150:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  151:     if ($symb eq '') { 
  152: 	if (!$silent) {
  153: 	    $request->print("Unable to handle ambiguous references:$url:.");
  154: 	    return ();
  155: 	}
  156:     }
  157:     &Apache::lonenc::check_decrypt(\$symb);
  158:     return ($symb);
  159: }
  160: 
  161: #--- Format fullname, username:domain if different for display
  162: #--- Use anywhere where the student names are listed
  163: sub nameUserString {
  164:     my ($type,$fullname,$uname,$udom) = @_;
  165:     if ($type eq 'header') {
  166: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  167:     } else {
  168: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  169: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  170:     }
  171: }
  172: 
  173: #--- Get the partlist and the response type for a given problem. ---
  174: #--- Indicate if a response type is coded handgraded or not. ---
  175: sub response_type {
  176:     my ($symb) = shift;
  177: 
  178:     my $navmap = Apache::lonnavmaps::navmap->new();
  179:     my $res = $navmap->getBySymb($symb);
  180:     my $partlist = $res->parts();
  181:     my %vPart = 
  182: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  183:     my (%response_types,%handgrade);
  184:     foreach my $part (@{ $partlist }) {
  185: 	next if (%vPart && !exists($vPart{$part}));
  186: 
  187: 	my @types = $res->responseType($part);
  188: 	my @ids = $res->responseIds($part);
  189: 	for (my $i=0; $i < scalar(@ids); $i++) {
  190: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  191: 	    $handgrade{$part.'_'.$ids[$i]} = 
  192: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  193: 				     '.handgrade',$symb);
  194: 	}
  195:     }
  196:     return ($partlist,\%handgrade,\%response_types);
  197: }
  198: 
  199: sub flatten_responseType {
  200:     my ($responseType) = @_;
  201:     my @part_response_id =
  202: 	map { 
  203: 	    my $part = $_;
  204: 	    map {
  205: 		[$part,$_]
  206: 		} sort(keys(%{ $responseType->{$part} }));
  207: 	} sort(keys(%$responseType));
  208:     return @part_response_id;
  209: }
  210: 
  211: sub get_display_part {
  212:     my ($partID,$symb)=@_;
  213:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  214:     if (defined($display) and $display ne '') {
  215: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  216:     } else {
  217: 	$display=$partID;
  218:     }
  219:     return $display;
  220: }
  221: 
  222: #--- Show resource title
  223: #--- and parts and response type
  224: sub showResourceInfo {
  225:     my ($symb,$probTitle,$checkboxes) = @_;
  226:     my $col=3;
  227:     if ($checkboxes) { $col=4; }
  228:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  229:     $result .='<table border="0">';
  230:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  231:     my %resptype = ();
  232:     my $hdgrade='no';
  233:     my %partsseen;
  234:     foreach my $partID (sort keys(%$responseType)) {
  235: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
  236: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  237: 	    my $responsetype = $responseType->{$partID}->{$resID};
  238: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  239: 	    $result.='<tr>';
  240: 	    if ($checkboxes) {
  241: 		if (exists($partsseen{$partID})) {
  242: 		    $result.="<td>&nbsp;</td>";
  243: 		} else {
  244: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  245: 		}
  246: 		$partsseen{$partID}=1;
  247: 	    }
  248: 	    my $display_part=&get_display_part($partID,$symb);
  249: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
  250: 		$resID.'</span></td>'.
  251: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
  252: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  253: 	}
  254:     }
  255:     $result.='</table>'."\n";
  256:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  257: }
  258: 
  259: sub reset_caches {
  260:     &reset_analyze_cache();
  261:     &reset_perm();
  262: }
  263: 
  264: {
  265:     my %analyze_cache;
  266: 
  267:     sub reset_analyze_cache {
  268: 	undef(%analyze_cache);
  269:     }
  270: 
  271:     sub get_analyze {
  272: 	my ($symb,$uname,$udom)=@_;
  273: 	my $key = "$symb\0$uname\0$udom";
  274: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  275: 
  276: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  277: 	$url=&Apache::lonnet::clutter($url);
  278: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  279: 					   ('grade_target' => 'analyze'),
  280: 					   ('grade_domain' => $udom),
  281: 					   ('grade_symb' => $symb),
  282: 					   ('grade_courseid' => 
  283: 					    $env{'request.course.id'}),
  284: 					   ('grade_username' => $uname));
  285: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  286: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  287: 	return $analyze_cache{$key} = \%analyze;
  288:     }
  289: 
  290:     sub get_order {
  291: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  292: 	my $analyze = &get_analyze($symb,$uname,$udom);
  293: 	return $analyze->{"$partid.$respid.shown"};
  294:     }
  295: 
  296:     sub get_radiobutton_correct_foil {
  297: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  298: 	my $analyze = &get_analyze($symb,$uname,$udom);
  299: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  300: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  301: 		return $foil;
  302: 	    }
  303: 	}
  304:     }
  305: }
  306: 
  307: #--- Clean response type for display
  308: #--- Currently filters option/rank/radiobutton/match/essay/Task
  309: #        response types only.
  310: sub cleanRecord {
  311:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  312: 	$uname,$udom) = @_;
  313:     my $grayFont = '<span class="LC_internal_info">';
  314:     if ($response =~ /^(option|rank)$/) {
  315: 	my %answer=&Apache::lonnet::str2hash($answer);
  316: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  317: 	my ($toprow,$bottomrow);
  318: 	foreach my $foil (@$order) {
  319: 	    if ($grading{$foil} == 1) {
  320: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  321: 	    } else {
  322: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  323: 	    }
  324: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  325: 	}
  326: 	return '<blockquote><table border="1">'.
  327: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  328: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  329: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  330:     } elsif ($response eq 'match') {
  331: 	my %answer=&Apache::lonnet::str2hash($answer);
  332: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  333: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  334: 	my ($toprow,$middlerow,$bottomrow);
  335: 	foreach my $foil (@$order) {
  336: 	    my $item=shift(@items);
  337: 	    if ($grading{$foil} == 1) {
  338: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  339: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  340: 	    } else {
  341: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  342: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  343: 	    }
  344: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  345: 	}
  346: 	return '<blockquote><table border="1">'.
  347: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  348: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  349: 	    $middlerow.'</tr>'.
  350: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  351: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  352:     } elsif ($response eq 'radiobutton') {
  353: 	my %answer=&Apache::lonnet::str2hash($answer);
  354: 	my ($toprow,$bottomrow);
  355: 	my $correct = 
  356: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  357: 	foreach my $foil (@$order) {
  358: 	    if (exists($answer{$foil})) {
  359: 		if ($foil eq $correct) {
  360: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  361: 		} else {
  362: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  363: 		}
  364: 	    } else {
  365: 		$toprow.='<td>'.&mt('false').'</td>';
  366: 	    }
  367: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  368: 	}
  369: 	return '<blockquote><table border="1">'.
  370: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  372: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  373:     } elsif ($response eq 'essay') {
  374: 	if (! exists ($env{'form.'.$symb})) {
  375: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  376: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  377: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  378: 
  379: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  380: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  381: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  382: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  383: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  384: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  385: 	}
  386: 	$answer =~ s-\n-<br />-g;
  387: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  388:     } elsif ( $response eq 'organic') {
  389: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  390: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  391: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  392: 	return $result;
  393:     } elsif ( $response eq 'Task') {
  394: 	if ( $answer eq 'SUBMITTED') {
  395: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  396: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  397: 	    return $result;
  398: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  399: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  400: 			       keys(%{$record}));
  401: 	    return join('<br />',($version,@matches));
  402: 			       
  403: 			       
  404: 	} else {
  405: 	    my $result =
  406: 		'<p>'
  407: 		.&mt('Overall result: [_1]',
  408: 		     $record->{$version."resource.$respid.$partid.status"})
  409: 		.'</p>';
  410: 	    
  411: 	    $result .= '<ul>';
  412: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  413: 			     keys(%{$record}));
  414: 	    foreach my $grade (sort(@grade)) {
  415: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  416: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  417: 				     $dim, $record->{$grade}).
  418: 			  '</li>';
  419: 	    }
  420: 	    $result.='</ul>';
  421: 	    return $result;
  422: 	}
  423:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  424: 	$answer = 
  425: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  426: 							      $answer);
  427:     }
  428:     return $answer;
  429: }
  430: 
  431: #-- A couple of common js functions
  432: sub commonJSfunctions {
  433:     my $request = shift;
  434:     $request->print(<<COMMONJSFUNCTIONS);
  435: <script type="text/javascript" language="javascript">
  436:     function radioSelection(radioButton) {
  437: 	var selection=null;
  438: 	if (radioButton.length > 1) {
  439: 	    for (var i=0; i<radioButton.length; i++) {
  440: 		if (radioButton[i].checked) {
  441: 		    return radioButton[i].value;
  442: 		}
  443: 	    }
  444: 	} else {
  445: 	    if (radioButton.checked) return radioButton.value;
  446: 	}
  447: 	return selection;
  448:     }
  449: 
  450:     function pullDownSelection(selectOne) {
  451: 	var selection="";
  452: 	if (selectOne.length > 1) {
  453: 	    for (var i=0; i<selectOne.length; i++) {
  454: 		if (selectOne[i].selected) {
  455: 		    return selectOne[i].value;
  456: 		}
  457: 	    }
  458: 	} else {
  459:             // only one value it must be the selected one
  460: 	    return selectOne.value;
  461: 	}
  462:     }
  463: </script>
  464: COMMONJSFUNCTIONS
  465: }
  466: 
  467: #--- Dumps the class list with usernames,list of sections,
  468: #--- section, ids and fullnames for each user.
  469: sub getclasslist {
  470:     my ($getsec,$filterlist,$getgroup) = @_;
  471:     my @getsec;
  472:     my @getgroup;
  473:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  474:     if (!ref($getsec)) {
  475: 	if ($getsec ne '' && $getsec ne 'all') {
  476: 	    @getsec=($getsec);
  477: 	}
  478:     } else {
  479: 	@getsec=@{$getsec};
  480:     }
  481:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  482:     if (!ref($getgroup)) {
  483: 	if ($getgroup ne '' && $getgroup ne 'all') {
  484: 	    @getgroup=($getgroup);
  485: 	}
  486:     } else {
  487: 	@getgroup=@{$getgroup};
  488:     }
  489:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  490: 
  491:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  492:     # Bail out if we were unable to get the classlist
  493:     return if (! defined($classlist));
  494:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  495:     #
  496:     my %sections;
  497:     my %fullnames;
  498:     foreach my $student (keys(%$classlist)) {
  499:         my $end      = 
  500:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  501:         my $start    = 
  502:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  503:         my $id       = 
  504:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  505:         my $section  = 
  506:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  507:         my $fullname = 
  508:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  509:         my $status   = 
  510:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  511:         my $group   = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  513: 	# filter students according to status selected
  514: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  515: 	    if (!($stu_status =~ $status)) {
  516: 		delete($classlist->{$student});
  517: 		next;
  518: 	    }
  519: 	}
  520: 	# filter students according to groups selected
  521: 	my @stu_groups = split(/,/,$group);
  522: 	if (@getgroup) {
  523: 	    my $exclude = 1;
  524: 	    foreach my $grp (@getgroup) {
  525: 	        foreach my $stu_group (@stu_groups) {
  526: 	            if ($stu_group eq $grp) {
  527: 	                $exclude = 0;
  528:     	            } 
  529: 	        }
  530:     	        if (($grp eq 'none') && !$group) {
  531:         	        $exclude = 0;
  532:         	}
  533: 	    }
  534: 	    if ($exclude) {
  535: 	        delete($classlist->{$student});
  536: 	    }
  537: 	}
  538: 	$section = ($section ne '' ? $section : 'none');
  539: 	if (&canview($section)) {
  540: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  541: 		$sections{$section}++;
  542: 		if ($classlist->{$student}) {
  543: 		    $fullnames{$student}=$fullname;
  544: 		}
  545: 	    } else {
  546: 		delete($classlist->{$student});
  547: 	    }
  548: 	} else {
  549: 	    delete($classlist->{$student});
  550: 	}
  551:     }
  552:     my %seen = ();
  553:     my @sections = sort(keys(%sections));
  554:     return ($classlist,\@sections,\%fullnames);
  555: }
  556: 
  557: sub canmodify {
  558:     my ($sec)=@_;
  559:     if ($perm{'mgr'}) {
  560: 	if (!defined($perm{'mgr_section'})) {
  561: 	    # can modify whole class
  562: 	    return 1;
  563: 	} else {
  564: 	    if ($sec eq $perm{'mgr_section'}) {
  565: 		#can modify the requested section
  566: 		return 1;
  567: 	    } else {
  568: 		# can't modify the request section
  569: 		return 0;
  570: 	    }
  571: 	}
  572:     }
  573:     #can't modify
  574:     return 0;
  575: }
  576: 
  577: sub canview {
  578:     my ($sec)=@_;
  579:     if ($perm{'vgr'}) {
  580: 	if (!defined($perm{'vgr_section'})) {
  581: 	    # can modify whole class
  582: 	    return 1;
  583: 	} else {
  584: 	    if ($sec eq $perm{'vgr_section'}) {
  585: 		#can modify the requested section
  586: 		return 1;
  587: 	    } else {
  588: 		# can't modify the request section
  589: 		return 0;
  590: 	    }
  591: 	}
  592:     }
  593:     #can't modify
  594:     return 0;
  595: }
  596: 
  597: #--- Retrieve the grade status of a student for all the parts
  598: sub student_gradeStatus {
  599:     my ($symb,$udom,$uname,$partlist) = @_;
  600:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  601:     my %partstatus = ();
  602:     foreach (@$partlist) {
  603: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  604: 	$status              = 'nothing' if ($status eq '');
  605: 	$partstatus{$_}      = $status;
  606: 	my $subkey           = "resource.$_.submitted_by";
  607: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  608:     }
  609:     return %partstatus;
  610: }
  611: 
  612: # hidden form and javascript that calls the form
  613: # Use by verifyscript and viewgrades
  614: # Shows a student's view of problem and submission
  615: sub jscriptNform {
  616:     my ($symb) = @_;
  617:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  618:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  619: 	'    function viewOneStudent(user,domain) {'."\n".
  620: 	'	document.onestudent.student.value = user;'."\n".
  621: 	'	document.onestudent.userdom.value = domain;'."\n".
  622: 	'	document.onestudent.submit();'."\n".
  623: 	'    }'."\n".
  624: 	'</script>'."\n";
  625:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  626: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  627: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  628: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  629: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  630: 	'<input type="hidden" name="command" value="submission" />'."\n".
  631: 	'<input type="hidden" name="student" value="" />'."\n".
  632: 	'<input type="hidden" name="userdom" value="" />'."\n".
  633: 	'</form>'."\n";
  634:     return $jscript;
  635: }
  636: 
  637: 
  638: 
  639: # Given the score (as a number [0-1] and the weight) what is the final
  640: # point value? This function will round to the nearest tenth, third,
  641: # or quarter if one of those is within the tolerance of .00001.
  642: sub compute_points {
  643:     my ($score, $weight) = @_;
  644:     
  645:     my $tolerance = .00001;
  646:     my $points = $score * $weight;
  647: 
  648:     # Check for nearness to 1/x.
  649:     my $check_for_nearness = sub {
  650:         my ($factor) = @_;
  651:         my $num = ($points * $factor) + $tolerance;
  652:         my $floored_num = floor($num);
  653:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  654:             return $floored_num / $factor;
  655:         }
  656:         return $points;
  657:     };
  658: 
  659:     $points = $check_for_nearness->(10);
  660:     $points = $check_for_nearness->(3);
  661:     $points = $check_for_nearness->(4);
  662:     
  663:     return $points;
  664: }
  665: 
  666: #------------------ End of general use routines --------------------
  667: 
  668: #
  669: # Find most similar essay
  670: #
  671: 
  672: sub most_similar {
  673:     my ($uname,$udom,$uessay,$old_essays)=@_;
  674: 
  675: # ignore spaces and punctuation
  676: 
  677:     $uessay=~s/\W+/ /gs;
  678: 
  679: # ignore empty submissions (occuring when only files are sent)
  680: 
  681:     unless ($uessay=~/\w+/) { return ''; }
  682: 
  683: # these will be returned. Do not care if not at least 50 percent similar
  684:     my $limit=0.6;
  685:     my $sname='';
  686:     my $sdom='';
  687:     my $scrsid='';
  688:     my $sessay='';
  689: # go through all essays ...
  690:     foreach my $tkey (keys(%$old_essays)) {
  691: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  692: # ... except the same student
  693:         next if (($tname eq $uname) && ($tdom eq $udom));
  694: 	my $tessay=$old_essays->{$tkey};
  695: 	$tessay=~s/\W+/ /gs;
  696: # String similarity gives up if not even limit
  697: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  698: # Found one
  699: 	if ($tsimilar>$limit) {
  700: 	    $limit=$tsimilar;
  701: 	    $sname=$tname;
  702: 	    $sdom=$tdom;
  703: 	    $scrsid=$tcrsid;
  704: 	    $sessay=$old_essays->{$tkey};
  705: 	}
  706:     }
  707:     if ($limit>0.6) {
  708:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  709:     } else {
  710:        return ('','','','',0);
  711:     }
  712: }
  713: 
  714: #-------------------------------------------------------------------
  715: 
  716: #------------------------------------ Receipt Verification Routines
  717: #
  718: #--- Check whether a receipt number is valid.---
  719: sub verifyreceipt {
  720:     my $request  = shift;
  721: 
  722:     my $courseid = $env{'request.course.id'};
  723:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  724: 	$env{'form.receipt'};
  725:     $receipt     =~ s/[^\-\d]//g;
  726:     my ($symb)   = &get_symb($request);
  727: 
  728:     my $title.=
  729: 	'<h3><span class="LC_info">'.
  730: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  731: 	'</span></h3>'."\n".
  732: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  733: 	'</h4>'."\n";
  734: 
  735:     my ($string,$contents,$matches) = ('','',0);
  736:     my (undef,undef,$fullname) = &getclasslist('all','0');
  737:     
  738:     my $receiptparts=0;
  739:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  740: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  741:     my $parts=['0'];
  742:     if ($receiptparts) { ($parts)=&response_type($symb); }
  743:     
  744:     my $header = 
  745: 	&Apache::loncommon::start_data_table().
  746: 	&Apache::loncommon::start_data_table_header_row().
  747: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  748: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  749: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  750:     if ($receiptparts) {
  751: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  752:     }
  753:     $header.=
  754: 	&Apache::loncommon::end_data_table_header_row();
  755: 
  756:     foreach (sort 
  757: 	     {
  758: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  759: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  760: 		 }
  761: 		 return $a cmp $b;
  762: 	     } (keys(%$fullname))) {
  763: 	my ($uname,$udom)=split(/\:/);
  764: 	foreach my $part (@$parts) {
  765: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  766: 		$contents.=
  767: 		    &Apache::loncommon::start_data_table_row().
  768: 		    '<td>&nbsp;'."\n".
  769: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  770: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  771: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  772: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  773: 		if ($receiptparts) {
  774: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  775: 		}
  776: 		$contents.= 
  777: 		    &Apache::loncommon::end_data_table_row()."\n";
  778: 		
  779: 		$matches++;
  780: 	    }
  781: 	}
  782:     }
  783:     if ($matches == 0) {
  784: 	$string = $title.&mt('No match found for the above receipt.');
  785:     } else {
  786: 	$string = &jscriptNform($symb).$title.
  787: 	    '<p>'.
  788: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  789: 	    '</p>'.
  790: 	    $header.
  791: 	    $contents.
  792: 	    &Apache::loncommon::end_data_table()."\n";
  793:     }
  794:     return $string.&show_grading_menu_form($symb);
  795: }
  796: 
  797: #--- This is called by a number of programs.
  798: #--- Called from the Grading Menu - View/Grade an individual student
  799: #--- Also called directly when one clicks on the subm button 
  800: #    on the problem page.
  801: sub listStudents {
  802:     my ($request) = shift;
  803: 
  804:     my ($symb) = &get_symb($request);
  805:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  806:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  807:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  808:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  809:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  810:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  811:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  812: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  813: 
  814:     my $result='<h3><span class="LC_info">&nbsp;'.
  815: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  816: 	.'</span></h3>';
  817: 
  818:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  819: 
  820:     my %lt = ( 'multiple' =>
  821: 	       "Please select a student or group of students before clicking on the Next button.",
  822: 	       'single'   =>
  823: 	       "Please select the student before clicking on the Next button.",
  824: 	       );
  825:     %lt = &Apache::lonlocal::texthash(%lt);
  826:     $request->print(<<LISTJAVASCRIPT);
  827: <script type="text/javascript" language="javascript">
  828:     function checkSelect(checkBox) {
  829: 	var ctr=0;
  830: 	var sense="";
  831: 	if (checkBox.length > 1) {
  832: 	    for (var i=0; i<checkBox.length; i++) {
  833: 		if (checkBox[i].checked) {
  834: 		    ctr++;
  835: 		}
  836: 	    }
  837: 	    sense = '$lt{'multiple'}';
  838: 	} else {
  839: 	    if (checkBox.checked) {
  840: 		ctr = 1;
  841: 	    }
  842: 	    sense = '$lt{'single'}';
  843: 	}
  844: 	if (ctr == 0) {
  845: 	    alert(sense);
  846: 	    return false;
  847: 	}
  848: 	document.gradesub.submit();
  849:     }
  850: 
  851:     function reLoadList(formname) {
  852: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  853: 	formname.command.value = 'submission';
  854: 	formname.submit();
  855:     }
  856: </script>
  857: LISTJAVASCRIPT
  858: 
  859:     &commonJSfunctions($request);
  860:     $request->print($result);
  861: 
  862:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  863:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  864:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  865: 	"\n".$table;
  866: 	
  867:     $gradeTable .= 
  868: 	'&nbsp;'.
  869: 	&mt('<b>View Problem Text: </b>[_1]',
  870: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  871: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  872: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
  873:     $gradeTable .= 
  874: 	'&nbsp;'.
  875: 	&mt('<b>View Answer: </b>[_1]',
  876: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  877: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  878: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
  879: 
  880:     my $submission_options;
  881:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  882: 	$submission_options.=
  883: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  884:     }
  885:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  886:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  887:     $env{'form.Status'} = $saveStatus;
  888:     $submission_options.=
  889: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  890: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  891: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  892: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  893:     $gradeTable .= 
  894: 	'&nbsp;'.
  895: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
  896: 
  897:     $gradeTable .= 
  898:         '&nbsp;'.
  899: 	&mt('<b>Grading Increments:</b> [_1]',
  900: 	    '<select name="increment">'.
  901: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  902: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  903: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  904: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  905: 	    '</select>');
  906:     
  907:     $gradeTable .= 
  908:         &build_section_inputs().
  909: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  910: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  911: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  912: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  913: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  914: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  915: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  916: 
  917:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  918: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  919:     } else {
  920: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  921: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  922:     }
  923: 
  924:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  925: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
  926: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  927: 
  928: # checkall buttons
  929:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  930:     $gradeTable.='<input type="button" '."\n".
  931: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  932: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
  933:     $gradeTable.=&check_buttons();
  934:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  935:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  936:     $gradeTable.= &Apache::loncommon::start_data_table().
  937: 	&Apache::loncommon::start_data_table_header_row();
  938:     my $loop = 0;
  939:     while ($loop < 2) {
  940: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  941: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  942: 	if ($env{'form.showgrading'} eq 'yes' 
  943: 	    && $submitonly ne 'queued'
  944: 	    && $submitonly ne 'all') {
  945: 	    foreach my $part (sort(@$partlist)) {
  946: 		my $display_part=
  947: 		    &get_display_part((split(/_/,$part))[0],$symb);
  948: 		$gradeTable.=
  949: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  950: 	    }
  951: 	} elsif ($submitonly eq 'queued') {
  952: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  953: 	}
  954: 	$loop++;
  955: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  956:     }
  957:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  958: 
  959:     my $ctr = 0;
  960:     foreach my $student (sort 
  961: 			 {
  962: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  963: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  964: 			     }
  965: 			     return $a cmp $b;
  966: 			 }
  967: 			 (keys(%$fullname))) {
  968: 	my ($uname,$udom) = split(/:/,$student);
  969: 
  970: 	my %status = ();
  971: 
  972: 	if ($submitonly eq 'queued') {
  973: 	    my %queue_status = 
  974: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  975: 							$udom,$uname);
  976: 	    next if (!defined($queue_status{'gradingqueue'}));
  977: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  978: 	}
  979: 
  980: 	if ($env{'form.showgrading'} eq 'yes' 
  981: 	    && $submitonly ne 'queued'
  982: 	    && $submitonly ne 'all') {
  983: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  984: 	    my $submitted = 0;
  985: 	    my $graded = 0;
  986: 	    my $incorrect = 0;
  987: 	    foreach (keys(%status)) {
  988: 		$submitted = 1 if ($status{$_} ne 'nothing');
  989: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  990: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  991: 		
  992: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  993: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  994: 		    $submitted = 0;
  995: 		    my ($part)=split(/\./,$partid);
  996: 		    $gradeTable.='<input type="hidden" name="'.
  997: 			$student.':'.$part.':submitted_by" value="'.
  998: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  999: 		}
 1000: 	    }
 1001: 	    
 1002: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1003: 				     $submitonly eq 'incorrect' ||
 1004: 				     $submitonly eq 'graded'));
 1005: 	    next if (!$graded && ($submitonly eq 'graded'));
 1006: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1007: 	}
 1008: 
 1009: 	$ctr++;
 1010: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1011:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1012: 	if ( $perm{'vgr'} eq 'F' ) {
 1013: 	    if ($ctr%2 ==1) {
 1014: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1015: 	    }
 1016: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1017:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1018:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1019: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1020: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1021: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1022: 
 1023: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1024: 		foreach (sort keys(%status)) {
 1025: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1026: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1027: 		}
 1028: 	    }
 1029: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1030: 	    if ($ctr%2 ==0) {
 1031: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1032: 	    }
 1033: 	}
 1034:     }
 1035:     if ($ctr%2 ==1) {
 1036: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1037: 	    if ($env{'form.showgrading'} eq 'yes' 
 1038: 		&& $submitonly ne 'queued'
 1039: 		&& $submitonly ne 'all') {
 1040: 		foreach (@$partlist) {
 1041: 		    $gradeTable.='<td>&nbsp;</td>';
 1042: 		}
 1043: 	    } elsif ($submitonly eq 'queued') {
 1044: 		$gradeTable.='<td>&nbsp;</td>';
 1045: 	    }
 1046: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1047:     }
 1048: 
 1049:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1050: 	'<input type="button" '.
 1051: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1052: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1053:     if ($ctr == 0) {
 1054: 	my $num_students=(scalar(keys(%$fullname)));
 1055: 	if ($num_students eq 0) {
 1056: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1057: 	} else {
 1058: 	    my $submissions='submissions';
 1059: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1060: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1061: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1063: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1064: 		    $num_students).
 1065: 		'</span><br />';
 1066: 	}
 1067:     } elsif ($ctr == 1) {
 1068: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1069:     }
 1070:     $gradeTable.=&show_grading_menu_form($symb);
 1071:     $request->print($gradeTable);
 1072:     return '';
 1073: }
 1074: 
 1075: #---- Called from the listStudents routine
 1076: 
 1077: sub check_script {
 1078:     my ($form, $type)=@_;
 1079:     my $chkallscript='<script type="text/javascript">
 1080:     function checkall() {
 1081:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1082:             ele = document.forms.'.$form.'.elements[i];
 1083:             if (ele.name == "'.$type.'") {
 1084:             document.forms.'.$form.'.elements[i].checked=true;
 1085:                                        }
 1086:         }
 1087:     }
 1088: 
 1089:     function checksec() {
 1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1091:             ele = document.forms.'.$form.'.elements[i];
 1092:            string = document.forms.'.$form.'.chksec.value;
 1093:            if
 1094:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1095:               document.forms.'.$form.'.elements[i].checked=true;
 1096:             }
 1097:         }
 1098:     }
 1099: 
 1100: 
 1101:     function uncheckall() {
 1102:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1103:             ele = document.forms.'.$form.'.elements[i];
 1104:             if (ele.name == "'.$type.'") {
 1105:             document.forms.'.$form.'.elements[i].checked=false;
 1106:                                        }
 1107:         }
 1108:     }
 1109: 
 1110: </script>'."\n";
 1111:     return $chkallscript;
 1112: }
 1113: 
 1114: sub check_buttons {
 1115:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1116:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1117:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1118:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1119:     return $buttons;
 1120: }
 1121: 
 1122: #     Displays the submissions for one student or a group of students
 1123: sub processGroup {
 1124:     my ($request)  = shift;
 1125:     my $ctr        = 0;
 1126:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1127:     my $total      = scalar(@stuchecked)-1;
 1128: 
 1129:     foreach my $student (@stuchecked) {
 1130: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1131: 	$env{'form.student'}        = $uname;
 1132: 	$env{'form.userdom'}        = $udom;
 1133: 	$env{'form.fullname'}       = $fullname;
 1134: 	&submission($request,$ctr,$total);
 1135: 	$ctr++;
 1136:     }
 1137:     return '';
 1138: }
 1139: 
 1140: #------------------------------------------------------------------------------------
 1141: #
 1142: #-------------------------- Next few routines handles grading by student, essentially
 1143: #                           handles essay response type problem/part
 1144: #
 1145: #--- Javascript to handle the submission page functionality ---
 1146: sub sub_page_js {
 1147:     my $request = shift;
 1148:     $request->print(<<SUBJAVASCRIPT);
 1149: <script type="text/javascript" language="javascript">
 1150:     function updateRadio(formname,id,weight) {
 1151: 	var gradeBox = formname["GD_BOX"+id];
 1152: 	var radioButton = formname["RADVAL"+id];
 1153: 	var oldpts = formname["oldpts"+id].value;
 1154: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1155: 	gradeBox.value = pts;
 1156: 	var resetbox = false;
 1157: 	if (isNaN(pts) || pts < 0) {
 1158: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1159: 	    for (var i=0; i<radioButton.length; i++) {
 1160: 		if (radioButton[i].checked) {
 1161: 		    gradeBox.value = i;
 1162: 		    resetbox = true;
 1163: 		}
 1164: 	    }
 1165: 	    if (!resetbox) {
 1166: 		formtextbox.value = "";
 1167: 	    }
 1168: 	    return;
 1169: 	}
 1170: 
 1171: 	if (pts > weight) {
 1172: 	    var resp = confirm("You entered a value ("+pts+
 1173: 			       ") greater than the weight for the part. Accept?");
 1174: 	    if (resp == false) {
 1175: 		gradeBox.value = oldpts;
 1176: 		return;
 1177: 	    }
 1178: 	}
 1179: 
 1180: 	for (var i=0; i<radioButton.length; i++) {
 1181: 	    radioButton[i].checked=false;
 1182: 	    if (pts == i && pts != "") {
 1183: 		radioButton[i].checked=true;
 1184: 	    }
 1185: 	}
 1186: 	updateSelect(formname,id);
 1187: 	formname["stores"+id].value = "0";
 1188:     }
 1189: 
 1190:     function writeBox(formname,id,pts) {
 1191: 	var gradeBox = formname["GD_BOX"+id];
 1192: 	if (checkSolved(formname,id) == 'update') {
 1193: 	    gradeBox.value = pts;
 1194: 	} else {
 1195: 	    var oldpts = formname["oldpts"+id].value;
 1196: 	    gradeBox.value = oldpts;
 1197: 	    var radioButton = formname["RADVAL"+id];
 1198: 	    for (var i=0; i<radioButton.length; i++) {
 1199: 		radioButton[i].checked=false;
 1200: 		if (i == oldpts) {
 1201: 		    radioButton[i].checked=true;
 1202: 		}
 1203: 	    }
 1204: 	}
 1205: 	formname["stores"+id].value = "0";
 1206: 	updateSelect(formname,id);
 1207: 	return;
 1208:     }
 1209: 
 1210:     function clearRadBox(formname,id) {
 1211: 	if (checkSolved(formname,id) == 'noupdate') {
 1212: 	    updateSelect(formname,id);
 1213: 	    return;
 1214: 	}
 1215: 	gradeSelect = formname["GD_SEL"+id];
 1216: 	for (var i=0; i<gradeSelect.length; i++) {
 1217: 	    if (gradeSelect[i].selected) {
 1218: 		var selectx=i;
 1219: 	    }
 1220: 	}
 1221: 	var stores = formname["stores"+id];
 1222: 	if (selectx == stores.value) { return };
 1223: 	var gradeBox = formname["GD_BOX"+id];
 1224: 	gradeBox.value = "";
 1225: 	var radioButton = formname["RADVAL"+id];
 1226: 	for (var i=0; i<radioButton.length; i++) {
 1227: 	    radioButton[i].checked=false;
 1228: 	}
 1229: 	stores.value = selectx;
 1230:     }
 1231: 
 1232:     function checkSolved(formname,id) {
 1233: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1234: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1235: 	    if (!reply) {return "noupdate";}
 1236: 	    formname.overRideScore.value = 'yes';
 1237: 	}
 1238: 	return "update";
 1239:     }
 1240: 
 1241:     function updateSelect(formname,id) {
 1242: 	formname["GD_SEL"+id][0].selected = true;
 1243: 	return;
 1244:     }
 1245: 
 1246: //=========== Check that a point is assigned for all the parts  ============
 1247:     function checksubmit(formname,val,total,parttot) {
 1248: 	formname.gradeOpt.value = val;
 1249: 	if (val == "Save & Next") {
 1250: 	    for (i=0;i<=total;i++) {
 1251: 		for (j=0;j<parttot;j++) {
 1252: 		    var partid = formname["partid"+i+"_"+j].value;
 1253: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1254: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1255: 			if (points == "") {
 1256: 			    var name = formname["name"+i].value;
 1257: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1258: 			    var resp = confirm("You did not assign a score for "+studentID+
 1259: 					       ", part "+partid+". Continue?");
 1260: 			    if (resp == false) {
 1261: 				formname["GD_BOX"+i+"_"+partid].focus();
 1262: 				return false;
 1263: 			    }
 1264: 			}
 1265: 		    }
 1266: 		    
 1267: 		}
 1268: 	    }
 1269: 	    
 1270: 	}
 1271: 	if (val == "Grade Student") {
 1272: 	    formname.showgrading.value = "yes";
 1273: 	    if (formname.Status.value == "") {
 1274: 		formname.Status.value = "Active";
 1275: 	    }
 1276: 	    formname.studentNo.value = total;
 1277: 	}
 1278: 	formname.submit();
 1279:     }
 1280: 
 1281: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1282:     function checkSubmitPage(formname,total) {
 1283: 	noscore = new Array(100);
 1284: 	var ptr = 0;
 1285: 	for (i=1;i<total;i++) {
 1286: 	    var partid = formname["q_"+i].value;
 1287: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1288: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1289: 		var status = formname["solved"+i+"_"+partid].value;
 1290: 		if (points == "" && status != "correct_by_student") {
 1291: 		    noscore[ptr] = i;
 1292: 		    ptr++;
 1293: 		}
 1294: 	    }
 1295: 	}
 1296: 	if (ptr != 0) {
 1297: 	    var sense = ptr == 1 ? ": " : "s: ";
 1298: 	    var prolist = "";
 1299: 	    if (ptr == 1) {
 1300: 		prolist = noscore[0];
 1301: 	    } else {
 1302: 		var i = 0;
 1303: 		while (i < ptr-1) {
 1304: 		    prolist += noscore[i]+", ";
 1305: 		    i++;
 1306: 		}
 1307: 		prolist += "and "+noscore[i];
 1308: 	    }
 1309: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1310: 	    if (resp == false) {
 1311: 		return false;
 1312: 	    }
 1313: 	}
 1314: 
 1315: 	formname.submit();
 1316:     }
 1317: </script>
 1318: SUBJAVASCRIPT
 1319: }
 1320: 
 1321: #--- javascript for essay type problem --
 1322: sub sub_page_kw_js {
 1323:     my $request = shift;
 1324:     my $iconpath = $request->dir_config('lonIconsURL');
 1325:     &commonJSfunctions($request);
 1326: 
 1327:     my $inner_js_msg_central=<<INNERJS;
 1328:     <script text="text/javascript">
 1329:     function checkInput() {
 1330:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1331:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1332:       var usrctr = document.msgcenter.usrctr.value;
 1333:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1334:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1335: 
 1336:       var msgchk = "";
 1337:       if (document.msgcenter.subchk.checked) {
 1338:          msgchk = "msgsub,";
 1339:       }
 1340:       var includemsg = 0;
 1341:       for (var i=1; i<=nmsg; i++) {
 1342:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1343:           var frmmsg = document.msgcenter["msg"+i];
 1344:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1345:           var showflg = opener.document.SCORE["shownOnce"+i];
 1346:           showflg.value = "1";
 1347:           var chkbox = document.msgcenter["msgn"+i];
 1348:           if (chkbox.checked) {
 1349:              msgchk += "savemsg"+i+",";
 1350:              includemsg = 1;
 1351:           }
 1352:       }
 1353:       if (document.msgcenter.newmsgchk.checked) {
 1354:          msgchk += "newmsg"+usrctr;
 1355:          includemsg = 1;
 1356:       }
 1357:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1358:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1359:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1360:       includemsg.value = msgchk;
 1361: 
 1362:       self.close()
 1363: 
 1364:     }
 1365:     </script>
 1366: INNERJS
 1367: 
 1368:     my $inner_js_highlight_central=<<INNERJS;
 1369:  <script type="text/javascript">
 1370:     function updateChoice(flag) {
 1371:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1372:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1373:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1374:       opener.document.SCORE.refresh.value = "on";
 1375:       if (opener.document.SCORE.keywords.value!=""){
 1376:          opener.document.SCORE.submit();
 1377:       }
 1378:       self.close()
 1379:     }
 1380: </script>
 1381: INNERJS
 1382: 
 1383:     my $start_page_msg_central = 
 1384:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1385: 				       {'js_ready'  => 1,
 1386: 					'only_body' => 1,
 1387: 					'bgcolor'   =>'#FFFFFF',});
 1388:     my $end_page_msg_central = 
 1389: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1390: 
 1391: 
 1392:     my $start_page_highlight_central = 
 1393:         &Apache::loncommon::start_page('Highlight Central',
 1394: 				       $inner_js_highlight_central,
 1395: 				       {'js_ready'  => 1,
 1396: 					'only_body' => 1,
 1397: 					'bgcolor'   =>'#FFFFFF',});
 1398:     my $end_page_highlight_central = 
 1399: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1400: 
 1401:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1402:     $docopen=~s/^document\.//;
 1403:     $request->print(<<SUBJAVASCRIPT);
 1404: <script type="text/javascript" language="javascript">
 1405: 
 1406: //===================== Show list of keywords ====================
 1407:   function keywords(formname) {
 1408:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1409:     if (nret==null) return;
 1410:     formname.keywords.value = nret;
 1411: 
 1412:     if (formname.keywords.value != "") {
 1413: 	formname.refresh.value = "on";
 1414: 	formname.submit();
 1415:     }
 1416:     return;
 1417:   }
 1418: 
 1419: //===================== Script to view submitted by ==================
 1420:   function viewSubmitter(submitter) {
 1421:     document.SCORE.refresh.value = "on";
 1422:     document.SCORE.NCT.value = "1";
 1423:     document.SCORE.unamedom0.value = submitter;
 1424:     document.SCORE.submit();
 1425:     return;
 1426:   }
 1427: 
 1428: //===================== Script to add keyword(s) ==================
 1429:   function getSel() {
 1430:     if (document.getSelection) txt = document.getSelection();
 1431:     else if (document.selection) txt = document.selection.createRange().text;
 1432:     else return;
 1433:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1434:     if (cleantxt=="") {
 1435: 	alert("Please select a word or group of words from document and then click this link.");
 1436: 	return;
 1437:     }
 1438:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1439:     if (nret==null) return;
 1440:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1441:     if (document.SCORE.keywords.value != "") {
 1442: 	document.SCORE.refresh.value = "on";
 1443: 	document.SCORE.submit();
 1444:     }
 1445:     return;
 1446:   }
 1447: 
 1448: //====================== Script for composing message ==============
 1449:    // preload images
 1450:    img1 = new Image();
 1451:    img1.src = "$iconpath/mailbkgrd.gif";
 1452:    img2 = new Image();
 1453:    img2.src = "$iconpath/mailto.gif";
 1454: 
 1455:   function msgCenter(msgform,usrctr,fullname) {
 1456:     var Nmsg  = msgform.savemsgN.value;
 1457:     savedMsgHeader(Nmsg,usrctr,fullname);
 1458:     var subject = msgform.msgsub.value;
 1459:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1460:     re = /msgsub/;
 1461:     var shwsel = "";
 1462:     if (re.test(msgchk)) { shwsel = "checked" }
 1463:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1464:     displaySubject(checkEntities(subject),shwsel);
 1465:     for (var i=1; i<=Nmsg; i++) {
 1466: 	var testmsg = "savemsg"+i+",";
 1467: 	re = new RegExp(testmsg,"g");
 1468: 	shwsel = "";
 1469: 	if (re.test(msgchk)) { shwsel = "checked" }
 1470: 	var message = document.SCORE["savemsg"+i].value;
 1471: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1472: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1473: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1474:     }
 1475:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1476:     shwsel = "";
 1477:     re = /newmsg/;
 1478:     if (re.test(msgchk)) { shwsel = "checked" }
 1479:     newMsg(newmsg,shwsel);
 1480:     msgTail(); 
 1481:     return;
 1482:   }
 1483: 
 1484:   function checkEntities(strx) {
 1485:     if (strx.length == 0) return strx;
 1486:     var orgStr = ["&", "<", ">", '"']; 
 1487:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1488:     var counter = 0;
 1489:     while (counter < 4) {
 1490: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1491: 	counter++;
 1492:     }
 1493:     return strx;
 1494:   }
 1495: 
 1496:   function strReplace(strx, orgStr, newStr) {
 1497:     return strx.split(orgStr).join(newStr);
 1498:   }
 1499: 
 1500:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1501:     var height = 70*Nmsg+250;
 1502:     var scrollbar = "no";
 1503:     if (height > 600) {
 1504: 	height = 600;
 1505: 	scrollbar = "yes";
 1506:     }
 1507:     var xpos = (screen.width-600)/2;
 1508:     xpos = (xpos < 0) ? '0' : xpos;
 1509:     var ypos = (screen.height-height)/2-30;
 1510:     ypos = (ypos < 0) ? '0' : ypos;
 1511: 
 1512:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1513:     pWin.focus();
 1514:     pDoc = pWin.document;
 1515:     pDoc.$docopen;
 1516:     pDoc.write('$start_page_msg_central');
 1517: 
 1518:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1519:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1520:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1521: 
 1522:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1523:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1524:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1525: }
 1526:     function displaySubject(msg,shwsel) {
 1527:     pDoc = pWin.document;
 1528:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1529:     pDoc.write("<td>Subject<\\/td>");
 1530:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1531:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1532: }
 1533: 
 1534:   function displaySavedMsg(ctr,msg,shwsel) {
 1535:     pDoc = pWin.document;
 1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1537:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1538:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1539:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1540: }
 1541: 
 1542:   function newMsg(newmsg,shwsel) {
 1543:     pDoc = pWin.document;
 1544:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1545:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1546:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1547:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1548: }
 1549: 
 1550:   function msgTail() {
 1551:     pDoc = pWin.document;
 1552:     pDoc.write("<\\/table>");
 1553:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1554:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1555:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1556:     pDoc.write("<\\/form>");
 1557:     pDoc.write('$end_page_msg_central');
 1558:     pDoc.close();
 1559: }
 1560: 
 1561: //====================== Script for keyword highlight options ==============
 1562:   function kwhighlight() {
 1563:     var kwclr    = document.SCORE.kwclr.value;
 1564:     var kwsize   = document.SCORE.kwsize.value;
 1565:     var kwstyle  = document.SCORE.kwstyle.value;
 1566:     var redsel = "";
 1567:     var grnsel = "";
 1568:     var blusel = "";
 1569:     if (kwclr=="red")   {var redsel="checked"};
 1570:     if (kwclr=="green") {var grnsel="checked"};
 1571:     if (kwclr=="blue")  {var blusel="checked"};
 1572:     var sznsel = "";
 1573:     var sz1sel = "";
 1574:     var sz2sel = "";
 1575:     if (kwsize=="0")  {var sznsel="checked"};
 1576:     if (kwsize=="+1") {var sz1sel="checked"};
 1577:     if (kwsize=="+2") {var sz2sel="checked"};
 1578:     var synsel = "";
 1579:     var syisel = "";
 1580:     var sybsel = "";
 1581:     if (kwstyle=="")    {var synsel="checked"};
 1582:     if (kwstyle=="<i>") {var syisel="checked"};
 1583:     if (kwstyle=="<b>") {var sybsel="checked"};
 1584:     highlightCentral();
 1585:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1586:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1587:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1588:     highlightend();
 1589:     return;
 1590:   }
 1591: 
 1592:   function highlightCentral() {
 1593: //    if (window.hwdWin) window.hwdWin.close();
 1594:     var xpos = (screen.width-400)/2;
 1595:     xpos = (xpos < 0) ? '0' : xpos;
 1596:     var ypos = (screen.height-330)/2-30;
 1597:     ypos = (ypos < 0) ? '0' : ypos;
 1598: 
 1599:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1600:     hwdWin.focus();
 1601:     var hDoc = hwdWin.document;
 1602:     hDoc.$docopen;
 1603:     hDoc.write('$start_page_highlight_central');
 1604:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1605:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1606: 
 1607:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1608:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1609:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1610:   }
 1611: 
 1612:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1613:     var hDoc = hwdWin.document;
 1614:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1615:     hDoc.write("<td align=\\"left\\">");
 1616:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1617:     hDoc.write("<td align=\\"left\\">");
 1618:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1619:     hDoc.write("<td align=\\"left\\">");
 1620:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1621:     hDoc.write("<\\/tr>");
 1622:   }
 1623: 
 1624:   function highlightend() { 
 1625:     var hDoc = hwdWin.document;
 1626:     hDoc.write("<\\/table>");
 1627:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1628:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1629:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1630:     hDoc.write("<\\/form>");
 1631:     hDoc.write('$end_page_highlight_central');
 1632:     hDoc.close();
 1633:   }
 1634: 
 1635: </script>
 1636: SUBJAVASCRIPT
 1637: }
 1638: 
 1639: sub get_increment {
 1640:     my $increment = $env{'form.increment'};
 1641:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1642:         $increment != .1) {
 1643:         $increment = 1;
 1644:     }
 1645:     return $increment;
 1646: }
 1647: 
 1648: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1649: sub gradeBox {
 1650:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1651:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1652: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1653:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1654:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1655:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1656:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1657:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1658: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1659:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1660:     my $display_part= &get_display_part($partid,$symb);
 1661:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1662: 				       [$partid]);
 1663:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1664:     if ($last_resets{$partid}) {
 1665:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1666:     }
 1667:     $result.='<table border="0"><tr>';
 1668:     my $ctr = 0;
 1669:     my $thisweight = 0;
 1670:     my $increment = &get_increment();
 1671: 
 1672:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1673:     while ($thisweight<=$wgt) {
 1674: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1675: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1676: 	    $thisweight.')" value="'.$thisweight.'" '.
 1677: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1678: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1679:         $thisweight += $increment;
 1680: 	$ctr++;
 1681:     }
 1682:     $radio.='</tr></table>';
 1683: 
 1684:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1685: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1686: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1687: 	$wgt.')" /></td>'."\n";
 1688:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1689: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1690: 	' </td><td>'."\n";
 1691:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1692: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1693:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1694: 	$line.='<option></option>'.
 1695: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1696:     } else {
 1697: 	$line.='<option selected="selected"></option>'.
 1698: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1699:     }
 1700:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1701: 
 1702: 
 1703:     $result .= 
 1704: 	&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);
 1705: 
 1706:     
 1707:     $result.='</tr></table>'."\n";
 1708:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1709: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1710: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1711: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1712:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1713:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1714:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1715:         $aggtries.'" />'."\n";
 1716:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1717:     return $result;
 1718: }
 1719: 
 1720: sub handback_box {
 1721:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1722:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1723:     my (@respids);
 1724:      my @part_response_id = &flatten_responseType($responseType);
 1725:     foreach my $part_response_id (@part_response_id) {
 1726:     	my ($part,$resp) = @{ $part_response_id };
 1727:         if ($part eq $partid) {
 1728:             push(@respids,$resp);
 1729:         }
 1730:     }
 1731:     my $result;
 1732:     foreach my $respid (@respids) {
 1733: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1734: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1735: 	next if (!@$files);
 1736: 	my $file_counter = 1;
 1737: 	foreach my $file (@$files) {
 1738: 	    if ($file =~ /\/portfolio\//) {
 1739:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1740:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1741:     	        $file_disp = "$name.$ext";
 1742:     	        $file = $file_path.$file_disp;
 1743:     	        $result.=&mt('Return commented version of [_1] to student.',
 1744:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1745:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1746:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1747:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1748:     	        $file_counter++;
 1749: 	    }
 1750: 	}
 1751:     }
 1752:     return $result;    
 1753: }
 1754: 
 1755: sub show_problem {
 1756:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1757:     my $rendered;
 1758:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1759:     &Apache::lonxml::remember_problem_counter();
 1760:     if ($mode eq 'both' or $mode eq 'text') {
 1761: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1762: 						       $env{'request.course.id'},
 1763: 						       undef,\%form);
 1764:     }
 1765:     if ($removeform) {
 1766: 	$rendered=~s|<form(.*?)>||g;
 1767: 	$rendered=~s|</form>||g;
 1768: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1769:     }
 1770:     my $companswer;
 1771:     if ($mode eq 'both' or $mode eq 'answer') {
 1772: 	&Apache::lonxml::restore_problem_counter();
 1773: 	$companswer=
 1774: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1775: 						    $env{'request.course.id'},
 1776: 						    %form);
 1777:     }
 1778:     if ($removeform) {
 1779: 	$companswer=~s|<form(.*?)>||g;
 1780: 	$companswer=~s|</form>||g;
 1781: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1782:     }
 1783:     $rendered=
 1784: 	'<div class="LC_grade_show_problem_header">'.
 1785: 	&mt('View of the problem').
 1786: 	'</div><div class="LC_grade_show_problem_problem">'.
 1787: 	$rendered.
 1788: 	'</div>';
 1789:     $companswer=
 1790: 	'<div class="LC_grade_show_problem_header">'.
 1791: 	&mt('Correct answer').
 1792: 	'</div><div class="LC_grade_show_problem_problem">'.
 1793: 	$companswer.
 1794: 	'</div>';
 1795:     my $result;
 1796:     if ($mode eq 'both') {
 1797: 	$result=$rendered.$companswer;
 1798:     } elsif ($mode eq 'text') {
 1799: 	$result=$rendered;
 1800:     } elsif ($mode eq 'answer') {
 1801: 	$result=$companswer;
 1802:     }
 1803:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1804:     return $result;
 1805: }
 1806: 
 1807: sub files_exist {
 1808:     my ($r, $symb) = @_;
 1809:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1810: 
 1811:     foreach my $student (@students) {
 1812:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1813:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1814: 					      $udom,$uname);
 1815:         my ($string,$timestamp)= &get_last_submission(\%record);
 1816:         foreach my $submission (@$string) {
 1817:             my ($partid,$respid) =
 1818: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1819:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1820: 					   \%record);
 1821:             return 1 if (@$files);
 1822:         }
 1823:     }
 1824:     return 0;
 1825: }
 1826: 
 1827: sub download_all_link {
 1828:     my ($r,$symb) = @_;
 1829:     my $all_students = 
 1830: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1831: 
 1832:     my $parts =
 1833: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1834: 
 1835:     my $identifier = &Apache::loncommon::get_cgi_id();
 1836:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1837:                              'cgi.'.$identifier.'.symb' => $symb,
 1838:                              'cgi.'.$identifier.'.parts' => $parts,});
 1839:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1840: 	      &mt('Download All Submitted Documents').'</a>');
 1841:     return
 1842: }
 1843: 
 1844: sub build_section_inputs {
 1845:     my $section_inputs;
 1846:     if ($env{'form.section'} eq '') {
 1847:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1848:     } else {
 1849:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1850:         foreach my $section (@sections) {
 1851:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1852:         }
 1853:     }
 1854:     return $section_inputs;
 1855: }
 1856: 
 1857: # --------------------------- show submissions of a student, option to grade 
 1858: sub submission {
 1859:     my ($request,$counter,$total) = @_;
 1860:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1861:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1862:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1863:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1864:     my $symb = &get_symb($request); 
 1865:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1866: 
 1867:     if (!&canview($usec)) {
 1868: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1869: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1870: 			$env{'request.course.id'}.')</span>');
 1871: 	$request->print(&show_grading_menu_form($symb));
 1872: 	return;
 1873:     }
 1874: 
 1875:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1876:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1877:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1878:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1879:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1880: 	'" src="'.$request->dir_config('lonIconsURL').
 1881: 	'/check.gif" height="16" border="0" />';
 1882: 
 1883:     my %old_essays;
 1884:     # header info
 1885:     if ($counter == 0) {
 1886: 	&sub_page_js($request);
 1887: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1888: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1889: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1890: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1891: 	    &download_all_link($request, $symb);
 1892: 	}
 1893: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1894: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1895: 
 1896: 	# option to display problem, only once else it cause problems 
 1897:         # with the form later since the problem has a form.
 1898: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1899: 	    my $mode;
 1900: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1901: 		$mode='both';
 1902: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1903: 		$mode='text';
 1904: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1905: 		$mode='answer';
 1906: 	    }
 1907: 	    &Apache::lonxml::clear_problem_counter();
 1908: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1909: 	}
 1910: 
 1911: 	# kwclr is the only variable that is guaranteed to be non blank 
 1912:         # if this subroutine has been called once.
 1913: 	my %keyhash = ();
 1914: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1915: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1916: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1917: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1918: 
 1919: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1920: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1921: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1922: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1923: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1924: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1925: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1926: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1927: 	}
 1928: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1929: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1930: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1931: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1932: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1933: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1934: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1935: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1936: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1937: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1938: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1939: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1940: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1941: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1942: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1943: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1944: 			&build_section_inputs().
 1945: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1946: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1947: 			'<input type="hidden" name="NCT"'.
 1948: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1949: 	if ($env{'form.handgrade'} eq 'yes') {
 1950: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1951: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1952: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1953: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1954: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1955: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1956: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1957: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1958: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1959: 	    }
 1960: 	}
 1961: 	
 1962: 	my ($cts,$prnmsg) = (1,'');
 1963: 	while ($cts <= $env{'form.savemsgN'}) {
 1964: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1965: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1966: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1967: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1968: 		'" />'."\n".
 1969: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1970: 	    $cts++;
 1971: 	}
 1972: 	$request->print($prnmsg);
 1973: 
 1974: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1975: #
 1976: # Print out the keyword options line
 1977: #
 1978: 	    $request->print(<<KEYWORDS);
 1979: &nbsp;<b>Keyword Options:</b>&nbsp;
 1980: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1981: <a href="#" onMouseDown="javascript:getSel(); return false"
 1982:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1983: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1984: KEYWORDS
 1985: #
 1986: # Load the other essays for similarity check
 1987: #
 1988:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1989: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1990: 	    $apath=&escape($apath);
 1991: 	    $apath=~s/\W/\_/gs;
 1992: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1993:         }
 1994:     }
 1995: 
 1996: # This is where output for one specific student would start
 1997:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 1998:     $request->print("\n\n".
 1999:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2000: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2001: 		    '<div class="LC_grade_show_user_body">'."\n");
 2002: 
 2003:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2004: 	my $mode;
 2005: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2006: 	    $mode='both';
 2007: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2008: 	    $mode='text';
 2009: 	} elsif ($env{'form.vAns'} eq 'all') {
 2010: 	    $mode='answer';
 2011: 	}
 2012: 	&Apache::lonxml::clear_problem_counter();
 2013: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2014:     }
 2015: 
 2016:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2017:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2018: 
 2019:     # Display student info
 2020:     $request->print(($counter == 0 ? '' : '<br />'));
 2021:     my $result='<div class="LC_grade_submissions">';
 2022:     
 2023:     $result.='<div class="LC_grade_submissions_header">';
 2024:     $result.= &mt('Submissions');
 2025:     $result.='<input type="hidden" name="name'.$counter.
 2026: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2027:     if ($env{'form.handgrade'} eq 'no') {
 2028: 	$result.='<span class="LC_grade_check_note">'.
 2029: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2030: 
 2031:     }
 2032: 
 2033: 
 2034: 
 2035:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2036:     my $fullname;
 2037:     my $col_fullnames = [];
 2038:     if ($env{'form.handgrade'} eq 'yes') {
 2039: 	(my $sub_result,$fullname,$col_fullnames)=
 2040: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2041: 				 $counter);
 2042: 	$result.=$sub_result;
 2043:     }
 2044:     $request->print($result."\n");
 2045:     $request->print('</div>'."\n");
 2046:     # print student answer/submission
 2047:     # Options are (1) Handgaded submission only
 2048:     #             (2) Last submission, includes submission that is not handgraded 
 2049:     #                  (for multi-response type part)
 2050:     #             (3) Last submission plus the parts info
 2051:     #             (4) The whole record for this student
 2052:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2053: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2054: 	
 2055: 	my $lastsubonly;
 2056: 
 2057: 	if ($$timestamp eq '') {
 2058: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2059: 	} else {
 2060: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2061: 
 2062: 	    my %seenparts;
 2063: 	    my @part_response_id = &flatten_responseType($responseType);
 2064: 	    foreach my $part (@part_response_id) {
 2065: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2066: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2067: 
 2068: 		my ($partid,$respid) = @{ $part };
 2069: 		my $display_part=&get_display_part($partid,$symb);
 2070: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2071: 		    if (exists($seenparts{$partid})) { next; }
 2072: 		    $seenparts{$partid}=1;
 2073: 		    my $submitby='<b>Part:</b> '.$display_part.
 2074: 			' <b>Collaborative submission by:</b> '.
 2075: 			'<a href="javascript:viewSubmitter(\''.
 2076: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2077: 			'\');" target="_self">'.
 2078: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2079: 		    $request->print($submitby);
 2080: 		    next;
 2081: 		}
 2082: 		my $responsetype = $responseType->{$partid}->{$respid};
 2083: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2084: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2085: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2086: 			' )</span>&nbsp; &nbsp;'.
 2087: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2088: 		    next;
 2089: 		}
 2090: 		foreach my $submission (@$string) {
 2091: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2092: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2093: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2094: 		    # Similarity check
 2095: 		    my $similar='';
 2096: 		    if($env{'form.checkPlag'}){
 2097: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2098: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2099: 			if ($osim) {
 2100: 			    $osim=int($osim*100.0);
 2101: 			    my %old_course_desc = 
 2102: 				&Apache::lonnet::coursedescription($ocrsid,
 2103: 								   {'one_time' => 1});
 2104: 
 2105: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2106: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2107: 				    $osim,
 2108: 				    &Apache::loncommon::plainname($oname,$odom),
 2109: 				    $oname,$odom,
 2110: 				    $old_course_desc{'description'},
 2111: 				    $old_course_desc{'num'},
 2112: 				    $old_course_desc{'domain'}).
 2113: 				'</span></h3><blockquote><i>'.
 2114: 				&keywords_highlight($oessay).
 2115: 				'</i></blockquote><hr />';
 2116: 			}
 2117: 		    }
 2118: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2119: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2120: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2121: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2122: 			my $display_part=&get_display_part($partid,$symb);
 2123: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2124: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2125: 			    ' )</span>&nbsp; &nbsp;';
 2126: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2127: 			if (@$files) {
 2128: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
 2129: 			    my $file_counter = 0;
 2130: 			    foreach my $file (@$files) {
 2131: 			        $file_counter++;
 2132: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2133: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2134: 			    }
 2135: 			    $lastsubonly.='<br />';
 2136: 			}
 2137: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2138: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2139: 					 $respid,\%record,$order);
 2140: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2141: 			$lastsubonly.='</div>';
 2142: 		    }
 2143: 		}
 2144: 	    }
 2145: 	    $lastsubonly.='</div>'."\n";
 2146: 	}
 2147: 	$request->print($lastsubonly);
 2148:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2149: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2150: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2151:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2152: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2153: 								 $env{'request.course.id'},
 2154: 								 $last,'.submission',
 2155: 								 'Apache::grades::keywords_highlight'));
 2156:     }
 2157: 
 2158:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2159: 	.$udom.'" />'."\n");
 2160:     # return if view submission with no grading option
 2161:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2162: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2163: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2164: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2165: 	$toGrade.='</div>'."\n";
 2166: 	if (($env{'form.command'} eq 'submission') || 
 2167: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2168: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2169: 	}
 2170: 	$request->print($toGrade);
 2171: 	return;
 2172:     } else {
 2173: 	$request->print('</div>'."\n");
 2174:     }
 2175: 
 2176:     # essay grading message center
 2177:     if ($env{'form.handgrade'} eq 'yes') {
 2178: 	my $result='<div class="LC_grade_message_center">';
 2179:     
 2180: 	$result.='<div class="LC_grade_message_center_header">'.
 2181: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2182: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2183: 	my $msgfor = $givenn.' '.$lastname;
 2184: 	if (scalar(@$col_fullnames) > 0) {
 2185: 	    my $lastone = pop(@$col_fullnames);
 2186: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2187: 	}
 2188: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2189: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2190: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2191: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2192: 	    ',\''.$msgfor.'\');" target="_self">'.
 2193: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2194: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2195: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2196: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2197: 	    '<br />&nbsp;('.
 2198: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2199: 	$result.='</div></div>';
 2200: 	$request->print($result);
 2201:     }
 2202: 
 2203:     my %seen = ();
 2204:     my @partlist;
 2205:     my @gradePartRespid;
 2206:     my @part_response_id = &flatten_responseType($responseType);
 2207:     $request->print('<div class="LC_grade_assign">'.
 2208: 		    
 2209: 		    '<div class="LC_grade_assign_header">'.
 2210: 		    &mt('Assign Grades').'</div>'.
 2211: 		    '<div class="LC_grade_assign_body">');
 2212:     foreach my $part_response_id (@part_response_id) {
 2213:     	my ($partid,$respid) = @{ $part_response_id };
 2214: 	my $part_resp = join('_',@{ $part_response_id });
 2215: 	next if ($seen{$partid} > 0);
 2216: 	$seen{$partid}++;
 2217: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2218: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2219: 	push @partlist,$partid;
 2220: 	push @gradePartRespid,$partid.'.'.$respid;
 2221: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2222:     }
 2223:     $request->print('</div></div>');
 2224: 
 2225:     $request->print('<div class="LC_grade_info_links">');
 2226:     if ($perm{'vgr'}) {
 2227: 	$request->print(
 2228: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2229: 						   $uname,$udom,'check'));
 2230:     }
 2231:     if ($perm{'opa'}) {
 2232: 	$request->print(
 2233: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2234: 					 $uname,$udom,$symb,'check'));
 2235:     }
 2236:     $request->print('</div>');
 2237: 
 2238:     $result='<input type="hidden" name="partlist'.$counter.
 2239: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2240:     $result.='<input type="hidden" name="gradePartRespid'.
 2241: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2242:     my $ctr = 0;
 2243:     while ($ctr < scalar(@partlist)) {
 2244: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2245: 	    $partlist[$ctr].'" />'."\n";
 2246: 	$ctr++;
 2247:     }
 2248:     $request->print($result.''."\n");
 2249: 
 2250: # Done with printing info for one student
 2251: 
 2252:     $request->print('</div>');#LC_grade_show_user_body
 2253:     $request->print('</div>');#LC_grade_show_user
 2254: 
 2255: 
 2256:     # print end of form
 2257:     if ($counter == $total) {
 2258: 	my $endform='<table border="0"><tr><td>'."\n";
 2259: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2260: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2261: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2262: 	my $ntstu ='<select name="NTSTU">'.
 2263: 	    '<option>1</option><option>2</option>'.
 2264: 	    '<option>3</option><option>5</option>'.
 2265: 	    '<option>7</option><option>10</option></select>'."\n";
 2266: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2267: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2268: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2269: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2270: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2271: 	    '<input type="button" value="'.&mt('Next').'" '.
 2272: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2273: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2274:         $endform.="<input type='hidden' value='".&get_increment().
 2275:             "' name='increment' />";
 2276: 	$endform.='</td></tr></table></form>';
 2277: 	$endform.=&show_grading_menu_form($symb);
 2278: 	$request->print($endform);
 2279:     }
 2280:     return '';
 2281: }
 2282: 
 2283: sub check_collaborators {
 2284:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2285:     my ($result,@col_fullnames);
 2286:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2287:     foreach my $part (keys(%$handgrade)) {
 2288: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2289: 					'.maxcollaborators',
 2290: 					$symb,$udom,$uname);
 2291: 	next if ($ncol <= 0);
 2292: 	$part =~ s/\_/\./g;
 2293: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2294: 	my (@good_collaborators, @bad_collaborators);
 2295: 	foreach my $possible_collaborator
 2296: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2297: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2298: 	    next if ($possible_collaborator eq '');
 2299: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2300: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2301: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2302: 	    # Doing this grep allows 'fuzzy' specification
 2303: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2304: 			       keys(%$classlist));
 2305: 	    if (! scalar(@matches)) {
 2306: 		push(@bad_collaborators, $possible_collaborator);
 2307: 	    } else {
 2308: 		push(@good_collaborators, @matches);
 2309: 	    }
 2310: 	}
 2311: 	if (scalar(@good_collaborators) != 0) {
 2312: 	    $result.='<br />'.&mt('Collaborators: ');
 2313: 	    foreach my $name (@good_collaborators) {
 2314: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2315: 		push(@col_fullnames, $givenn.' '.$lastname);
 2316: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2317: 	    }
 2318: 	    $result.='<br />'."\n";
 2319: 	    my ($part)=split(/\./,$part);
 2320: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2321: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2322: 		"\n";
 2323: 	}
 2324: 	if (scalar(@bad_collaborators) > 0) {
 2325: 	    $result.='<div class="LC_warning">';
 2326: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2327: 	    $result .= '</div>';
 2328: 	}         
 2329: 	if (scalar(@bad_collaborators > $ncol)) {
 2330: 	    $result .= '<div class="LC_warning">';
 2331: 	    $result .= &mt('This student has submitted too many '.
 2332: 		'collaborators.  Maximum is [_1].',$ncol);
 2333: 	    $result .= '</div>';
 2334: 	}
 2335:     }
 2336:     return ($result,$fullname,\@col_fullnames);
 2337: }
 2338: 
 2339: #--- Retrieve the last submission for all the parts
 2340: sub get_last_submission {
 2341:     my ($returnhash)=@_;
 2342:     my (@string,$timestamp);
 2343:     if ($$returnhash{'version'}) {
 2344: 	my %lasthash=();
 2345: 	my ($version);
 2346: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2347: 	    foreach my $key (sort(split(/\:/,
 2348: 					$$returnhash{$version.':keys'}))) {
 2349: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2350: 		$timestamp = 
 2351: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2352: 	    }
 2353: 	}
 2354: 	foreach my $key (keys(%lasthash)) {
 2355: 	    next if ($key !~ /\.submission$/);
 2356: 
 2357: 	    my ($partid,$foo) = split(/submission$/,$key);
 2358: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2359: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2360: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2361: 	}
 2362:     }
 2363:     if (!@string) {
 2364: 	$string[0] =
 2365: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2366:     }
 2367:     return (\@string,\$timestamp);
 2368: }
 2369: 
 2370: #--- High light keywords, with style choosen by user.
 2371: sub keywords_highlight {
 2372:     my $string    = shift;
 2373:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2374:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2375:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2376:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2377:     foreach my $keyword (@keylist) {
 2378: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2379:     }
 2380:     return $string;
 2381: }
 2382: 
 2383: #--- Called from submission routine
 2384: sub processHandGrade {
 2385:     my ($request) = shift;
 2386:     my $symb   = &get_symb($request);
 2387:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2388:     my $button = $env{'form.gradeOpt'};
 2389:     my $ngrade = $env{'form.NCT'};
 2390:     my $ntstu  = $env{'form.NTSTU'};
 2391:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2392:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2393: 
 2394:     if ($button eq 'Save & Next') {
 2395: 	my $ctr = 0;
 2396: 	while ($ctr < $ngrade) {
 2397: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2398: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2399: 	    if ($errorflag eq 'no_score') {
 2400: 		$ctr++;
 2401: 		next;
 2402: 	    }
 2403: 	    if ($errorflag eq 'not_allowed') {
 2404: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2405: 		$ctr++;
 2406: 		next;
 2407: 	    }
 2408: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2409: 	    my ($subject,$message,$msgstatus) = ('','','');
 2410: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2411:             my ($feedurl,$showsymb) =
 2412: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2413: 	    my $messagetail;
 2414: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2415: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2416: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2417: 		$subject.=' ['.$restitle.']';
 2418: 		my (@msgnum) = split(/,/,$includemsg);
 2419: 		foreach (@msgnum) {
 2420: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2421: 		}
 2422: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2423: 		if ($env{'form.withgrades'.$ctr}) {
 2424: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2425: 		    $messagetail = " for <a href=\"".
 2426: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2427: 		}
 2428: 		$msgstatus = 
 2429:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2430: 						     $message.$messagetail,
 2431:                                                      undef,$feedurl,undef,
 2432:                                                      undef,undef,$showsymb,
 2433:                                                      $restitle);
 2434: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2435: 				$msgstatus);
 2436: 	    }
 2437: 	    if ($env{'form.collaborator'.$ctr}) {
 2438: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2439: 		foreach my $collabstr (@collabstrs) {
 2440: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2441: 		    foreach my $collaborator (@collaborators) {
 2442: 			my ($errorflag,$pts,$wgt) = 
 2443: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2444: 					   $env{'form.unamedom'.$ctr},$part);
 2445: 			if ($errorflag eq 'not_allowed') {
 2446: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2447: 			    next;
 2448: 			} elsif ($message ne '') {
 2449: 			    my ($baseurl,$showsymb) = 
 2450: 				&get_feedurl_and_symb($symb,$collaborator,
 2451: 						      $udom);
 2452: 			    if ($env{'form.withgrades'.$ctr}) {
 2453: 				$messagetail = " for <a href=\"".
 2454:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2455: 			    }
 2456: 			    $msgstatus = 
 2457: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2458: 			}
 2459: 		    }
 2460: 		}
 2461: 	    }
 2462: 	    $ctr++;
 2463: 	}
 2464:     }
 2465: 
 2466:     if ($env{'form.handgrade'} eq 'yes') {
 2467: 	# Keywords sorted in alphabatical order
 2468: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2469: 	my %keyhash = ();
 2470: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2471: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2472: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2473: 	$env{'form.keywords'} = join(' ',@keywords);
 2474: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2475: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2476: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2477: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2478: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2479: 
 2480: 	# message center - Order of message gets changed. Blank line is eliminated.
 2481: 	# New messages are saved in env for the next student.
 2482: 	# All messages are saved in nohist_handgrade.db
 2483: 	my ($ctr,$idx) = (1,1);
 2484: 	while ($ctr <= $env{'form.savemsgN'}) {
 2485: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2486: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2487: 		$idx++;
 2488: 	    }
 2489: 	    $ctr++;
 2490: 	}
 2491: 	$ctr = 0;
 2492: 	while ($ctr < $ngrade) {
 2493: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2494: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2495: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2496: 		$idx++;
 2497: 	    }
 2498: 	    $ctr++;
 2499: 	}
 2500: 	$env{'form.savemsgN'} = --$idx;
 2501: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2502: 	my $putresult = &Apache::lonnet::put
 2503: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2504:     }
 2505:     # Called by Save & Refresh from Highlight Attribute Window
 2506:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2507:     if ($env{'form.refresh'} eq 'on') {
 2508: 	my ($ctr,$total) = (0,0);
 2509: 	while ($ctr < $ngrade) {
 2510: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2511: 	    $ctr++;
 2512: 	}
 2513: 	$env{'form.NTSTU'}=$ngrade;
 2514: 	$ctr = 0;
 2515: 	while ($ctr < $total) {
 2516: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2517: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2518: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2519: 	    &submission($request,$ctr,$total-1);
 2520: 	    $ctr++;
 2521: 	}
 2522: 	return '';
 2523:     }
 2524: 
 2525: # Go directly to grade student - from submission or link from chart page
 2526:     if ($button eq 'Grade Student') {
 2527: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2528: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2529: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2530: 	$env{'form.fullname'} = $$fullname{$processUser};
 2531: 	&submission($request,0,0);
 2532: 	return '';
 2533:     }
 2534: 
 2535:     # Get the next/previous one or group of students
 2536:     my $firststu = $env{'form.unamedom0'};
 2537:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2538:     my $ctr = 2;
 2539:     while ($laststu eq '') {
 2540: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2541: 	$ctr++;
 2542: 	$laststu = $firststu if ($ctr > $ngrade);
 2543:     }
 2544: 
 2545:     my (@parsedlist,@nextlist);
 2546:     my ($nextflg) = 0;
 2547:     foreach (sort 
 2548: 	     {
 2549: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2550: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2551: 		 }
 2552: 		 return $a cmp $b;
 2553: 	     } (keys(%$fullname))) {
 2554: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2555: 	    push @parsedlist,$_;
 2556: 	}
 2557: 	$nextflg = 1 if ($_ eq $laststu);
 2558: 	if ($button eq 'Previous') {
 2559: 	    last if ($_ eq $firststu);
 2560: 	    push @parsedlist,$_;
 2561: 	}
 2562:     }
 2563:     $ctr = 0;
 2564:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2565:     my ($partlist) = &response_type($symb);
 2566:     foreach my $student (@parsedlist) {
 2567: 	my $submitonly=$env{'form.submitonly'};
 2568: 	my ($uname,$udom) = split(/:/,$student);
 2569: 	
 2570: 	if ($submitonly eq 'queued') {
 2571: 	    my %queue_status = 
 2572: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2573: 							$udom,$uname);
 2574: 	    next if (!defined($queue_status{'gradingqueue'}));
 2575: 	}
 2576: 
 2577: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2578: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2579: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2580: 	    my $submitted = 0;
 2581: 	    my $ungraded = 0;
 2582: 	    my $incorrect = 0;
 2583: 	    foreach (keys(%status)) {
 2584: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2585: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2586: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2587: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2588: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2589: 		    $submitted = 0;
 2590: 		}
 2591: 	    }
 2592: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2593: 				     $submitonly eq 'incorrect' ||
 2594: 				     $submitonly eq 'graded'));
 2595: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2596: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2597: 	}
 2598: 	push @nextlist,$student if ($ctr < $ntstu);
 2599: 	last if ($ctr == $ntstu);
 2600: 	$ctr++;
 2601:     }
 2602: 
 2603:     $ctr = 0;
 2604:     my $total = scalar(@nextlist)-1;
 2605: 
 2606:     foreach (sort @nextlist) {
 2607: 	my ($uname,$udom,$submitter) = split(/:/);
 2608: 	$env{'form.student'}  = $uname;
 2609: 	$env{'form.userdom'}  = $udom;
 2610: 	$env{'form.fullname'} = $$fullname{$_};
 2611: 	&submission($request,$ctr,$total);
 2612: 	$ctr++;
 2613:     }
 2614:     if ($total < 0) {
 2615: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2616: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2617: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2618: 	$the_end.=&show_grading_menu_form($symb);
 2619: 	$request->print($the_end);
 2620:     }
 2621:     return '';
 2622: }
 2623: 
 2624: #---- Save the score and award for each student, if changed
 2625: sub saveHandGrade {
 2626:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2627:     my @version_parts;
 2628:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2629: 					   $env{'request.course.id'});
 2630:     if (!&canmodify($usec)) { return('not_allowed'); }
 2631:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2632:     my @parts_graded;
 2633:     my %newrecord  = ();
 2634:     my ($pts,$wgt) = ('','');
 2635:     my %aggregate = ();
 2636:     my $aggregateflag = 0;
 2637:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2638:     foreach my $new_part (@parts) {
 2639: 	#collaborator ($submi may vary for different parts
 2640: 	if ($submitter && $new_part ne $part) { next; }
 2641: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2642: 	if ($dropMenu eq 'excused') {
 2643: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2644: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2645: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2646: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2647: 		}
 2648: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2649: 	    }
 2650: 	} elsif ($dropMenu eq 'reset status'
 2651: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2652: 	    foreach my $key (keys (%record)) {
 2653: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2654: 	    }
 2655: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2656: 		"$env{'user.name'}:$env{'user.domain'}";
 2657:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2658: 
 2659:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2660: 					       [$new_part]);
 2661:             my $aggtries =$totaltries;
 2662:             if ($last_resets{$new_part}) {
 2663:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2664: 					   $new_part);
 2665:             }
 2666: 
 2667:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2668:             if ($aggtries > 0) {
 2669:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2670:                 $aggregateflag = 1;
 2671:             }
 2672: 	} elsif ($dropMenu eq '') {
 2673: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2674: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2675: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2676: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2677: 		next;
 2678: 	    }
 2679: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2680: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2681: 	    my $partial= $pts/$wgt;
 2682: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2683: 		#do not update score for part if not changed.
 2684:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2685: 		next;
 2686: 	    } else {
 2687: 	        push @parts_graded, $new_part;
 2688: 	    }
 2689: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2690: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2691: 	    }
 2692: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2693: 	    if ($partial == 0) {
 2694: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2695: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2696: 		}
 2697: 	    } else {
 2698: 		if ($record{$reckey} ne 'correct_by_override') {
 2699: 		    $newrecord{$reckey} = 'correct_by_override';
 2700: 		}
 2701: 	    }	    
 2702: 	    if ($submitter && 
 2703: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2704: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2705: 	    }
 2706: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2707: 		"$env{'user.name'}:$env{'user.domain'}";
 2708: 	}
 2709: 	# unless problem has been graded, set flag to version the submitted files
 2710: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2711: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2712: 	        $dropMenu eq 'reset status')
 2713: 	   {
 2714: 	    push (@version_parts,$new_part);
 2715: 	}
 2716:     }
 2717:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2718:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2719: 
 2720:     if (%newrecord) {
 2721:         if (@version_parts) {
 2722:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2723:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2724: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2725: 	    foreach my $new_part (@version_parts) {
 2726: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2727: 				$new_part,\%newrecord);
 2728: 	    }
 2729:         }
 2730: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2731: 				$env{'request.course.id'},$domain,$stuname);
 2732: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2733: 				     $cdom,$cnum,$domain,$stuname);
 2734:     }
 2735:     if ($aggregateflag) {
 2736:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2737: 			      $cdom,$cnum);
 2738:     }
 2739:     return ('',$pts,$wgt);
 2740: }
 2741: 
 2742: sub check_and_remove_from_queue {
 2743:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2744:     my @ungraded_parts;
 2745:     foreach my $part (@{$parts}) {
 2746: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2747: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2748: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2749: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2750: 		) {
 2751: 	    push(@ungraded_parts, $part);
 2752: 	}
 2753:     }
 2754:     if ( !@ungraded_parts ) {
 2755: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2756: 					       $cnum,$domain,$stuname);
 2757:     }
 2758: }
 2759: 
 2760: sub handback_files {
 2761:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2762:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2763:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2764: 
 2765:     my @part_response_id = &flatten_responseType($responseType);
 2766:     foreach my $part_response_id (@part_response_id) {
 2767:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2768: 	my $part_resp = join('_',@{ $part_response_id });
 2769:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2770:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2771:                 my $file_counter = 1;
 2772: 		my $file_msg;
 2773:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2774:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2775:                     my ($directory,$answer_file) = 
 2776:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2777:                     my ($answer_name,$answer_ver,$answer_ext) =
 2778: 		        &file_name_version_ext($answer_file);
 2779: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2780: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2781: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2782:                     # fix file name
 2783:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2784:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2785:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2786:             	                                $save_file_name);
 2787:                     if ($result !~ m|^/uploaded/|) {
 2788:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2789:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2790:                     } else {
 2791:                         # mark the file as read only
 2792:                         my @files = ($save_file_name);
 2793:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2794:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2795: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2796: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2797: 			}
 2798:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2799: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2800: 
 2801:                     }
 2802:                     $request->print("<br />".$fname." will be the uploaded file name");
 2803:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2804:                     $file_counter++;
 2805:                 }
 2806: 		my $subject = "File Handed Back by Instructor ";
 2807: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2808: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2809: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2810: 		$message .= " and can be found in your portfolio space.";
 2811: 		my ($feedurl,$showsymb) = 
 2812: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2813:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2814: 		my $msgstatus = 
 2815:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2816: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2817:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2818:             }
 2819:         }
 2820:     return;
 2821: }
 2822: 
 2823: sub get_feedurl_and_symb {
 2824:     my ($symb,$uname,$udom) = @_;
 2825:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2826:     $url = &Apache::lonnet::clutter($url);
 2827:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2828: 					$symb,$udom,$uname);
 2829:     if ($encrypturl =~ /^yes$/i) {
 2830: 	&Apache::lonenc::encrypted(\$url,1);
 2831: 	&Apache::lonenc::encrypted(\$symb,1);
 2832:     }
 2833:     return ($url,$symb);
 2834: }
 2835: 
 2836: sub get_submitted_files {
 2837:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2838:     my @files;
 2839:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2840:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2841:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2842:     	    push(@files,$file_url.$file);
 2843:         }
 2844:     }
 2845:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2846:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2847:     }
 2848:     return (\@files);
 2849: }
 2850: 
 2851: # ----------- Provides number of tries since last reset.
 2852: sub get_num_tries {
 2853:     my ($record,$last_reset,$part) = @_;
 2854:     my $timestamp = '';
 2855:     my $num_tries = 0;
 2856:     if ($$record{'version'}) {
 2857:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2858:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2859:                 $timestamp = $$record{$version.':timestamp'};
 2860:                 if ($timestamp > $last_reset) {
 2861:                     $num_tries ++;
 2862:                 } else {
 2863:                     last;
 2864:                 }
 2865:             }
 2866:         }
 2867:     }
 2868:     return $num_tries;
 2869: }
 2870: 
 2871: # ----------- Determine decrements required in aggregate totals 
 2872: sub decrement_aggs {
 2873:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2874:     my %decrement = (
 2875:                         attempts => 0,
 2876:                         users => 0,
 2877:                         correct => 0
 2878:                     );
 2879:     $decrement{'attempts'} = $aggtries;
 2880:     if ($solvedstatus =~ /^correct/) {
 2881:         $decrement{'correct'} = 1;
 2882:     }
 2883:     if ($aggtries == $totaltries) {
 2884:         $decrement{'users'} = 1;
 2885:     }
 2886:     foreach my $type (keys (%decrement)) {
 2887:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2888:     }
 2889:     return;
 2890: }
 2891: 
 2892: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2893: sub get_last_resets {
 2894:     my ($symb,$courseid,$partids) =@_;
 2895:     my %last_resets;
 2896:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2897:     my $cname = $env{'course.'.$courseid.'.num'};
 2898:     my @keys;
 2899:     foreach my $part (@{$partids}) {
 2900: 	push(@keys,"$symb\0$part\0resettime");
 2901:     }
 2902:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2903: 				     $cdom,$cname);
 2904:     foreach my $part (@{$partids}) {
 2905: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2906:     }
 2907:     return %last_resets;
 2908: }
 2909: 
 2910: # ----------- Handles creating versions for portfolio files as answers
 2911: sub version_portfiles {
 2912:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2913:     my $version_parts = join('|',@$v_flag);
 2914:     my @returned_keys;
 2915:     my $parts = join('|', @$parts_graded);
 2916:     my $portfolio_root = &propath($domain,$stu_name).
 2917: 	'/userfiles/portfolio';
 2918:     foreach my $key (keys(%$record)) {
 2919:         my $new_portfiles;
 2920:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2921:             my @versioned_portfiles;
 2922:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2923:             foreach my $file (@portfiles) {
 2924:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2925:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2926: 		my ($answer_name,$answer_ver,$answer_ext) =
 2927: 		    &file_name_version_ext($answer_file);
 2928:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2929:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2930:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2931:                 if ($new_answer ne 'problem getting file') {
 2932:                     push(@versioned_portfiles, $directory.$new_answer);
 2933:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2934:                         [$directory.$new_answer],
 2935:                         [$symb,$env{'request.course.id'},'graded']);
 2936:                 }
 2937:             }
 2938:             $$record{$key} = join(',',@versioned_portfiles);
 2939:             push(@returned_keys,$key);
 2940:         }
 2941:     } 
 2942:     return (@returned_keys);   
 2943: }
 2944: 
 2945: sub get_next_version {
 2946:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2947:     my $version;
 2948:     foreach my $row (@$dir_list) {
 2949:         my ($file) = split(/\&/,$row,2);
 2950:         my ($file_name,$file_version,$file_ext) =
 2951: 	    &file_name_version_ext($file);
 2952:         if (($file_name eq $answer_name) && 
 2953: 	    ($file_ext eq $answer_ext)) {
 2954:                 # gets here if filename and extension match, regardless of version
 2955:                 if ($file_version ne '') {
 2956:                 # a versioned file is found  so save it for later
 2957:                 if ($file_version > $version) {
 2958: 		    $version = $file_version;
 2959: 	        }
 2960:             }
 2961:         }
 2962:     } 
 2963:     $version ++;
 2964:     return($version);
 2965: }
 2966: 
 2967: sub version_selected_portfile {
 2968:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2969:     my ($answer_name,$answer_ver,$answer_ext) =
 2970:         &file_name_version_ext($file_name);
 2971:     my $new_answer;
 2972:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2973:     if($env{'form.copy'} eq '-1') {
 2974:         $new_answer = 'problem getting file';
 2975:     } else {
 2976:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2977:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2978:                             $stu_name,$domain,'copy',
 2979: 		        '/portfolio'.$directory.$new_answer);
 2980:     }    
 2981:     return ($new_answer);
 2982: }
 2983: 
 2984: sub file_name_version_ext {
 2985:     my ($file)=@_;
 2986:     my @file_parts = split(/\./, $file);
 2987:     my ($name,$version,$ext);
 2988:     if (@file_parts > 1) {
 2989: 	$ext=pop(@file_parts);
 2990: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2991: 	    $version=pop(@file_parts);
 2992: 	}
 2993: 	$name=join('.',@file_parts);
 2994:     } else {
 2995: 	$name=join('.',@file_parts);
 2996:     }
 2997:     return($name,$version,$ext);
 2998: }
 2999: 
 3000: #--------------------------------------------------------------------------------------
 3001: #
 3002: #-------------------------- Next few routines handles grading by section or whole class
 3003: #
 3004: #--- Javascript to handle grading by section or whole class
 3005: sub viewgrades_js {
 3006:     my ($request) = shift;
 3007: 
 3008:     $request->print(<<VIEWJAVASCRIPT);
 3009: <script type="text/javascript" language="javascript">
 3010:    function writePoint(partid,weight,point) {
 3011: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3012: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3013: 	if (point == "textval") {
 3014: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3015: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3016: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3017: 		var resetbox = false;
 3018: 		for (var i=0; i<radioButton.length; i++) {
 3019: 		    if (radioButton[i].checked) {
 3020: 			textbox.value = i;
 3021: 			resetbox = true;
 3022: 		    }
 3023: 		}
 3024: 		if (!resetbox) {
 3025: 		    textbox.value = "";
 3026: 		}
 3027: 		return;
 3028: 	    }
 3029: 	    if (parseFloat(point) > parseFloat(weight)) {
 3030: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3031: 				   ") greater than the weight for the part. Accept?");
 3032: 		if (resp == false) {
 3033: 		    textbox.value = "";
 3034: 		    return;
 3035: 		}
 3036: 	    }
 3037: 	    for (var i=0; i<radioButton.length; i++) {
 3038: 		radioButton[i].checked=false;
 3039: 		if (parseFloat(point) == i) {
 3040: 		    radioButton[i].checked=true;
 3041: 		}
 3042: 	    }
 3043: 
 3044: 	} else {
 3045: 	    textbox.value = parseFloat(point);
 3046: 	}
 3047: 	for (i=0;i<document.classgrade.total.value;i++) {
 3048: 	    var user = document.classgrade["ctr"+i].value;
 3049: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3050: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3051: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3052: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3053: 	    if (saveval != "correct") {
 3054: 		scorename.value = point;
 3055: 		if (selname[0].selected != true) {
 3056: 		    selname[0].selected = true;
 3057: 		}
 3058: 	    }
 3059: 	}
 3060: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3061:     }
 3062: 
 3063:     function writeRadText(partid,weight) {
 3064: 	var selval   = document.classgrade["SELVAL_"+partid];
 3065: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3066:         var override = document.classgrade["FORCE_"+partid].checked;
 3067: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3068: 	if (selval[1].selected || selval[2].selected) {
 3069: 	    for (var i=0; i<radioButton.length; i++) {
 3070: 		radioButton[i].checked=false;
 3071: 
 3072: 	    }
 3073: 	    textbox.value = "";
 3074: 
 3075: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3076: 		var user = document.classgrade["ctr"+i].value;
 3077: 		user = user.replace(new RegExp(':', 'g'),"_");
 3078: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3079: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3080: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3081: 		if ((saveval != "correct") || override) {
 3082: 		    scorename.value = "";
 3083: 		    if (selval[1].selected) {
 3084: 			selname[1].selected = true;
 3085: 		    } else {
 3086: 			selname[2].selected = true;
 3087: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3088: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3089: 		    }
 3090: 		}
 3091: 	    }
 3092: 	} else {
 3093: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3094: 		var user = document.classgrade["ctr"+i].value;
 3095: 		user = user.replace(new RegExp(':', 'g'),"_");
 3096: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3097: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3098: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3099: 		if ((saveval != "correct") || override) {
 3100: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3101: 		    selname[0].selected = true;
 3102: 		}
 3103: 	    }
 3104: 	}	    
 3105:     }
 3106: 
 3107:     function changeSelect(partid,user) {
 3108: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3109: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3110: 	var point  = textbox.value;
 3111: 	var weight = document.classgrade["weight_"+partid].value;
 3112: 
 3113: 	if (isNaN(point) || parseFloat(point) < 0) {
 3114: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3115: 	    textbox.value = "";
 3116: 	    return;
 3117: 	}
 3118: 	if (parseFloat(point) > parseFloat(weight)) {
 3119: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3120: 			       ") greater than the weight of the part. Accept?");
 3121: 	    if (resp == false) {
 3122: 		textbox.value = "";
 3123: 		return;
 3124: 	    }
 3125: 	}
 3126: 	selval[0].selected = true;
 3127:     }
 3128: 
 3129:     function changeOneScore(partid,user) {
 3130: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3131: 	if (selval[1].selected || selval[2].selected) {
 3132: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3133: 	    if (selval[2].selected) {
 3134: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3135: 	    }
 3136:         }
 3137:     }
 3138: 
 3139:     function resetEntry(numpart) {
 3140: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3141: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3142: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3143: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3144: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3145: 	    for (var i=0; i<radioButton.length; i++) {
 3146: 		radioButton[i].checked=false;
 3147: 
 3148: 	    }
 3149: 	    textbox.value = "";
 3150: 	    selval[0].selected = true;
 3151: 
 3152: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3153: 		var user = document.classgrade["ctr"+i].value;
 3154: 		user = user.replace(new RegExp(':', 'g'),"_");
 3155: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3156: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3157: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3158: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3159: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3160: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3161: 		if (saveselval == "excused") {
 3162: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3163: 		} else {
 3164: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3165: 		}
 3166: 	    }
 3167: 	}
 3168:     }
 3169: 
 3170: </script>
 3171: VIEWJAVASCRIPT
 3172: }
 3173: 
 3174: #--- show scores for a section or whole class w/ option to change/update a score
 3175: sub viewgrades {
 3176:     my ($request) = shift;
 3177:     &viewgrades_js($request);
 3178: 
 3179:     my ($symb) = &get_symb($request);
 3180:     #need to make sure we have the correct data for later EXT calls, 
 3181:     #thus invalidate the cache
 3182:     &Apache::lonnet::devalidatecourseresdata(
 3183:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3184:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3185:     &Apache::lonnet::clear_EXT_cache_status();
 3186: 
 3187:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3188:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3189: 
 3190:     #view individual student submission form - called using Javascript viewOneStudent
 3191:     $result.=&jscriptNform($symb);
 3192: 
 3193:     #beginning of class grading form
 3194:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3195:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3196: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3197: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3198: 	&build_section_inputs().
 3199: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3200: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3201: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3202: 
 3203:     my $sectionClass;
 3204:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3205:     if ($env{'form.section'} eq 'all') {
 3206: 	$sectionClass='Class';
 3207:     } elsif ($env{'form.section'} eq 'none') {
 3208: 	$sectionClass='Students in no Section';
 3209:     } else {
 3210: 	$sectionClass='Students in Section(s) [_1]';
 3211:     }
 3212:     $result.=
 3213: 	'<h3>'.
 3214: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3215:     $result.= &Apache::loncommon::start_data_table();
 3216:     #radio buttons/text box for assigning points for a section or class.
 3217:     #handles different parts of a problem
 3218:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3219:     my %weight = ();
 3220:     my $ctsparts = 0;
 3221:     my %seen = ();
 3222:     my @part_response_id = &flatten_responseType($responseType);
 3223:     foreach my $part_response_id (@part_response_id) {
 3224:     	my ($partid,$respid) = @{ $part_response_id };
 3225: 	my $part_resp = join('_',@{ $part_response_id });
 3226: 	next if $seen{$partid};
 3227: 	$seen{$partid}++;
 3228: 	my $handgrade=$$handgrade{$part_resp};
 3229: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3230: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3231: 
 3232: 	my $display_part=&get_display_part($partid,$symb);
 3233: 	my $radio.='<table border="0"><tr>';  
 3234: 	my $ctr = 0;
 3235: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3236: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3237: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3238: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3239: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3240: 	    $ctr++;
 3241: 	}
 3242: 	$radio.='</tr></table>';
 3243: 	my $line = '<input type="text" name="TEXTVAL_'.
 3244: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3245: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3246: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3247: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3248: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3249: 		$weight{$partid}.')"> '.
 3250: 	    '<option selected="selected"> </option>'.
 3251: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3252: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3253: 	    '</select></td>'.
 3254:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3255: 	$line.='<input type="hidden" name="partid_'.
 3256: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3257: 	$line.='<input type="hidden" name="weight_'.
 3258: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3259: 
 3260: 	$result.=
 3261: 	    &Apache::loncommon::start_data_table_row()."\n".
 3262: 	    &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).
 3263: 	    &Apache::loncommon::end_data_table_row()."\n";
 3264: 	$ctsparts++;
 3265:     }
 3266:     $result.=&Apache::loncommon::end_data_table()."\n".
 3267: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3268:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3269: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3270: 
 3271:     #table listing all the students in a section/class
 3272:     #header of table
 3273:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3274: 			 $section_display).'</h3>';
 3275:     $result.= &Apache::loncommon::start_data_table().
 3276: 	&Apache::loncommon::start_data_table_header_row().
 3277: 	'<th>'.&mt('No.').'</th>'.
 3278: 	'<th>'.&nameUserString('header')."</th>\n";
 3279:     my (@parts) = sort(&getpartlist($symb));
 3280:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3281:     my @partids = ();
 3282:     foreach my $part (@parts) {
 3283: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3284: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3285: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3286: 	my ($partid) = &split_part_type($part);
 3287:         push(@partids, $partid);
 3288: 	my $display_part=&get_display_part($partid,$symb);
 3289: 	if ($display =~ /^Partial Credit Factor/) {
 3290: 	    $result.='<th>'.
 3291: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3292: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3293: 	    next;
 3294: 	    
 3295: 	} else {
 3296: 	    if ($display =~ /Problem Status/) {
 3297: 		my $grade_status_mt = &mt('Grade Status');
 3298: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3299: 	    }
 3300: 	    my $part_mt = &mt('Part:');
 3301: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3302: 	}
 3303: 
 3304: 	$result.='<th>'.$display.'</th>'."\n";
 3305:     }
 3306:     $result.=&Apache::loncommon::end_data_table_header_row();
 3307: 
 3308:     my %last_resets = 
 3309: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3310: 
 3311:     #get info for each student
 3312:     #list all the students - with points and grade status
 3313:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3314:     my $ctr = 0;
 3315:     foreach (sort 
 3316: 	     {
 3317: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3318: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3319: 		 }
 3320: 		 return $a cmp $b;
 3321: 	     } (keys(%$fullname))) {
 3322: 	$ctr++;
 3323: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3324: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3325:     }
 3326:     $result.=&Apache::loncommon::end_data_table();
 3327:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3328:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3329: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3330:     if (scalar(%$fullname) eq 0) {
 3331: 	my $colspan=3+scalar(@parts);
 3332: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3333:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3334: 	$result='<span class="LC_warning">'.
 3335: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3336: 	        $section_display, $stu_status).
 3337: 	    '</span>';
 3338:     }
 3339:     $result.=&show_grading_menu_form($symb);
 3340:     return $result;
 3341: }
 3342: 
 3343: #--- call by previous routine to display each student
 3344: sub viewstudentgrade {
 3345:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3346:     my ($uname,$udom) = split(/:/,$student);
 3347:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3348:     my %aggregates = (); 
 3349:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3350: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3351: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3352: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3353: 	'\');" target="_self">'.$fullname.'</a> '.
 3354: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3355:     $student=~s/:/_/; # colon doen't work in javascript for names
 3356:     foreach my $apart (@$parts) {
 3357: 	my ($part,$type) = &split_part_type($apart);
 3358: 	my $score=$record{"resource.$part.$type"};
 3359:         $result.='<td align="center">';
 3360:         my ($aggtries,$totaltries);
 3361:         unless (exists($aggregates{$part})) {
 3362: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3363: 
 3364: 	    $aggtries = $totaltries;
 3365:             if ($$last_resets{$part}) {  
 3366:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3367: 					   $part);
 3368:             }
 3369:             $result.='<input type="hidden" name="'.
 3370:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3371:             $result.='<input type="hidden" name="'.
 3372:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3373:             $aggregates{$part} = 1;
 3374:         }
 3375: 	if ($type eq 'awarded') {
 3376: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3377: 	    $result.='<input type="hidden" name="'.
 3378: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3379: 	    $result.='<input type="text" name="'.
 3380: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3381: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3382: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3383: 	} elsif ($type eq 'solved') {
 3384: 	    my ($status,$foo)=split(/_/,$score,2);
 3385: 	    $status = 'nothing' if ($status eq '');
 3386: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3387: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3388: 	    $result.='&nbsp;<select name="'.
 3389: 		'GD_'.$student.'_'.$part.'_solved" '.
 3390: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3391: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3392: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3393: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3394: 	    $result.="</select>&nbsp;</td>\n";
 3395: 	} else {
 3396: 	    $result.='<input type="hidden" name="'.
 3397: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3398: 		    "\n";
 3399: 	    $result.='<input type="text" name="'.
 3400: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3401: 		'value="'.$score.'" size="4" /></td>'."\n";
 3402: 	}
 3403:     }
 3404:     $result.=&Apache::loncommon::end_data_table_row();
 3405:     return $result;
 3406: }
 3407: 
 3408: #--- change scores for all the students in a section/class
 3409: #    record does not get update if unchanged
 3410: sub editgrades {
 3411:     my ($request) = @_;
 3412: 
 3413:     my $symb=&get_symb($request);
 3414:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3415:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3416:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3417:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3418: 
 3419:     my $result= &Apache::loncommon::start_data_table().
 3420: 	&Apache::loncommon::start_data_table_header_row().
 3421: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3422: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3423:     my %scoreptr = (
 3424: 		    'correct'  =>'correct_by_override',
 3425: 		    'incorrect'=>'incorrect_by_override',
 3426: 		    'excused'  =>'excused',
 3427: 		    'ungraded' =>'ungraded_attempted',
 3428: 		    'nothing'  => '',
 3429: 		    );
 3430:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3431: 
 3432:     my (@partid);
 3433:     my %weight = ();
 3434:     my %columns = ();
 3435:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3436: 
 3437:     my (@parts) = sort(&getpartlist($symb));
 3438:     my $header;
 3439:     while ($ctr < $env{'form.totalparts'}) {
 3440: 	my $partid = $env{'form.partid_'.$ctr};
 3441: 	push @partid,$partid;
 3442: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3443: 	$ctr++;
 3444:     }
 3445:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3446:     foreach my $partid (@partid) {
 3447: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3448: 	    '<th align="center">'.&mt('New Score').'</th>';
 3449: 	$columns{$partid}=2;
 3450: 	foreach my $stores (@parts) {
 3451: 	    my ($part,$type) = &split_part_type($stores);
 3452: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3453: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3454: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3455: 	    $display =~ s/\[Part: (\w)+\]//;
 3456: 	    $display =~ s/Number of Attempts/Tries/;
 3457: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3458: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3459: 	    $columns{$partid}+=2;
 3460: 	}
 3461:     }
 3462:     foreach my $partid (@partid) {
 3463: 	my $display_part=&get_display_part($partid,$symb);
 3464: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3465: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3466: 	    '</th>';
 3467: 
 3468:     }
 3469:     $result .= &Apache::loncommon::end_data_table_header_row().
 3470: 	&Apache::loncommon::start_data_table_header_row().
 3471: 	$header.
 3472: 	&Apache::loncommon::end_data_table_header_row();
 3473:     my @noupdate;
 3474:     my ($updateCtr,$noupdateCtr) = (1,1);
 3475:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3476: 	my $line;
 3477: 	my $user = $env{'form.ctr'.$i};
 3478: 	my ($uname,$udom)=split(/:/,$user);
 3479: 	my %newrecord;
 3480: 	my $updateflag = 0;
 3481: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3482: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3483: 	if (!&canmodify($usec)) {
 3484: 	    my $numcols=scalar(@partid)*4+2;
 3485: 	    push(@noupdate,
 3486: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3487: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3488: 	    next;
 3489: 	}
 3490:         my %aggregate = ();
 3491:         my $aggregateflag = 0;
 3492: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3493: 	foreach (@partid) {
 3494: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3495: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3496: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3497: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3498: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3499: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3500: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3501: 	    my $score;
 3502: 	    if ($partial eq '') {
 3503: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3504: 	    } elsif ($partial > 0) {
 3505: 		$score = 'correct_by_override';
 3506: 	    } elsif ($partial == 0) {
 3507: 		$score = 'incorrect_by_override';
 3508: 	    }
 3509: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3510: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3511: 
 3512: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3513: 		"$env{'user.name'}:$env{'user.domain'}";
 3514: 	    if ($dropMenu eq 'reset status' &&
 3515: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3516: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3517: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3518: 		$newrecord{'resource.'.$_.'.award'} = '';
 3519: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3520: 		$updateflag = 1;
 3521:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3522:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3523:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3524:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3525:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3526:                     $aggregateflag = 1;
 3527:                 }
 3528: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3529: 		$updateflag = 1;
 3530: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3531: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3532: 		$rec_update++;
 3533: 	    }
 3534: 
 3535: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3536: 		'<td align="center">'.$awarded.
 3537: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3538: 
 3539: 
 3540: 	    my $partid=$_;
 3541: 	    foreach my $stores (@parts) {
 3542: 		my ($part,$type) = &split_part_type($stores);
 3543: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3544: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3545: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3546: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3547: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3548: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3549: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3550: 		    $updateflag=1;
 3551: 		}
 3552: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3553: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3554: 	    }
 3555: 	}
 3556: 	$line.="\n";
 3557: 
 3558: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3559: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3560: 
 3561: 	if ($updateflag) {
 3562: 	    $count++;
 3563: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3564: 				    $udom,$uname);
 3565: 
 3566: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3567: 					      $cnum,$udom,$uname)) {
 3568: 		# need to figure out if should be in queue.
 3569: 		my %record =  
 3570: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3571: 					     $udom,$uname);
 3572: 		my $all_graded = 1;
 3573: 		my $none_graded = 1;
 3574: 		foreach my $part (@parts) {
 3575: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3576: 			$all_graded = 0;
 3577: 		    } else {
 3578: 			$none_graded = 0;
 3579: 		    }
 3580: 		}
 3581: 
 3582: 		if ($all_graded || $none_graded) {
 3583: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3584: 							   $symb,$cdom,$cnum,
 3585: 							   $udom,$uname);
 3586: 		}
 3587: 	    }
 3588: 
 3589: 	    $result.=&Apache::loncommon::start_data_table_row().
 3590: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3591: 		&Apache::loncommon::end_data_table_row();
 3592: 	    $updateCtr++;
 3593: 	} else {
 3594: 	    push(@noupdate,
 3595: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3596: 	    $noupdateCtr++;
 3597: 	}
 3598:         if ($aggregateflag) {
 3599:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3600: 				  $cdom,$cnum);
 3601:         }
 3602:     }
 3603:     if (@noupdate) {
 3604: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3605: 	my $numcols=scalar(@partid)*4+2;
 3606: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3607: 	    '<td align="center" colspan="'.$numcols.'">'.
 3608: 	    &mt('No Changes Occurred For the Students Below').
 3609: 	    '</td>'.
 3610: 	    &Apache::loncommon::end_data_table_row();
 3611: 	foreach my $line (@noupdate) {
 3612: 	    $result.=
 3613: 		&Apache::loncommon::start_data_table_row().
 3614: 		$line.
 3615: 		&Apache::loncommon::end_data_table_row();
 3616: 	}
 3617:     }
 3618:     $result .= &Apache::loncommon::end_data_table().
 3619: 	&show_grading_menu_form($symb);
 3620:     my $msg = '<p><b>'.
 3621: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3622: 	    $rec_update,$count).'</b><br />'.
 3623: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3624: 	'</b></p>';
 3625:     return $title.$msg.$result;
 3626: }
 3627: 
 3628: sub split_part_type {
 3629:     my ($partstr) = @_;
 3630:     my ($temp,@allparts)=split(/_/,$partstr);
 3631:     my $type=pop(@allparts);
 3632:     my $part=join('_',@allparts);
 3633:     return ($part,$type);
 3634: }
 3635: 
 3636: #------------- end of section for handling grading by section/class ---------
 3637: #
 3638: #----------------------------------------------------------------------------
 3639: 
 3640: 
 3641: #----------------------------------------------------------------------------
 3642: #
 3643: #-------------------------- Next few routines handles grading by csv upload
 3644: #
 3645: #--- Javascript to handle csv upload
 3646: sub csvupload_javascript_reverse_associate {
 3647:     my $error1=&mt('You need to specify the username or ID');
 3648:     my $error2=&mt('You need to specify at least one grading field');
 3649:   return(<<ENDPICK);
 3650:   function verify(vf) {
 3651:     var foundsomething=0;
 3652:     var founduname=0;
 3653:     var foundID=0;
 3654:     for (i=0;i<=vf.nfields.value;i++) {
 3655:       tw=eval('vf.f'+i+'.selectedIndex');
 3656:       if (i==0 && tw!=0) { foundID=1; }
 3657:       if (i==1 && tw!=0) { founduname=1; }
 3658:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3659:     }
 3660:     if (founduname==0 && foundID==0) {
 3661: 	alert('$error1');
 3662: 	return;
 3663:     }
 3664:     if (foundsomething==0) {
 3665: 	alert('$error2');
 3666: 	return;
 3667:     }
 3668:     vf.submit();
 3669:   }
 3670:   function flip(vf,tf) {
 3671:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3672:     var i;
 3673:     for (i=0;i<=vf.nfields.value;i++) {
 3674:       //can not pick the same destination field for both name and domain
 3675:       if (((i ==0)||(i ==1)) && 
 3676:           ((tf==0)||(tf==1)) && 
 3677:           (i!=tf) &&
 3678:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3679:         eval('vf.f'+i+'.selectedIndex=0;')
 3680:       }
 3681:     }
 3682:   }
 3683: ENDPICK
 3684: }
 3685: 
 3686: sub csvupload_javascript_forward_associate {
 3687:     my $error1=&mt('You need to specify the username or ID');
 3688:     my $error2=&mt('You need to specify at least one grading field');
 3689:   return(<<ENDPICK);
 3690:   function verify(vf) {
 3691:     var foundsomething=0;
 3692:     var founduname=0;
 3693:     var foundID=0;
 3694:     for (i=0;i<=vf.nfields.value;i++) {
 3695:       tw=eval('vf.f'+i+'.selectedIndex');
 3696:       if (tw==1) { foundID=1; }
 3697:       if (tw==2) { founduname=1; }
 3698:       if (tw>3) { foundsomething=1; }
 3699:     }
 3700:     if (founduname==0 && foundID==0) {
 3701: 	alert('$error1');
 3702: 	return;
 3703:     }
 3704:     if (foundsomething==0) {
 3705: 	alert('$error2');
 3706: 	return;
 3707:     }
 3708:     vf.submit();
 3709:   }
 3710:   function flip(vf,tf) {
 3711:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3712:     var i;
 3713:     //can not pick the same destination field twice
 3714:     for (i=0;i<=vf.nfields.value;i++) {
 3715:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3716:         eval('vf.f'+i+'.selectedIndex=0;')
 3717:       }
 3718:     }
 3719:   }
 3720: ENDPICK
 3721: }
 3722: 
 3723: sub csvuploadmap_header {
 3724:     my ($request,$symb,$datatoken,$distotal)= @_;
 3725:     my $javascript;
 3726:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3727: 	$javascript=&csvupload_javascript_reverse_associate();
 3728:     } else {
 3729: 	$javascript=&csvupload_javascript_forward_associate();
 3730:     }
 3731: 
 3732:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3733:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3734:     my $ignore=&mt('Ignore First Line');
 3735:     $symb = &Apache::lonenc::check_encrypt($symb);
 3736:     $request->print(<<ENDPICK);
 3737: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3738: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3739: $result
 3740: <hr />
 3741: <h3>Identify fields</h3>
 3742: Total number of records found in file: $distotal <hr />
 3743: Enter as many fields as you can. The system will inform you and bring you back
 3744: to this page if the data selected is insufficient to run your class.<hr />
 3745: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3746: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3747: <input type="hidden" name="associate"  value="" />
 3748: <input type="hidden" name="phase"      value="three" />
 3749: <input type="hidden" name="datatoken"  value="$datatoken" />
 3750: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3751: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3752: <input type="hidden" name="upfile_associate" 
 3753:                                        value="$env{'form.upfile_associate'}" />
 3754: <input type="hidden" name="symb"       value="$symb" />
 3755: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3756: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3757: <input type="hidden" name="command"    value="csvuploadoptions" />
 3758: <hr />
 3759: <script type="text/javascript" language="Javascript">
 3760: $javascript
 3761: </script>
 3762: ENDPICK
 3763:     return '';
 3764: 
 3765: }
 3766: 
 3767: sub csvupload_fields {
 3768:     my ($symb) = @_;
 3769:     my (@parts) = &getpartlist($symb);
 3770:     my @fields=(['ID','Student ID'],
 3771: 		['username','Student Username'],
 3772: 		['domain','Student Domain']);
 3773:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3774:     foreach my $part (sort(@parts)) {
 3775: 	my @datum;
 3776: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3777: 	my $name=$part;
 3778: 	if  (!$display) { $display = $name; }
 3779: 	@datum=($name,$display);
 3780: 	if ($name=~/^stores_(.*)_awarded/) {
 3781: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3782: 	}
 3783: 	push(@fields,\@datum);
 3784:     }
 3785:     return (@fields);
 3786: }
 3787: 
 3788: sub csvuploadmap_footer {
 3789:     my ($request,$i,$keyfields) =@_;
 3790:     $request->print(<<ENDPICK);
 3791: </table>
 3792: <input type="hidden" name="nfields" value="$i" />
 3793: <input type="hidden" name="keyfields" value="$keyfields" />
 3794: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3795: </form>
 3796: ENDPICK
 3797: }
 3798: 
 3799: sub checkforfile_js {
 3800:     my $result =<<CSVFORMJS;
 3801: <script type="text/javascript" language="javascript">
 3802:     function checkUpload(formname) {
 3803: 	if (formname.upfile.value == "") {
 3804: 	    alert("Please use the browse button to select a file from your local directory.");
 3805: 	    return false;
 3806: 	}
 3807: 	formname.submit();
 3808:     }
 3809:     </script>
 3810: CSVFORMJS
 3811:     return $result;
 3812: }
 3813: 
 3814: sub upcsvScores_form {
 3815:     my ($request) = shift;
 3816:     my ($symb)=&get_symb($request);
 3817:     if (!$symb) {return '';}
 3818:     my $result=&checkforfile_js();
 3819:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3820:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3821:     $result.=$table;
 3822:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3823:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3824:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3825: 	'.</b></td></tr>'."\n";
 3826:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3827:     my $upload=&mt("Upload Scores");
 3828:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3829:     my $ignore=&mt('Ignore First Line');
 3830:     $symb = &Apache::lonenc::check_encrypt($symb);
 3831:     $result.=<<ENDUPFORM;
 3832: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3833: <input type="hidden" name="symb" value="$symb" />
 3834: <input type="hidden" name="command" value="csvuploadmap" />
 3835: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3836: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3837: $upfile_select
 3838: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3839: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3840: </form>
 3841: ENDUPFORM
 3842:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3843:                            &mt("How do I create a CSV file from a spreadsheet"))
 3844:     .'</td></tr></table>'."\n";
 3845:     $result.='</td></tr></table><br /><br />'."\n";
 3846:     $result.=&show_grading_menu_form($symb);
 3847:     return $result;
 3848: }
 3849: 
 3850: 
 3851: sub csvuploadmap {
 3852:     my ($request)= @_;
 3853:     my ($symb)=&get_symb($request);
 3854:     if (!$symb) {return '';}
 3855: 
 3856:     my $datatoken;
 3857:     if (!$env{'form.datatoken'}) {
 3858: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3859:     } else {
 3860: 	$datatoken=$env{'form.datatoken'};
 3861: 	&Apache::loncommon::load_tmp_file($request);
 3862:     }
 3863:     my @records=&Apache::loncommon::upfile_record_sep();
 3864:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3865:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3866:     my ($i,$keyfields);
 3867:     if (@records) {
 3868: 	my @fields=&csvupload_fields($symb);
 3869: 
 3870: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3871: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3872: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3873: 							  \@fields);
 3874: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3875: 	    chop($keyfields);
 3876: 	} else {
 3877: 	    unshift(@fields,['none','']);
 3878: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3879: 							    \@fields);
 3880:             foreach my $rec (@records) {
 3881:                 my %temp = &Apache::loncommon::record_sep($rec);
 3882:                 if (%temp) {
 3883:                     $keyfields=join(',',sort(keys(%temp)));
 3884:                     last;
 3885:                 }
 3886:             }
 3887: 	}
 3888:     }
 3889:     &csvuploadmap_footer($request,$i,$keyfields);
 3890:     $request->print(&show_grading_menu_form($symb));
 3891: 
 3892:     return '';
 3893: }
 3894: 
 3895: sub csvuploadoptions {
 3896:     my ($request)= @_;
 3897:     my ($symb)=&get_symb($request);
 3898:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3899:     my $ignore=&mt('Ignore First Line');
 3900:     $request->print(<<ENDPICK);
 3901: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3902: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3903: <input type="hidden" name="command"    value="csvuploadassign" />
 3904: <!--
 3905: <p>
 3906: <label>
 3907:    <input type="checkbox" name="show_full_results" />
 3908:    Show a table of all changes
 3909: </label>
 3910: </p>
 3911: -->
 3912: <p>
 3913: <label>
 3914:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3915:    Overwrite any existing score
 3916: </label>
 3917: </p>
 3918: ENDPICK
 3919:     my %fields=&get_fields();
 3920:     if (!defined($fields{'domain'})) {
 3921: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3922: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3923:     }
 3924:     foreach my $key (sort(keys(%env))) {
 3925: 	if ($key !~ /^form\.(.*)$/) { next; }
 3926: 	my $cleankey=$1;
 3927: 	if ($cleankey eq 'command') { next; }
 3928: 	$request->print('<input type="hidden" name="'.$cleankey.
 3929: 			'"  value="'.$env{$key}.'" />'."\n");
 3930:     }
 3931:     # FIXME do a check for any duplicated user ids...
 3932:     # FIXME do a check for any invalid user ids?...
 3933:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3934: <hr /></form>'."\n");
 3935:     $request->print(&show_grading_menu_form($symb));
 3936:     return '';
 3937: }
 3938: 
 3939: sub get_fields {
 3940:     my %fields;
 3941:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3942:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3943: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3944: 	    if ($env{'form.f'.$i} ne 'none') {
 3945: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3946: 	    }
 3947: 	} else {
 3948: 	    if ($env{'form.f'.$i} ne 'none') {
 3949: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3950: 	    }
 3951: 	}
 3952:     }
 3953:     return %fields;
 3954: }
 3955: 
 3956: sub csvuploadassign {
 3957:     my ($request)= @_;
 3958:     my ($symb)=&get_symb($request);
 3959:     if (!$symb) {return '';}
 3960:     my $error_msg = '';
 3961:     &Apache::loncommon::load_tmp_file($request);
 3962:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3963:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3964:     my %fields=&get_fields();
 3965:     $request->print('<h3>Assigning Grades</h3>');
 3966:     my $courseid=$env{'request.course.id'};
 3967:     my ($classlist) = &getclasslist('all',0);
 3968:     my @notallowed;
 3969:     my @skipped;
 3970:     my $countdone=0;
 3971:     foreach my $grade (@gradedata) {
 3972: 	my %entries=&Apache::loncommon::record_sep($grade);
 3973: 	my $domain;
 3974: 	if ($entries{$fields{'domain'}}) {
 3975: 	    $domain=$entries{$fields{'domain'}};
 3976: 	} else {
 3977: 	    $domain=$env{'form.default_domain'};
 3978: 	}
 3979: 	$domain=~s/\s//g;
 3980: 	my $username=$entries{$fields{'username'}};
 3981: 	$username=~s/\s//g;
 3982: 	if (!$username) {
 3983: 	    my $id=$entries{$fields{'ID'}};
 3984: 	    $id=~s/\s//g;
 3985: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3986: 	    $username=$ids{$id};
 3987: 	}
 3988: 	if (!exists($$classlist{"$username:$domain"})) {
 3989: 	    my $id=$entries{$fields{'ID'}};
 3990: 	    $id=~s/\s//g;
 3991: 	    if ($id) {
 3992: 		push(@skipped,"$id:$domain");
 3993: 	    } else {
 3994: 		push(@skipped,"$username:$domain");
 3995: 	    }
 3996: 	    next;
 3997: 	}
 3998: 	my $usec=$classlist->{"$username:$domain"}[5];
 3999: 	if (!&canmodify($usec)) {
 4000: 	    push(@notallowed,"$username:$domain");
 4001: 	    next;
 4002: 	}
 4003: 	my %points;
 4004: 	my %grades;
 4005: 	foreach my $dest (keys(%fields)) {
 4006: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4007: 		$dest eq 'domain') { next; }
 4008: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4009: 	    if ($dest=~/stores_(.*)_points/) {
 4010: 		my $part=$1;
 4011: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4012: 					      $symb,$domain,$username);
 4013:                 if ($wgt) {
 4014:                     $entries{$fields{$dest}}=~s/\s//g;
 4015:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4016:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4017:                                           : 'correct_by_override';
 4018:                     $grades{"resource.$part.awarded"}=$pcr;
 4019:                     $grades{"resource.$part.solved"}=$award;
 4020:                     $points{$part}=1;
 4021:                 } else {
 4022:                     $error_msg = "<br />" .
 4023:                         &mt("Some point values were assigned"
 4024:                             ." for problems with a weight "
 4025:                             ."of zero. These values were "
 4026:                             ."ignored.");
 4027:                 }
 4028: 	    } else {
 4029: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4030: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4031: 		my $store_key=$dest;
 4032: 		$store_key=~s/^stores/resource/;
 4033: 		$store_key=~s/_/\./g;
 4034: 		$grades{$store_key}=$entries{$fields{$dest}};
 4035: 	    }
 4036: 	}
 4037: 	if (! %grades) { 
 4038:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4039:         } else {
 4040: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4041: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4042: 					   $env{'request.course.id'},
 4043: 					   $domain,$username);
 4044: 	   if ($result eq 'ok') {
 4045: 	      $request->print('.');
 4046: 	   } else {
 4047: 	      $request->print("<p><span class=\"LC_error\">".
 4048:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4049:                                   "$username:$domain",$result)."</span></p>");
 4050: 	   }
 4051: 	   $request->rflush();
 4052: 	   $countdone++;
 4053:         }
 4054:     }
 4055:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4056:     if (@skipped) {
 4057: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4058: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4059:     }
 4060:     if (@notallowed) {
 4061: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4062: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4063:     }
 4064:     $request->print("<br />\n");
 4065:     $request->print(&show_grading_menu_form($symb));
 4066:     return $error_msg;
 4067: }
 4068: #------------- end of section for handling csv file upload ---------
 4069: #
 4070: #-------------------------------------------------------------------
 4071: #
 4072: #-------------- Next few routines handle grading by page/sequence
 4073: #
 4074: #--- Select a page/sequence and a student to grade
 4075: sub pickStudentPage {
 4076:     my ($request) = shift;
 4077: 
 4078:     $request->print(<<LISTJAVASCRIPT);
 4079: <script type="text/javascript" language="javascript">
 4080: 
 4081: function checkPickOne(formname) {
 4082:     if (radioSelection(formname.student) == null) {
 4083: 	alert("Please select the student you wish to grade.");
 4084: 	return;
 4085:     }
 4086:     ptr = pullDownSelection(formname.selectpage);
 4087:     formname.page.value = formname["page"+ptr].value;
 4088:     formname.title.value = formname["title"+ptr].value;
 4089:     formname.submit();
 4090: }
 4091: 
 4092: </script>
 4093: LISTJAVASCRIPT
 4094:     &commonJSfunctions($request);
 4095:     my ($symb) = &get_symb($request);
 4096:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4097:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4098:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4099: 
 4100:     my $result='<h3><span class="LC_info">&nbsp;'.
 4101: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4102: 
 4103:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4104:     my ($titles,$symbx) = &getSymbMap();
 4105:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4106: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4107: #    my $type=($curpage =~ /\.(page|sequence)/);
 4108:     my $select = '<select name="selectpage">'."\n";
 4109:     my $ctr=0;
 4110:     foreach (@$titles) {
 4111: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4112: 	$select.='<option value="'.$ctr.'" '.
 4113: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4114: 	    '>'.$showtitle.'</option>'."\n";
 4115: 	$ctr++;
 4116:     }
 4117:     $select.= '</select>';
 4118:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4119: 
 4120:     $ctr=0;
 4121:     foreach (@$titles) {
 4122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4123: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4124: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4125: 	$ctr++;
 4126:     }
 4127:     $result.='<input type="hidden" name="page" />'."\n".
 4128: 	'<input type="hidden" name="title" />'."\n";
 4129: 
 4130:     my $options =
 4131: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4132: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4133:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4134: 
 4135:     $options =
 4136: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4137: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4138: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4139:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4140:     
 4141:     $result.=&build_section_inputs();
 4142:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4143:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4144: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4145: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4146: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4147: 
 4148:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4149: 			  '<input type="text" name="CODE" value="" />').
 4150: 			      '<br />'."\n";
 4151: 
 4152:     $result.='&nbsp;<input type="button" '.
 4153: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4154: 
 4155:     $request->print($result);
 4156: 
 4157:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4158: 	&Apache::loncommon::start_data_table().
 4159: 	&Apache::loncommon::start_data_table_header_row().
 4160: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4161: 	'<th>'.&nameUserString('header').'</th>'.
 4162: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4163: 	'<th>'.&nameUserString('header').'</th>'.
 4164: 	&Apache::loncommon::end_data_table_header_row();
 4165:  
 4166:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4167:     my $ptr = 1;
 4168:     foreach my $student (sort 
 4169: 			 {
 4170: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4171: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4172: 			     }
 4173: 			     return $a cmp $b;
 4174: 			 } (keys(%$fullname))) {
 4175: 	my ($uname,$udom) = split(/:/,$student);
 4176: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4177:                                   : '</td>');
 4178: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4179: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4180: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4181: 	$studentTable.=
 4182: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4183:                          : '');
 4184: 	$ptr++;
 4185:     }
 4186:     if ($ptr%2 == 0) {
 4187: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4188: 	    &Apache::loncommon::end_data_table_row();
 4189:     }
 4190:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4191:     $studentTable.='<input type="button" '.
 4192: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4193: 
 4194:     $studentTable.=&show_grading_menu_form($symb);
 4195:     $request->print($studentTable);
 4196: 
 4197:     return '';
 4198: }
 4199: 
 4200: sub getSymbMap {
 4201:     my $navmap = Apache::lonnavmaps::navmap->new();
 4202: 
 4203:     my %symbx = ();
 4204:     my @titles = ();
 4205:     my $minder = 0;
 4206: 
 4207:     # Gather every sequence that has problems.
 4208:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4209: 					       1,0,1);
 4210:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4211: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4212: 	    my $title = $minder.'.'.
 4213: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4214: 	    push(@titles, $title); # minder in case two titles are identical
 4215: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4216: 	    $minder++;
 4217: 	}
 4218:     }
 4219:     return \@titles,\%symbx;
 4220: }
 4221: 
 4222: #
 4223: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4224: sub displayPage {
 4225:     my ($request) = shift;
 4226: 
 4227:     my ($symb) = &get_symb($request);
 4228:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4229:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4230:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4231:     my $pageTitle = $env{'form.page'};
 4232:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4233:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4234:     my $usec=$classlist->{$env{'form.student'}}[5];
 4235: 
 4236:     #need to make sure we have the correct data for later EXT calls, 
 4237:     #thus invalidate the cache
 4238:     &Apache::lonnet::devalidatecourseresdata(
 4239:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4240:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4241:     &Apache::lonnet::clear_EXT_cache_status();
 4242: 
 4243:     if (!&canview($usec)) {
 4244: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4245: 	$request->print(&show_grading_menu_form($symb));
 4246: 	return;
 4247:     }
 4248:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4249:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4250: 	'</h3>'."\n";
 4251:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4252:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4253: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4254:     } else {
 4255: 	delete($env{'form.CODE'});
 4256:     }
 4257:     &sub_page_js($request);
 4258:     $request->print($result);
 4259: 
 4260:     my $navmap = Apache::lonnavmaps::navmap->new();
 4261:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4262:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4263:     if (!$map) {
 4264: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4265: 	$request->print(&show_grading_menu_form($symb));
 4266: 	return; 
 4267:     }
 4268:     my $iterator = $navmap->getIterator($map->map_start(),
 4269: 					$map->map_finish());
 4270: 
 4271:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4272: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4273: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4274: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4275: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4276: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4277: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4278: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4279: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4280: 
 4281:     if (defined($env{'form.CODE'})) {
 4282: 	$studentTable.=
 4283: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4284:     }
 4285:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4286: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4287: 
 4288:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4289: 	&Apache::loncommon::start_data_table().
 4290: 	&Apache::loncommon::start_data_table_header_row().
 4291: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4292: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4293: 	&Apache::loncommon::end_data_table_header_row();
 4294: 
 4295:     &Apache::lonxml::clear_problem_counter();
 4296:     my ($depth,$question,$prob) = (1,1,1);
 4297:     $iterator->next(); # skip the first BEGIN_MAP
 4298:     my $curRes = $iterator->next(); # for "current resource"
 4299:     while ($depth > 0) {
 4300:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4301:         if($curRes == $iterator->END_MAP) { $depth--; }
 4302: 
 4303:         if (ref($curRes) && $curRes->is_problem()) {
 4304: 	    my $parts = $curRes->parts();
 4305:             my $title = $curRes->compTitle();
 4306: 	    my $symbx = $curRes->symb();
 4307: 	    $studentTable.=
 4308: 		&Apache::loncommon::start_data_table_row().
 4309: 		'<td align="center" valign="top" >'.$prob.
 4310: 		(scalar(@{$parts}) == 1 ? '' 
 4311: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4312: 							scalar(@{$parts}))
 4313: 		 ).
 4314: 		 '</td>';
 4315: 	    $studentTable.='<td valign="top">';
 4316: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4317: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4318: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4319: 					     undef,'both',\%form);
 4320: 	    } else {
 4321: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4322: 		$companswer =~ s|<form(.*?)>||g;
 4323: 		$companswer =~ s|</form>||g;
 4324: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4325: #		    $companswer =~ s/$1/ /ms;
 4326: #		    $request->print('match='.$1."<br />\n");
 4327: #		}
 4328: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4329: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4330: 	    }
 4331: 
 4332: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4333: 
 4334: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4335: 		if ($record{'version'} eq '') {
 4336: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4337: 		} else {
 4338: 		    my %responseType = ();
 4339: 		    foreach my $partid (@{$parts}) {
 4340: 			my @responseIds =$curRes->responseIds($partid);
 4341: 			my @responseType =$curRes->responseType($partid);
 4342: 			my %responseIds;
 4343: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4344: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4345: 			}
 4346: 			$responseType{$partid} = \%responseIds;
 4347: 		    }
 4348: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4349: 
 4350: 		}
 4351: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4352: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4353: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4354: 									$env{'request.course.id'},
 4355: 									'','.submission');
 4356:  
 4357: 	    }
 4358: 	    if (&canmodify($usec)) {
 4359: 		foreach my $partid (@{$parts}) {
 4360: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4361: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4362: 		    $question++;
 4363: 		}
 4364: 		$prob++;
 4365: 	    }
 4366: 	    $studentTable.='</td></tr>';
 4367: 
 4368: 	}
 4369:         $curRes = $iterator->next();
 4370:     }
 4371: 
 4372:     $studentTable.='</table>'."\n".
 4373: 	'<input type="button" value="'.&mt('Save').'" '.
 4374: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4375: 	'</form>'."\n";
 4376:     $studentTable.=&show_grading_menu_form($symb);
 4377:     $request->print($studentTable);
 4378: 
 4379:     return '';
 4380: }
 4381: 
 4382: sub displaySubByDates {
 4383:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4384:     my $isCODE=0;
 4385:     my $isTask = ($symb =~/\.task$/);
 4386:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4387:     my $studentTable=&Apache::loncommon::start_data_table().
 4388: 	&Apache::loncommon::start_data_table_header_row().
 4389: 	'<th>'.&mt('Date/Time').'</th>'.
 4390: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4391: 	'<th>'.&mt('Submission').'</th>'.
 4392: 	'<th>'.&mt('Status').'</th>'.
 4393: 	&Apache::loncommon::end_data_table_header_row();
 4394:     my ($version);
 4395:     my %mark;
 4396:     my %orders;
 4397:     $mark{'correct_by_student'} = $checkIcon;
 4398:     if (!exists($$record{'1:timestamp'})) {
 4399: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4400:     }
 4401: 
 4402:     my $interaction;
 4403:     for ($version=1;$version<=$$record{'version'};$version++) {
 4404: 	my $timestamp = 
 4405: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4406: 	if (exists($$record{$version.':resource.0.version'})) {
 4407: 	    $interaction = $$record{$version.':resource.0.version'};
 4408: 	}
 4409: 
 4410: 	my $where = ($isTask ? "$version:resource.$interaction"
 4411: 		             : "$version:resource");
 4412: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4413: 	    '<td>'.$timestamp.'</td>';
 4414: 	if ($isCODE) {
 4415: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4416: 	}
 4417: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4418: 	my @displaySub = ();
 4419: 	foreach my $partid (@{$parts}) {
 4420: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4421: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4422: 	    
 4423: 
 4424: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4425: 	    my $display_part=&get_display_part($partid,$symb);
 4426: 	    foreach my $matchKey (@matchKey) {
 4427: 		if (exists($$record{$version.':'.$matchKey}) &&
 4428: 		    $$record{$version.':'.$matchKey} ne '') {
 4429: 
 4430: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4431: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4432: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4433: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4434: 			$responseId.')</span>&nbsp;<b>';
 4435: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4436: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4437: 		    } else {
 4438: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4439: 					    $$record{"$where.$partid.tries"});
 4440: 		    }
 4441: 		    my $responseType=($isTask ? 'Task'
 4442:                                               : $responseType->{$partid}->{$responseId});
 4443: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4444: 		    if (!exists($orders{$partid}->{$responseId})) {
 4445: 			$orders{$partid}->{$responseId}=
 4446: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4447: 		    }
 4448: 		    $displaySub[0].='</b>&nbsp; '.
 4449: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4450: 		}
 4451: 	    }
 4452: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4453: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4454: 				    $$record{"$where.$partid.checkedin"},
 4455: 				    $$record{"$where.$partid.checkedin.slot"}).
 4456: 					'<br />';
 4457: 	    }
 4458: 	    if (exists $$record{"$where.$partid.award"}) {
 4459: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4460: 		    lc($$record{"$where.$partid.award"}).' '.
 4461: 		    $mark{$$record{"$where.$partid.solved"}}.
 4462: 		    '<br />';
 4463: 	    }
 4464: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4465: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4466: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4467: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4468: 		$displaySub[2].=
 4469: 		    $$record{"$version:resource.$partid.regrader"}.
 4470: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4471: 	    }
 4472: 	}
 4473: 	# needed because old essay regrader has not parts info
 4474: 	if (exists $$record{"$version:resource.regrader"}) {
 4475: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4476: 	}
 4477: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4478: 	if ($displaySub[2]) {
 4479: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4480: 	}
 4481: 	$studentTable.='&nbsp;</td>'.
 4482: 	    &Apache::loncommon::end_data_table_row();
 4483:     }
 4484:     $studentTable.=&Apache::loncommon::end_data_table();
 4485:     return $studentTable;
 4486: }
 4487: 
 4488: sub updateGradeByPage {
 4489:     my ($request) = shift;
 4490: 
 4491:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4492:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4493:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4494:     my $pageTitle = $env{'form.page'};
 4495:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4496:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4497:     my $usec=$classlist->{$env{'form.student'}}[5];
 4498:     if (!&canmodify($usec)) {
 4499: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4500: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4501: 	return;
 4502:     }
 4503:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4504:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4505: 	'</h3>'."\n";
 4506: 
 4507:     $request->print($result);
 4508: 
 4509:     my $navmap = Apache::lonnavmaps::navmap->new();
 4510:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4511:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4512:     if (!$map) {
 4513: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4514: 	my ($symb)=&get_symb($request);
 4515: 	$request->print(&show_grading_menu_form($symb));
 4516: 	return; 
 4517:     }
 4518:     my $iterator = $navmap->getIterator($map->map_start(),
 4519: 					$map->map_finish());
 4520: 
 4521:     my $studentTable=
 4522: 	&Apache::loncommon::start_data_table().
 4523: 	&Apache::loncommon::start_data_table_header_row().
 4524: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4525: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4526: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4527: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4528: 	&Apache::loncommon::end_data_table_header_row();
 4529: 
 4530:     $iterator->next(); # skip the first BEGIN_MAP
 4531:     my $curRes = $iterator->next(); # for "current resource"
 4532:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4533:     while ($depth > 0) {
 4534:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4535:         if($curRes == $iterator->END_MAP) { $depth--; }
 4536: 
 4537:         if (ref($curRes) && $curRes->is_problem()) {
 4538: 	    my $parts = $curRes->parts();
 4539:             my $title = $curRes->compTitle();
 4540: 	    my $symbx = $curRes->symb();
 4541: 	    $studentTable.=
 4542: 		&Apache::loncommon::start_data_table_row().
 4543: 		'<td align="center" valign="top" >'.$prob.
 4544: 		(scalar(@{$parts}) == 1 ? '' 
 4545:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
 4546: 		 ).')</td>';
 4547: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4548: 
 4549: 	    my %newrecord=();
 4550: 	    my @displayPts=();
 4551:             my %aggregate = ();
 4552:             my $aggregateflag = 0;
 4553: 	    foreach my $partid (@{$parts}) {
 4554: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4555: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4556: 
 4557: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4558: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4559: 		my $partial = $newpts/$wgt;
 4560: 		my $score;
 4561: 		if ($partial > 0) {
 4562: 		    $score = 'correct_by_override';
 4563: 		} elsif ($newpts ne '') { #empty is taken as 0
 4564: 		    $score = 'incorrect_by_override';
 4565: 		}
 4566: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4567: 		if ($dropMenu eq 'excused') {
 4568: 		    $partial = '';
 4569: 		    $score = 'excused';
 4570: 		} elsif ($dropMenu eq 'reset status'
 4571: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4572: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4573: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4574: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4575: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4576: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4577: 		    $changeflag++;
 4578: 		    $newpts = '';
 4579:                     
 4580:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4581:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4582:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4583:                     if ($aggtries > 0) {
 4584:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4585:                         $aggregateflag = 1;
 4586:                     }
 4587: 		}
 4588: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4589: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4590: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4591: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4592: 		    '&nbsp;<br />';
 4593: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4594: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4595: 		    '&nbsp;<br />';
 4596: 		$question++;
 4597: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4598: 
 4599: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4600: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4601: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4602: 		    if (scalar(keys(%newrecord)) > 0);
 4603: 
 4604: 		$changeflag++;
 4605: 	    }
 4606: 	    if (scalar(keys(%newrecord)) > 0) {
 4607: 		my %record = 
 4608: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4609: 					     $udom,$uname);
 4610: 
 4611: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4612: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4613: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4614: 		    $newrecord{'resource.CODE'} = '';
 4615: 		}
 4616: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4617: 					$udom,$uname);
 4618: 		%record = &Apache::lonnet::restore($symbx,
 4619: 						   $env{'request.course.id'},
 4620: 						   $udom,$uname);
 4621: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4622: 					     $cdom,$cnum,$udom,$uname);
 4623: 	    }
 4624: 	    
 4625:             if ($aggregateflag) {
 4626:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4627:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4628:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4629:             }
 4630: 
 4631: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4632: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4633: 		&Apache::loncommon::end_data_table_row();
 4634: 
 4635: 	    $prob++;
 4636: 	}
 4637:         $curRes = $iterator->next();
 4638:     }
 4639: 
 4640:     $studentTable.=&Apache::loncommon::end_data_table();
 4641:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4642:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4643: 		  'The scores were changed for '.
 4644: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4645:     $request->print($grademsg.$studentTable);
 4646: 
 4647:     return '';
 4648: }
 4649: 
 4650: #-------- end of section for handling grading by page/sequence ---------
 4651: #
 4652: #-------------------------------------------------------------------
 4653: 
 4654: #--------------------Scantron Grading-----------------------------------
 4655: #
 4656: #------ start of section for handling grading by page/sequence ---------
 4657: 
 4658: =pod
 4659: 
 4660: =head1 Bubble sheet grading routines
 4661: 
 4662:   For this documentation:
 4663: 
 4664:    'scanline' refers to the full line of characters
 4665:    from the file that we are parsing that represents one entire sheet
 4666: 
 4667:    'bubble line' refers to the data
 4668:    representing the line of bubbles that are on the physical bubble sheet
 4669: 
 4670: 
 4671: The overall process is that a scanned in bubble sheet data is uploaded
 4672: into a course. When a user wants to grade, they select a
 4673: sequence/folder of resources, a file of bubble sheet info, and pick
 4674: one of the predefined configurations for what each scanline looks
 4675: like.
 4676: 
 4677: Next each scanline is checked for any errors of either 'missing
 4678: bubbles' (it's an error because it may have been mis-scanned
 4679: because too light bubbling), 'double bubble' (each bubble line should
 4680: have no more that one letter picked), invalid or duplicated CODE,
 4681: invalid student ID
 4682: 
 4683: If the CODE option is used that determines the randomization of the
 4684: homework problems, either way the student ID is looked up into a
 4685: username:domain.
 4686: 
 4687: During the validation phase the instructor can choose to skip scanlines. 
 4688: 
 4689: After the validation phase, there are now 3 bubble sheet files
 4690: 
 4691:   scantron_original_filename (unmodified original file)
 4692:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4693:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4694: 
 4695: Also there is a separate hash nohist_scantrondata that contains extra
 4696: correction information that isn't representable in the bubble sheet
 4697: file (see &scantron_getfile() for more information)
 4698: 
 4699: After all scanlines are either valid, marked as valid or skipped, then
 4700: foreach line foreach problem in the picked sequence, an ssi request is
 4701: made that simulates a user submitting their selected letter(s) against
 4702: the homework problem.
 4703: 
 4704: =over 4
 4705: 
 4706: 
 4707: 
 4708: =item defaultFormData
 4709: 
 4710:   Returns html hidden inputs used to hold context/default values.
 4711: 
 4712:  Arguments:
 4713:   $symb - $symb of the current resource 
 4714: 
 4715: =cut
 4716: 
 4717: sub defaultFormData {
 4718:     my ($symb)=@_;
 4719:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4720:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4721:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4722: }
 4723: 
 4724: 
 4725: =pod 
 4726: 
 4727: =item getSequenceDropDown
 4728: 
 4729:    Return html dropdown of possible sequences to grade
 4730:  
 4731:  Arguments:
 4732:    $symb - $symb of the current resource 
 4733: 
 4734: =cut
 4735: 
 4736: sub getSequenceDropDown {
 4737:     my ($symb)=@_;
 4738:     my $result='<select name="selectpage">'."\n";
 4739:     my ($titles,$symbx) = &getSymbMap();
 4740:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4741:     my $ctr=0;
 4742:     foreach (@$titles) {
 4743: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4744: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4745: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4746: 	    '>'.$showtitle.'</option>'."\n";
 4747: 	$ctr++;
 4748:     }
 4749:     $result.= '</select>';
 4750:     return $result;
 4751: }
 4752: 
 4753: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4754:                                    # index is "symb.part_id"
 4755: 
 4756: my %first_bubble_line;             # First bubble line no. for each bubble.
 4757: 
 4758: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4759:                                    # matchresponse or rankresponse, where 
 4760:                                    # an individual response can have multiple 
 4761:                                    # lines
 4762: 
 4763: my %responsetype_per_response;     # responsetype for each response
 4764: 
 4765: # Save and restore the bubble lines array to the form env.
 4766: 
 4767: 
 4768: sub save_bubble_lines {
 4769:     foreach my $line (keys(%bubble_lines_per_response)) {
 4770: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4771: 	$env{"form.scantron.first_bubble_line.$line"} =
 4772: 	    $first_bubble_line{$line};
 4773:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4774:             $subdivided_bubble_lines{$line};
 4775:         $env{"form.scantron.responsetype.$line"} =
 4776:             $responsetype_per_response{$line};
 4777:     }
 4778: }
 4779: 
 4780: 
 4781: sub restore_bubble_lines {
 4782:     my $line = 0;
 4783:     %bubble_lines_per_response = ();
 4784:     while ($env{"form.scantron.bubblelines.$line"}) {
 4785: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4786: 	$bubble_lines_per_response{$line} = $value;
 4787: 	$first_bubble_line{$line}  =
 4788: 	    $env{"form.scantron.first_bubble_line.$line"};
 4789:         $subdivided_bubble_lines{$line} =
 4790:             $env{"form.scantron.sub_bubblelines.$line"};
 4791:         $responsetype_per_response{$line} =
 4792:             $env{"form.scantron.responsetype.$line"};
 4793: 	$line++;
 4794:     }
 4795: 
 4796: }
 4797: 
 4798: #  Given the parsed scanline, get the response for 
 4799: #  'answer' number n:
 4800: 
 4801: sub get_response_bubbles {
 4802:     my ($parsed_line, $response)  = @_;
 4803: 
 4804: 
 4805:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4806:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4807:     
 4808:     my $selected = "";
 4809: 
 4810:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4811: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4812: 	$bubble_line++;
 4813:     }
 4814:     return $selected;
 4815: }
 4816: 
 4817: =pod 
 4818: 
 4819: =item scantron_filenames
 4820: 
 4821:    Returns a list of the scantron files in the current course 
 4822: 
 4823: =cut
 4824: 
 4825: sub scantron_filenames {
 4826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4827:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4828:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4829: 				    &propath($cdom,$cname));
 4830:     my @possiblenames;
 4831:     foreach my $filename (sort(@files)) {
 4832: 	($filename)=split(/&/,$filename);
 4833: 	if ($filename!~/^scantron_orig_/) { next ; }
 4834: 	$filename=~s/^scantron_orig_//;
 4835: 	push(@possiblenames,$filename);
 4836:     }
 4837:     return @possiblenames;
 4838: }
 4839: 
 4840: =pod 
 4841: 
 4842: =item scantron_uploads
 4843: 
 4844:    Returns  html drop-down list of scantron files in current course.
 4845: 
 4846:  Arguments:
 4847:    $file2grade - filename to set as selected in the dropdown
 4848: 
 4849: =cut
 4850: 
 4851: sub scantron_uploads {
 4852:     my ($file2grade) = @_;
 4853:     my $result=	'<select name="scantron_selectfile">';
 4854:     $result.="<option></option>";
 4855:     foreach my $filename (sort(&scantron_filenames())) {
 4856: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4857:     }
 4858:     $result.="</select>";
 4859:     return $result;
 4860: }
 4861: 
 4862: =pod 
 4863: 
 4864: =item scantron_scantab
 4865: 
 4866:   Returns html drop down of the scantron formats in the scantronformat.tab
 4867:   file.
 4868: 
 4869: =cut
 4870: 
 4871: sub scantron_scantab {
 4872:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4873:     my $result='<select name="scantron_format">'."\n";
 4874:     $result.='<option></option>'."\n";
 4875:     foreach my $line (<$fh>) {
 4876: 	my ($name,$descrip)=split(/:/,$line);
 4877: 	if ($name =~ /^\#/) { next; }
 4878: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4879:     }
 4880:     $result.='</select>'."\n";
 4881: 
 4882:     return $result;
 4883: }
 4884: 
 4885: =pod 
 4886: 
 4887: =item scantron_CODElist
 4888: 
 4889:   Returns html drop down of the saved CODE lists from current course,
 4890:   generated from earlier printings.
 4891: 
 4892: =cut
 4893: 
 4894: sub scantron_CODElist {
 4895:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4896:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4897:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4898:     my $namechoice='<option></option>';
 4899:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4900: 	if ($name =~ /^error: 2 /) { next; }
 4901: 	if ($name =~ /^type\0/) { next; }
 4902: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4903:     }
 4904:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4905:     return $namechoice;
 4906: }
 4907: 
 4908: =pod 
 4909: 
 4910: =item scantron_CODEunique
 4911: 
 4912:   Returns the html for "Each CODE to be used once" radio.
 4913: 
 4914: =cut
 4915: 
 4916: sub scantron_CODEunique {
 4917:     my $result='<span style="white-space: nowrap;">
 4918:                  <label><input type="radio" name="scantron_CODEunique"
 4919:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4920:                 </span>
 4921:                 <span style="white-space: nowrap;">
 4922:                  <label><input type="radio" name="scantron_CODEunique"
 4923:                         value="no" />'.&mt('No').' </label>
 4924:                 </span>';
 4925:     return $result;
 4926: }
 4927: 
 4928: =pod 
 4929: 
 4930: =item scantron_selectphase
 4931: 
 4932:   Generates the initial screen to start the bubble sheet process.
 4933:   Allows for - starting a grading run.
 4934:              - downloading existing scan data (original, corrected
 4935:                                                 or skipped info)
 4936: 
 4937:              - uploading new scan data
 4938: 
 4939:  Arguments:
 4940:   $r          - The Apache request object
 4941:   $file2grade - name of the file that contain the scanned data to score
 4942: 
 4943: =cut
 4944: 
 4945: sub scantron_selectphase {
 4946:     my ($r,$file2grade) = @_;
 4947:     my ($symb)=&get_symb($r);
 4948:     if (!$symb) {return '';}
 4949:     my $sequence_selector=&getSequenceDropDown($symb);
 4950:     my $default_form_data=&defaultFormData($symb);
 4951:     my $grading_menu_button=&show_grading_menu_form($symb);
 4952:     my $file_selector=&scantron_uploads($file2grade);
 4953:     my $format_selector=&scantron_scantab();
 4954:     my $CODE_selector=&scantron_CODElist();
 4955:     my $CODE_unique=&scantron_CODEunique();
 4956:     my $result;
 4957: 
 4958:     $ssi_error = 0;
 4959: 
 4960:     # Chunk of form to prompt for a file to grade and how:
 4961: 
 4962:     $result.= '
 4963:     <br />
 4964:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4965:     <input type="hidden" name="command" value="scantron_warning" />
 4966:     '.$default_form_data.'
 4967:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 4968:        '.&Apache::loncommon::start_data_table_header_row().'
 4969:             <th colspan="2">
 4970:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 4971:             </th>
 4972:        '.&Apache::loncommon::end_data_table_header_row().'
 4973:        '.&Apache::loncommon::start_data_table_row().'
 4974:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 4975:        '.&Apache::loncommon::end_data_table_row().'
 4976:        '.&Apache::loncommon::start_data_table_row().'
 4977:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 4978:        '.&Apache::loncommon::end_data_table_row().'
 4979:        '.&Apache::loncommon::start_data_table_row().'
 4980:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 4981:        '.&Apache::loncommon::end_data_table_row().'
 4982:        '.&Apache::loncommon::start_data_table_row().'
 4983:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 4984:        '.&Apache::loncommon::end_data_table_row().'
 4985:        '.&Apache::loncommon::start_data_table_row().'
 4986:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 4987:        '.&Apache::loncommon::end_data_table_row().'
 4988:        '.&Apache::loncommon::start_data_table_row().'
 4989: 	    <td> '.&mt('Options:').' </td>
 4990:             <td>
 4991: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 4992:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 4993:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 4994: 	    </td>
 4995:        '.&Apache::loncommon::end_data_table_row().'
 4996:        '.&Apache::loncommon::start_data_table_row().'
 4997:             <td colspan="2">
 4998:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 4999:             </td>
 5000:        '.&Apache::loncommon::end_data_table_row().'
 5001:     '.&Apache::loncommon::end_data_table().'
 5002:     </form>
 5003: ';
 5004:    
 5005:     $r->print($result);
 5006: 
 5007:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5008:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5009: 
 5010: 	# Chunk of form to prompt for a scantron file upload.
 5011: 
 5012:         $r->print('
 5013:     <br />
 5014:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5015:        '.&Apache::loncommon::start_data_table_header_row().'
 5016:             <th>
 5017:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5018:             </th>
 5019:        '.&Apache::loncommon::end_data_table_header_row().'
 5020:        '.&Apache::loncommon::start_data_table_row().'
 5021:             <td>
 5022: ');
 5023:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5024:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5025:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5026:     $r->print('
 5027:               <script type="text/javascript" language="javascript">
 5028:     function checkUpload(formname) {
 5029: 	if (formname.upfile.value == "") {
 5030: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5031: 	    return false;
 5032: 	}
 5033: 	formname.submit();
 5034:     }
 5035:               </script>
 5036: 
 5037:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5038:                 '.$default_form_data.'
 5039:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5040:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5041:                 <input name="command" value="scantronupload_save" type="hidden" />
 5042:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5043:                 <br />
 5044:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5045:               </form>
 5046: ');
 5047: 
 5048:         $r->print('
 5049:             </td>
 5050:        '.&Apache::loncommon::end_data_table_row().'
 5051:        '.&Apache::loncommon::end_data_table().'
 5052: ');
 5053:     }
 5054: 
 5055:     # Chunk of the form that prompts to view a scoring office file,
 5056:     # corrected file, skipped records in a file.
 5057: 
 5058:     $r->print('
 5059:    <br />
 5060:    <form action="/adm/grades" name="scantron_download">
 5061:      '.$default_form_data.'
 5062:      <input type="hidden" name="command" value="scantron_download" />
 5063:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5064:        '.&Apache::loncommon::start_data_table_header_row().'
 5065:               <th>
 5066:                 &nbsp;'.&mt('Download a scoring office file').'
 5067:               </th>
 5068:        '.&Apache::loncommon::end_data_table_header_row().'
 5069:        '.&Apache::loncommon::start_data_table_row().'
 5070:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5071:                 <br />
 5072:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5073:        '.&Apache::loncommon::end_data_table_row().'
 5074:      '.&Apache::loncommon::end_data_table().'
 5075:    </form>
 5076:    <br />
 5077: ');
 5078: 
 5079:     &Apache::lonpickcode::code_list($r,2);
 5080:     $r->print($grading_menu_button);
 5081:     return
 5082: }
 5083: 
 5084: =pod
 5085: 
 5086: =item get_scantron_config
 5087: 
 5088:    Parse and return the scantron configuration line selected as a
 5089:    hash of configuration file fields.
 5090: 
 5091:  Arguments:
 5092:     which - the name of the configuration to parse from the file.
 5093: 
 5094: 
 5095:  Returns:
 5096:             If the named configuration is not in the file, an empty
 5097:             hash is returned.
 5098:     a hash with the fields
 5099:       name         - internal name for the this configuration setup
 5100:       description  - text to display to operator that describes this config
 5101:       CODElocation - if 0 or the string 'none'
 5102:                           - no CODE exists for this config
 5103:                      if -1 || the string 'letter'
 5104:                           - a CODE exists for this config and is
 5105:                             a string of letters
 5106:                      Unsupported value (but planned for future support)
 5107:                           if a positive integer
 5108:                                - The CODE exists as the first n items from
 5109:                                  the question section of the form
 5110:                           if the string 'number'
 5111:                                - The CODE exists for this config and is
 5112:                                  a string of numbers
 5113:       CODEstart   - (only matter if a CODE exists) column in the line where
 5114:                      the CODE starts
 5115:       CODElength  - length of the CODE
 5116:       IDstart     - column where the student ID number starts
 5117:       IDlength    - length of the student ID info
 5118:       Qstart      - column where the information from the bubbled
 5119:                     'questions' start
 5120:       Qlength     - number of columns comprising a single bubble line from
 5121:                     the sheet. (usually either 1 or 10)
 5122:       Qon         - either a single character representing the character used
 5123:                     to signal a bubble was chosen in the positional setup, or
 5124:                     the string 'letter' if the letter of the chosen bubble is
 5125:                     in the final, or 'number' if a number representing the
 5126:                     chosen bubble is in the file (1->A 0->J)
 5127:       Qoff        - the character used to represent that a bubble was
 5128:                     left blank
 5129:       PaperID     - if the scanning process generates a unique number for each
 5130:                     sheet scanned the column that this ID number starts in
 5131:       PaperIDlength - number of columns that comprise the unique ID number
 5132:                       for the sheet of paper
 5133:       FirstName   - column that the first name starts in
 5134:       FirstNameLength - number of columns that the first name spans
 5135:  
 5136:       LastName    - column that the last name starts in
 5137:       LastNameLength - number of columns that the last name spans
 5138: 
 5139: =cut
 5140: 
 5141: sub get_scantron_config {
 5142:     my ($which) = @_;
 5143:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5144:     my %config;
 5145:     #FIXME probably should move to XML it has already gotten a bit much now
 5146:     foreach my $line (<$fh>) {
 5147: 	my ($name,$descrip)=split(/:/,$line);
 5148: 	if ($name ne $which ) { next; }
 5149: 	chomp($line);
 5150: 	my @config=split(/:/,$line);
 5151: 	$config{'name'}=$config[0];
 5152: 	$config{'description'}=$config[1];
 5153: 	$config{'CODElocation'}=$config[2];
 5154: 	$config{'CODEstart'}=$config[3];
 5155: 	$config{'CODElength'}=$config[4];
 5156: 	$config{'IDstart'}=$config[5];
 5157: 	$config{'IDlength'}=$config[6];
 5158: 	$config{'Qstart'}=$config[7];
 5159:  	$config{'Qlength'}=$config[8];
 5160: 	$config{'Qoff'}=$config[9];
 5161: 	$config{'Qon'}=$config[10];
 5162: 	$config{'PaperID'}=$config[11];
 5163: 	$config{'PaperIDlength'}=$config[12];
 5164: 	$config{'FirstName'}=$config[13];
 5165: 	$config{'FirstNamelength'}=$config[14];
 5166: 	$config{'LastName'}=$config[15];
 5167: 	$config{'LastNamelength'}=$config[16];
 5168: 	last;
 5169:     }
 5170:     return %config;
 5171: }
 5172: 
 5173: =pod 
 5174: 
 5175: =item username_to_idmap
 5176: 
 5177:     creates a hash keyed by student id with values of the corresponding
 5178:     student username:domain.
 5179: 
 5180:   Arguments:
 5181: 
 5182:     $classlist - reference to the class list hash. This is a hash
 5183:                  keyed by student name:domain  whose elements are references
 5184:                  to arrays containing various chunks of information
 5185:                  about the student. (See loncoursedata for more info).
 5186: 
 5187:   Returns
 5188:     %idmap - the constructed hash
 5189: 
 5190: =cut
 5191: 
 5192: sub username_to_idmap {
 5193:     my ($classlist)= @_;
 5194:     my %idmap;
 5195:     foreach my $student (keys(%$classlist)) {
 5196: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5197: 	    $student;
 5198:     }
 5199:     return %idmap;
 5200: }
 5201: 
 5202: =pod
 5203: 
 5204: =item scantron_fixup_scanline
 5205: 
 5206:    Process a requested correction to a scanline.
 5207: 
 5208:   Arguments:
 5209:     $scantron_config   - hash from &get_scantron_config()
 5210:     $scan_data         - hash of correction information 
 5211:                           (see &scantron_getfile())
 5212:     $line              - existing scanline
 5213:     $whichline         - line number of the passed in scanline
 5214:     $field             - type of change to process 
 5215:                          (either 
 5216:                           'ID'     -> correct the student ID number
 5217:                           'CODE'   -> correct the CODE
 5218:                           'answer' -> fixup the submitted answers)
 5219:     
 5220:    $args               - hash of additional info,
 5221:                           - 'ID' 
 5222:                                'newid' -> studentID to use in replacement
 5223:                                           of existing one
 5224:                           - 'CODE' 
 5225:                                'CODE_ignore_dup' - set to true if duplicates
 5226:                                                    should be ignored.
 5227: 	                       'CODE' - is new code or 'use_unfound'
 5228:                                         if the existing unfound code should
 5229:                                         be used as is
 5230:                           - 'answer'
 5231:                                'response' - new answer or 'none' if blank
 5232:                                'question' - the bubble line to change
 5233:                                'questionnum' - the question identifier,
 5234:                                                may include subquestion. 
 5235: 
 5236:   Returns:
 5237:     $line - the modified scanline
 5238: 
 5239:   Side effects: 
 5240:     $scan_data - may be updated
 5241: 
 5242: =cut
 5243: 
 5244: 
 5245: sub scantron_fixup_scanline {
 5246:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5247:     if ($field eq 'ID') {
 5248: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5249: 	    return ($line,1,'New value too large');
 5250: 	}
 5251: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5252: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5253: 				     $args->{'newid'});
 5254: 	}
 5255: 	substr($line,$$scantron_config{'IDstart'}-1,
 5256: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5257: 	if ($args->{'newid'}=~/^\s*$/) {
 5258: 	    &scan_data($scan_data,"$whichline.user",
 5259: 		       $args->{'username'}.':'.$args->{'domain'});
 5260: 	}
 5261:     } elsif ($field eq 'CODE') {
 5262: 	if ($args->{'CODE_ignore_dup'}) {
 5263: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5264: 	}
 5265: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5266: 	if ($args->{'CODE'} ne 'use_unfound') {
 5267: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5268: 		return ($line,1,'New CODE value too large');
 5269: 	    }
 5270: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5271: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5272: 	    }
 5273: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5274: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5275: 	}
 5276:     } elsif ($field eq 'answer') {
 5277: 	my $length=$scantron_config->{'Qlength'};
 5278: 	my $off=$scantron_config->{'Qoff'};
 5279: 	my $on=$scantron_config->{'Qon'};
 5280: 	my $answer=${off}x$length;
 5281: 	if ($args->{'response'} eq 'none') {
 5282: 	    &scan_data($scan_data,
 5283: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5284: 	} else {
 5285: 	    if ($on eq 'letter') {
 5286: 		my @alphabet=('A'..'Z');
 5287: 		$answer=$alphabet[$args->{'response'}];
 5288: 	    } elsif ($on eq 'number') {
 5289: 		$answer=$args->{'response'}+1;
 5290: 		if ($answer == 10) { $answer = '0'; }
 5291: 	    } else {
 5292: 		substr($answer,$args->{'response'},1)=$on;
 5293: 	    }
 5294: 	    &scan_data($scan_data,
 5295: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5296: 	}
 5297: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5298: 	substr($line,$where-1,$length)=$answer;
 5299:     }
 5300:     return $line;
 5301: }
 5302: 
 5303: =pod
 5304: 
 5305: =item scan_data
 5306: 
 5307:     Edit or look up  an item in the scan_data hash.
 5308: 
 5309:   Arguments:
 5310:     $scan_data  - The hash (see scantron_getfile)
 5311:     $key        - shorthand of the key to edit (actual key is
 5312:                   scantronfilename_key).
 5313:     $data        - New value of the hash entry.
 5314:     $delete      - If true, the entry is removed from the hash.
 5315: 
 5316:   Returns:
 5317:     The new value of the hash table field (undefined if deleted).
 5318: 
 5319: =cut
 5320: 
 5321: 
 5322: sub scan_data {
 5323:     my ($scan_data,$key,$value,$delete)=@_;
 5324:     my $filename=$env{'form.scantron_selectfile'};
 5325:     if (defined($value)) {
 5326: 	$scan_data->{$filename.'_'.$key} = $value;
 5327:     }
 5328:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5329:     return $scan_data->{$filename.'_'.$key};
 5330: }
 5331: 
 5332: # ----- These first few routines are general use routines.----
 5333: 
 5334: # Return the number of occurences of a pattern in a string.
 5335: 
 5336: sub occurence_count {
 5337:     my ($string, $pattern) = @_;
 5338: 
 5339:     my @matches = ($string =~ /$pattern/g);
 5340: 
 5341:     return scalar(@matches);
 5342: }
 5343: 
 5344: 
 5345: # Take a string known to have digits and convert all the
 5346: # digits into letters in the range J,A..I.
 5347: 
 5348: sub digits_to_letters {
 5349:     my ($input) = @_;
 5350: 
 5351:     my @alphabet = ('J', 'A'..'I');
 5352: 
 5353:     my @input    = split(//, $input);
 5354:     my $output ='';
 5355:     for (my $i = 0; $i < scalar(@input); $i++) {
 5356: 	if ($input[$i] =~ /\d/) {
 5357: 	    $output .= $alphabet[$input[$i]];
 5358: 	} else {
 5359: 	    $output .= $input[$i];
 5360: 	}
 5361:     }
 5362:     return $output;
 5363: }
 5364: 
 5365: =pod 
 5366: 
 5367: =item scantron_parse_scanline
 5368: 
 5369:   Decodes a scanline from the selected scantron file
 5370: 
 5371:  Arguments:
 5372:     line             - The text of the scantron file line to process
 5373:     whichline        - Line number
 5374:     scantron_config  - Hash describing the format of the scantron lines.
 5375:     scan_data        - Hash of extra information about the scanline
 5376:                        (see scantron_getfile for more information)
 5377:     just_header      - True if should not process question answers but only
 5378:                        the stuff to the left of the answers.
 5379:  Returns:
 5380:    Hash containing the result of parsing the scanline
 5381: 
 5382:    Keys are all proceeded by the string 'scantron.'
 5383: 
 5384:        CODE    - the CODE in use for this scanline
 5385:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5386:                  by the operator
 5387:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5388:                             CODEs were selected, but the usage has been
 5389:                             forced by the operator
 5390:        ID  - student ID
 5391:        PaperID - if used, the ID number printed on the sheet when the 
 5392:                  paper was scanned
 5393:        FirstName - first name from the sheet
 5394:        LastName  - last name from the sheet
 5395: 
 5396:      if just_header was not true these key may also exist
 5397: 
 5398:        missingerror - a list of bubble ranges that are considered to be answers
 5399:                       to a single question that don't have any bubbles filled in.
 5400:                       Of the form questionnumber:firstbubblenumber:count.
 5401:        doubleerror  - a list of bubble ranges that are considered to be answers
 5402:                       to a single question that have more than one bubble filled in.
 5403:                       Of the form questionnumber::firstbubblenumber:count
 5404:    
 5405:                 In the above, count is the number of bubble responses in the
 5406:                 input line needed to represent the possible answers to the question.
 5407:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5408:                 per line would have count = 2.
 5409: 
 5410:        maxquest     - the number of the last bubble line that was parsed
 5411: 
 5412:        (<number> starts at 1)
 5413:        <number>.answer - zero or more letters representing the selected
 5414:                          letters from the scanline for the bubble line 
 5415:                          <number>.
 5416:                          if blank there was either no bubble or there where
 5417:                          multiple bubbles, (consult the keys missingerror and
 5418:                          doubleerror if this is an error condition)
 5419: 
 5420: =cut
 5421: 
 5422: sub scantron_parse_scanline {
 5423:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5424: 
 5425:     my %record;
 5426:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5427:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5428:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5429: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5430: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5431: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5432: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5433: 	    $record{'scantron.CODE'}=substr($data,
 5434: 					    $$scantron_config{'CODEstart'}-1,
 5435: 					    $$scantron_config{'CODElength'});
 5436: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5437: 		$record{'scantron.useCODE'}=1;
 5438: 	    }
 5439: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5440: 		$record{'scantron.CODE_ignore_dup'}=1;
 5441: 	    }
 5442: 	} else {
 5443: 	    #FIXME interpret first N questions
 5444: 	}
 5445:     }
 5446:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5447: 				  $$scantron_config{'IDlength'});
 5448:     $record{'scantron.PaperID'}=
 5449: 	substr($data,$$scantron_config{'PaperID'}-1,
 5450: 	       $$scantron_config{'PaperIDlength'});
 5451:     $record{'scantron.FirstName'}=
 5452: 	substr($data,$$scantron_config{'FirstName'}-1,
 5453: 	       $$scantron_config{'FirstNamelength'});
 5454:     $record{'scantron.LastName'}=
 5455: 	substr($data,$$scantron_config{'LastName'}-1,
 5456: 	       $$scantron_config{'LastNamelength'});
 5457:     if ($just_header) { return \%record; }
 5458: 
 5459:     my @alphabet=('A'..'Z');
 5460:     my $questnum=0;
 5461:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5462: 
 5463:     chomp($questions);		# Get rid of any trailing \n.
 5464:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5465:     while (length($questions)) {
 5466: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5467:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5468:                              || 1;
 5469:         $questnum++;
 5470:         my $quest_id = $questnum;
 5471:         my $currentquest = substr($questions,0,$answer_length);
 5472:         $questions       = substr($questions,$answer_length);
 5473:         if (length($currentquest) < $answer_length) { next; }
 5474: 
 5475:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5476:             my $subquestnum = 1;
 5477:             my $subquestions = $currentquest;
 5478:             my @subanswers_needed = 
 5479:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5480:             foreach my $subans (@subanswers_needed) {
 5481:                 my $subans_length =
 5482:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5483:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5484:                 $subquestions   = substr($subquestions,$subans_length);
 5485:                 $quest_id = "$questnum.$subquestnum";
 5486:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5487:                     ($$scantron_config{'Qon'} eq 'number')) {
 5488:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5489:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5490:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5491:                 } else {
 5492:                     $ansnum = &scantron_validator_positional($ansnum,
 5493:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5494:                 }
 5495:                 $subquestnum ++;
 5496:             }
 5497:         } else {
 5498:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5499:                 ($$scantron_config{'Qon'} eq 'number')) {
 5500:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5501:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5502:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5503:             } else {
 5504:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5505:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5506:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5507:             }
 5508:         }
 5509:     }
 5510:     $record{'scantron.maxquest'}=$questnum;
 5511:     return \%record;
 5512: }
 5513: 
 5514: sub scantron_validator_lettnum {
 5515:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5516:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5517: 
 5518:     # Qon 'letter' implies for each slot in currquest we have:
 5519:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5520:     #    about anything else (esp. a value of Qoff) for missing
 5521:     #    bubbles.
 5522:     #
 5523:     # Qon 'number' implies each slot gives a digit that indexes the
 5524:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5525:     #    and * or ? for double bubbles on a single line.
 5526:     #
 5527: 
 5528:     my $matchon;
 5529:     if ($$scantron_config{'Qon'} eq 'letter') {
 5530:         $matchon = '[A-Z]';
 5531:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5532:         $matchon = '\d';
 5533:     }
 5534:     my $occurrences = 0;
 5535:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5536:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5537:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5538:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5539:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5540:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5541:         my @singlelines = split('',$currquest);
 5542:         foreach my $entry (@singlelines) {
 5543:             $occurrences = &occurence_count($entry,$matchon);
 5544:             if ($occurrences > 1) {
 5545:                 last;
 5546:             }
 5547:         } 
 5548:     } else {
 5549:         $occurrences = &occurence_count($currquest,$matchon); 
 5550:     }
 5551:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5552:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5553:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5554:             my $bubble = substr($currquest,$ans,1);
 5555:             if ($bubble =~ /$matchon/ ) {
 5556:                 if ($$scantron_config{'Qon'} eq 'number') {
 5557:                     if ($bubble == 0) {
 5558:                         $bubble = 10; 
 5559:                     }
 5560:                     $record->{"scantron.$ansnum.answer"} = 
 5561:                         $alphabet->[$bubble-1];
 5562:                 } else {
 5563:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5564:                 }
 5565:             } else {
 5566:                 $record->{"scantron.$ansnum.answer"}='';
 5567:             }
 5568:             $ansnum++;
 5569:         }
 5570:     } elsif (!defined($currquest)
 5571:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5572:             || (&occurence_count($currquest,$matchon) == 0)) {
 5573:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5574:             $record->{"scantron.$ansnum.answer"}='';
 5575:             $ansnum++;
 5576:         }
 5577:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5578:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5579:         }
 5580:     } else {
 5581:         if ($$scantron_config{'Qon'} eq 'number') {
 5582:             $currquest = &digits_to_letters($currquest);            
 5583:         }
 5584:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5585:             my $bubble = substr($currquest,$ans,1);
 5586:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5587:             $ansnum++;
 5588:         }
 5589:     }
 5590:     return $ansnum;
 5591: }
 5592: 
 5593: sub scantron_validator_positional {
 5594:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5595:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5596: 
 5597:     # Otherwise there's a positional notation;
 5598:     # each bubble line requires Qlength items, and there are filled in
 5599:     # bubbles for each case where there 'Qon' characters.
 5600:     #
 5601: 
 5602:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5603: 
 5604:     # If the split only gives us one element.. the full length of the
 5605:     # answer string, no bubbles are filled in:
 5606: 
 5607:     if ($answers_needed eq '') {
 5608:         return;
 5609:     }
 5610: 
 5611:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5612:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5613:             $record->{"scantron.$ansnum.answer"}='';
 5614:             $ansnum++;
 5615:         }
 5616:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5617:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5618:         }
 5619:     } elsif (scalar(@array) == 2) {
 5620:         my $location = length($array[0]);
 5621:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5622:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5623:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5624:             if ($ans eq $line_num) {
 5625:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5626:             } else {
 5627:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5628:             }
 5629:             $ansnum++;
 5630:          }
 5631:     } else {
 5632:         #  If there's more than one instance of a bubble character
 5633:         #  That's a double bubble; with positional notation we can
 5634:         #  record all the bubbles filled in as well as the
 5635:         #  fact this response consists of multiple bubbles.
 5636:         #
 5637:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5638:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5639:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5640:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5641:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5642:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5643:             my $doubleerror = 0;
 5644:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5645:                    (!$doubleerror)) {
 5646:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5647:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5648:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5649:                if (length(@currarray) > 2) {
 5650:                    $doubleerror = 1;
 5651:                } 
 5652:             }
 5653:             if ($doubleerror) {
 5654:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5655:             }
 5656:         } else {
 5657:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5658:         }
 5659:         my $item = $ansnum;
 5660:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5661:             $record->{"scantron.$item.answer"} = '';
 5662:             $item ++;
 5663:         }
 5664: 
 5665:         my @ans=@array;
 5666:         my $i=0;
 5667:         my $increment = 0;
 5668:         while ($#ans) {
 5669:             $i+=length($ans[0]) + $increment;
 5670:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5671:             my $bubble = $i%$$scantron_config{'Qlength'};
 5672:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5673:             shift(@ans);
 5674:             $increment = 1;
 5675:         }
 5676:         $ansnum += $answers_needed;
 5677:     }
 5678:     return $ansnum;
 5679: }
 5680: 
 5681: =pod
 5682: 
 5683: =item scantron_add_delay
 5684: 
 5685:    Adds an error message that occurred during the grading phase to a
 5686:    queue of messages to be shown after grading pass is complete
 5687: 
 5688:  Arguments:
 5689:    $delayqueue  - arrary ref of hash ref of error messages
 5690:    $scanline    - the scanline that caused the error
 5691:    $errormesage - the error message
 5692:    $errorcode   - a numeric code for the error
 5693: 
 5694:  Side Effects:
 5695:    updates the $delayqueue to have a new hash ref of the error
 5696: 
 5697: =cut
 5698: 
 5699: sub scantron_add_delay {
 5700:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5701:     push(@$delayqueue,
 5702: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5703: 	  'ecode' => $errorcode }
 5704: 	 );
 5705: }
 5706: 
 5707: =pod
 5708: 
 5709: =item scantron_find_student
 5710: 
 5711:    Finds the username for the current scanline
 5712: 
 5713:   Arguments:
 5714:    $scantron_record - hash result from scantron_parse_scanline
 5715:    $scan_data       - hash of correction information 
 5716:                       (see &scantron_getfile() form more information)
 5717:    $idmap           - hash from &username_to_idmap()
 5718:    $line            - number of current scanline
 5719:  
 5720:   Returns:
 5721:    Either 'username:domain' or undef if unknown
 5722: 
 5723: =cut
 5724: 
 5725: sub scantron_find_student {
 5726:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5727:     my $scanID=$$scantron_record{'scantron.ID'};
 5728:     if ($scanID =~ /^\s*$/) {
 5729:  	return &scan_data($scan_data,"$line.user");
 5730:     }
 5731:     foreach my $id (keys(%$idmap)) {
 5732:  	if (lc($id) eq lc($scanID)) {
 5733:  	    return $$idmap{$id};
 5734:  	}
 5735:     }
 5736:     return undef;
 5737: }
 5738: 
 5739: =pod
 5740: 
 5741: =item scantron_filter
 5742: 
 5743:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5744:    hidden resources was selected
 5745: 
 5746: =cut
 5747: 
 5748: sub scantron_filter {
 5749:     my ($curres)=@_;
 5750: 
 5751:     if (ref($curres) && $curres->is_problem()) {
 5752: 	# if the user has asked to not have either hidden
 5753: 	# or 'randomout' controlled resources to be graded
 5754: 	# don't include them
 5755: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5756: 	    && $curres->randomout) {
 5757: 	    return 0;
 5758: 	}
 5759: 	return 1;
 5760:     }
 5761:     return 0;
 5762: }
 5763: 
 5764: =pod
 5765: 
 5766: =item scantron_process_corrections
 5767: 
 5768:    Gets correction information out of submitted form data and corrects
 5769:    the scanline
 5770: 
 5771: =cut
 5772: 
 5773: sub scantron_process_corrections {
 5774:     my ($r) = @_;
 5775:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5776:     my ($scanlines,$scan_data)=&scantron_getfile();
 5777:     my $classlist=&Apache::loncoursedata::get_classlist();
 5778:     my $which=$env{'form.scantron_line'};
 5779:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5780:     my ($skip,$err,$errmsg);
 5781:     if ($env{'form.scantron_skip_record'}) {
 5782: 	$skip=1;
 5783:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5784: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5785: 	    $env{'form.scantron_domain'};
 5786: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5787: 	($line,$err,$errmsg)=
 5788: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5789: 				     'ID',{'newid'=>$newid,
 5790: 				    'username'=>$env{'form.scantron_username'},
 5791: 				    'domain'=>$env{'form.scantron_domain'}});
 5792:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5793: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5794: 	my $newCODE;
 5795: 	my %args;
 5796: 	if      ($resolution eq 'use_unfound') {
 5797: 	    $newCODE='use_unfound';
 5798: 	} elsif ($resolution eq 'use_found') {
 5799: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5800: 	} elsif ($resolution eq 'use_typed') {
 5801: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5802: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5803: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5804: 	}
 5805: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5806: 	    $args{'CODE_ignore_dup'}=1;
 5807: 	}
 5808: 	$args{'CODE'}=$newCODE;
 5809: 	($line,$err,$errmsg)=
 5810: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5811: 				     'CODE',\%args);
 5812:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5813: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5814: 	    ($line,$err,$errmsg)=
 5815: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5816: 					 $which,'answer',
 5817: 					 { 'question'=>$question,
 5818: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5819:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5820: 	    if ($err) { last; }
 5821: 	}
 5822:     }
 5823:     if ($err) {
 5824: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5825:     } else {
 5826: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5827: 	&scantron_putfile($scanlines,$scan_data);
 5828:     }
 5829: }
 5830: 
 5831: =pod
 5832: 
 5833: =item reset_skipping_status
 5834: 
 5835:    Forgets the current set of remember skipped scanlines (and thus
 5836:    reverts back to considering all lines in the
 5837:    scantron_skipped_<filename> file)
 5838: 
 5839: =cut
 5840: 
 5841: sub reset_skipping_status {
 5842:     my ($scanlines,$scan_data)=&scantron_getfile();
 5843:     &scan_data($scan_data,'remember_skipping',undef,1);
 5844:     &scantron_putfile(undef,$scan_data);
 5845: }
 5846: 
 5847: =pod
 5848: 
 5849: =item start_skipping
 5850: 
 5851:    Marks a scanline to be skipped. 
 5852: 
 5853: =cut
 5854: 
 5855: sub start_skipping {
 5856:     my ($scan_data,$i)=@_;
 5857:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5858:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5859: 	$remembered{$i}=2;
 5860:     } else {
 5861: 	$remembered{$i}=1;
 5862:     }
 5863:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5864: }
 5865: 
 5866: =pod
 5867: 
 5868: =item should_be_skipped
 5869: 
 5870:    Checks whether a scanline should be skipped.
 5871: 
 5872: =cut
 5873: 
 5874: sub should_be_skipped {
 5875:     my ($scanlines,$scan_data,$i)=@_;
 5876:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5877: 	# not redoing old skips
 5878: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5879: 	return 0;
 5880:     }
 5881:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5882: 
 5883:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5884: 	return 0;
 5885:     }
 5886:     return 1;
 5887: }
 5888: 
 5889: =pod
 5890: 
 5891: =item remember_current_skipped
 5892: 
 5893:    Discovers what scanlines are in the scantron_skipped_<filename>
 5894:    file and remembers them into scan_data for later use.
 5895: 
 5896: =cut
 5897: 
 5898: sub remember_current_skipped {
 5899:     my ($scanlines,$scan_data)=&scantron_getfile();
 5900:     my %to_remember;
 5901:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5902: 	if ($scanlines->{'skipped'}[$i]) {
 5903: 	    $to_remember{$i}=1;
 5904: 	}
 5905:     }
 5906: 
 5907:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5908:     &scantron_putfile(undef,$scan_data);
 5909: }
 5910: 
 5911: =pod
 5912: 
 5913: =item check_for_error
 5914: 
 5915:     Checks if there was an error when attempting to remove a specific
 5916:     scantron_.. bubble sheet data file. Prints out an error if
 5917:     something went wrong.
 5918: 
 5919: =cut
 5920: 
 5921: sub check_for_error {
 5922:     my ($r,$result)=@_;
 5923:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5924: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 5925:     }
 5926: }
 5927: 
 5928: =pod
 5929: 
 5930: =item scantron_warning_screen
 5931: 
 5932:    Interstitial screen to make sure the operator has selected the
 5933:    correct options before we start the validation phase.
 5934: 
 5935: =cut
 5936: 
 5937: sub scantron_warning_screen {
 5938:     my ($button_text)=@_;
 5939:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5940:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5941:     my $CODElist;
 5942:     if ($scantron_config{'CODElocation'} &&
 5943: 	$scantron_config{'CODEstart'} &&
 5944: 	$scantron_config{'CODElength'}) {
 5945: 	$CODElist=$env{'form.scantron_CODElist'};
 5946: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5947: 	$CODElist=
 5948: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 5949: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5950:     }
 5951:     return ('
 5952: <p>
 5953: <span class="LC_warning">
 5954: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 5955: </p>
 5956: <table>
 5957: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 5958: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 5959: '.$CODElist.'
 5960: </table>
 5961: <br />
 5962: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 5963: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 5964: 
 5965: <br />
 5966: ');
 5967: }
 5968: 
 5969: =pod
 5970: 
 5971: =item scantron_do_warning
 5972: 
 5973:    Check if the operator has picked something for all required
 5974:    fields. Error out if something is missing.
 5975: 
 5976: =cut
 5977: 
 5978: sub scantron_do_warning {
 5979:     my ($r)=@_;
 5980:     my ($symb)=&get_symb($r);
 5981:     if (!$symb) {return '';}
 5982:     my $default_form_data=&defaultFormData($symb);
 5983:     $r->print(&scantron_form_start().$default_form_data);
 5984:     if ( $env{'form.selectpage'} eq '' ||
 5985: 	 $env{'form.scantron_selectfile'} eq '' ||
 5986: 	 $env{'form.scantron_format'} eq '' ) {
 5987: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 5988: 	if ( $env{'form.selectpage'} eq '') {
 5989: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 5990: 	} 
 5991: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5992: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 5993: 	} 
 5994: 	if ( $env{'form.scantron_format'} eq '') {
 5995: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 5996: 	} 
 5997:     } else {
 5998: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5999: 	$r->print('
 6000: '.$warning.'
 6001: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6002: <input type="hidden" name="command" value="scantron_validate" />
 6003: ');
 6004:     }
 6005:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6006:     return '';
 6007: }
 6008: 
 6009: =pod
 6010: 
 6011: =item scantron_form_start
 6012: 
 6013:     html hidden input for remembering all selected grading options
 6014: 
 6015: =cut
 6016: 
 6017: sub scantron_form_start {
 6018:     my ($max_bubble)=@_;
 6019:     my $result= <<SCANTRONFORM;
 6020: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6021:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6022:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6023:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6024:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6025:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6026:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6027:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6028:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6029:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6030: SCANTRONFORM
 6031: 
 6032:   my $line = 0;
 6033:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6034:        my $chunk =
 6035: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6036:        $chunk .=
 6037: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6038:        $chunk .= 
 6039:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6040:        $chunk .=
 6041:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6042:        $result .= $chunk;
 6043:        $line++;
 6044:    }
 6045:     return $result;
 6046: }
 6047: 
 6048: =pod
 6049: 
 6050: =item scantron_validate_file
 6051: 
 6052:     Dispatch routine for doing validation of a bubble sheet data file.
 6053: 
 6054:     Also processes any necessary information resets that need to
 6055:     occur before validation begins (ignore previous corrections,
 6056:     restarting the skipped records processing)
 6057: 
 6058: =cut
 6059: 
 6060: sub scantron_validate_file {
 6061:     my ($r) = @_;
 6062:     my ($symb)=&get_symb($r);
 6063:     if (!$symb) {return '';}
 6064:     my $default_form_data=&defaultFormData($symb);
 6065:     
 6066:     # do the detection of only doing skipped records first befroe we delete
 6067:     # them when doing the corrections reset
 6068:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6069: 	&reset_skipping_status();
 6070:     }
 6071:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6072: 	&remember_current_skipped();
 6073: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6074:     }
 6075: 
 6076:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6077: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6078: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6079: 	&check_for_error($r,&scantron_remove_scan_data());
 6080: 	$env{'form.scantron_options_ignore'}='done';
 6081:     }
 6082: 
 6083:     if ($env{'form.scantron_corrections'}) {
 6084: 	&scantron_process_corrections($r);
 6085:     }
 6086:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6087:     #get the student pick code ready
 6088:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6089:     my $max_bubble=&scantron_get_maxbubble();
 6090:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6091:     $r->print($result);
 6092:     
 6093:     my @validate_phases=( 'sequence',
 6094: 			  'ID',
 6095: 			  'CODE',
 6096: 			  'doublebubble',
 6097: 			  'missingbubbles');
 6098:     if (!$env{'form.validatepass'}) {
 6099: 	$env{'form.validatepass'} = 0;
 6100:     }
 6101:     my $currentphase=$env{'form.validatepass'};
 6102: 
 6103: 
 6104:     my $stop=0;
 6105:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6106: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6107: 	$r->rflush();
 6108: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6109: 	{
 6110: 	    no strict 'refs';
 6111: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6112: 	}
 6113:     }
 6114:     if (!$stop) {
 6115: 	my $warning=&scantron_warning_screen('Start Grading');
 6116: 	$r->print(&mt('Validation process complete.').'<br />
 6117: '.$warning.'
 6118: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6119: <input type="hidden" name="command" value="scantron_process" />
 6120: ');
 6121: 
 6122:     } else {
 6123: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6124: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6125:     }
 6126:     if ($stop) {
 6127: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6128: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6129: 	    $r->print(' '.&mt('this error').' <br />');
 6130: 
 6131: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6132: 	} else {
 6133:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6134: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6135:             } else {
 6136:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6137:             }
 6138: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6139: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6140: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6141: 	}
 6142:     }
 6143:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6144:     return '';
 6145: }
 6146: 
 6147: 
 6148: =pod
 6149: 
 6150: =item scantron_remove_file
 6151: 
 6152:    Removes the requested bubble sheet data file, makes sure that
 6153:    scantron_original_<filename> is never removed
 6154: 
 6155: 
 6156: =cut
 6157: 
 6158: sub scantron_remove_file {
 6159:     my ($which)=@_;
 6160:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6162:     my $file='scantron_';
 6163:     if ($which eq 'corrected' || $which eq 'skipped') {
 6164: 	$file.=$which.'_';
 6165:     } else {
 6166: 	return 'refused';
 6167:     }
 6168:     $file.=$env{'form.scantron_selectfile'};
 6169:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6170: }
 6171: 
 6172: 
 6173: =pod
 6174: 
 6175: =item scantron_remove_scan_data
 6176: 
 6177:    Removes all scan_data correction for the requested bubble sheet
 6178:    data file.  (In the case that both the are doing skipped records we need
 6179:    to remember the old skipped lines for the time being so that element
 6180:    persists for a while.)
 6181: 
 6182: =cut
 6183: 
 6184: sub scantron_remove_scan_data {
 6185:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6186:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6187:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6188:     my @todelete;
 6189:     my $filename=$env{'form.scantron_selectfile'};
 6190:     foreach my $key (@keys) {
 6191: 	if ($key=~/^\Q$filename\E_/) {
 6192: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6193: 		$key=~/remember_skipping/) {
 6194: 		next;
 6195: 	    }
 6196: 	    push(@todelete,$key);
 6197: 	}
 6198:     }
 6199:     my $result;
 6200:     if (@todelete) {
 6201: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6202: 				       \@todelete,$cdom,$cname);
 6203:     } else {
 6204: 	$result = 'ok';
 6205:     }
 6206:     return $result;
 6207: }
 6208: 
 6209: 
 6210: =pod
 6211: 
 6212: =item scantron_getfile
 6213: 
 6214:     Fetches the requested bubble sheet data file (all 3 versions), and
 6215:     the scan_data hash
 6216:   
 6217:   Arguments:
 6218:     None
 6219: 
 6220:   Returns:
 6221:     2 hash references
 6222: 
 6223:      - first one has 
 6224:          orig      -
 6225:          corrected -
 6226:          skipped   -  each of which points to an array ref of the specified
 6227:                       file broken up into individual lines
 6228:          count     - number of scanlines
 6229:  
 6230:      - second is the scan_data hash possible keys are
 6231:        ($number refers to scanline numbered $number and thus the key affects
 6232:         only that scanline
 6233:         $bubline refers to the specific bubble line element and the aspects
 6234:         refers to that specific bubble line element)
 6235: 
 6236:        $number.user - username:domain to use
 6237:        $number.CODE_ignore_dup 
 6238:                     - ignore the duplicate CODE error 
 6239:        $number.useCODE
 6240:                     - use the CODE in the scanline as is
 6241:        $number.no_bubble.$bubline
 6242:                     - it is valid that there is no bubbled in bubble
 6243:                       at $number $bubline
 6244:        remember_skipping
 6245:                     - a frozen hash containing keys of $number and values
 6246:                       of either 
 6247:                         1 - we are on a 'do skipped records pass' and plan
 6248:                             on processing this line
 6249:                         2 - we are on a 'do skipped records pass' and this
 6250:                             scanline has been marked to skip yet again
 6251: 
 6252: =cut
 6253: 
 6254: sub scantron_getfile {
 6255:     #FIXME really would prefer a scantron directory
 6256:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6257:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6258:     my $lines;
 6259:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6260: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6261:     my %scanlines;
 6262:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6263:     my $temp=$scanlines{'orig'};
 6264:     $scanlines{'count'}=$#$temp;
 6265: 
 6266:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6267: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6268:     if ($lines eq '-1') {
 6269: 	$scanlines{'corrected'}=[];
 6270:     } else {
 6271: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6272:     }
 6273:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6274: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6275:     if ($lines eq '-1') {
 6276: 	$scanlines{'skipped'}=[];
 6277:     } else {
 6278: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6279:     }
 6280:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6281:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6282:     my %scan_data = @tmp;
 6283:     return (\%scanlines,\%scan_data);
 6284: }
 6285: 
 6286: =pod
 6287: 
 6288: =item lonnet_putfile
 6289: 
 6290:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6291: 
 6292:  Arguments:
 6293:    $contents - data to store
 6294:    $filename - filename to store $contents into
 6295: 
 6296:  Returns:
 6297:    result value from &Apache::lonnet::finishuserfileupload
 6298: 
 6299: =cut
 6300: 
 6301: sub lonnet_putfile {
 6302:     my ($contents,$filename)=@_;
 6303:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6304:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6305:     $env{'form.sillywaytopassafilearound'}=$contents;
 6306:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6307: 
 6308: }
 6309: 
 6310: =pod
 6311: 
 6312: =item scantron_putfile
 6313: 
 6314:     Stores the current version of the bubble sheet data files, and the
 6315:     scan_data hash. (Does not modify the original version only the
 6316:     corrected and skipped versions.
 6317: 
 6318:  Arguments:
 6319:     $scanlines - hash ref that looks like the first return value from
 6320:                  &scantron_getfile()
 6321:     $scan_data - hash ref that looks like the second return value from
 6322:                  &scantron_getfile()
 6323: 
 6324: =cut
 6325: 
 6326: sub scantron_putfile {
 6327:     my ($scanlines,$scan_data) = @_;
 6328:     #FIXME really would prefer a scantron directory
 6329:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6330:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6331:     if ($scanlines) {
 6332: 	my $prefix='scantron_';
 6333: # no need to update orig, shouldn't change
 6334: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6335: #		    $env{'form.scantron_selectfile'});
 6336: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6337: 			$prefix.'corrected_'.
 6338: 			$env{'form.scantron_selectfile'});
 6339: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6340: 			$prefix.'skipped_'.
 6341: 			$env{'form.scantron_selectfile'});
 6342:     }
 6343:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6344: }
 6345: 
 6346: =pod
 6347: 
 6348: =item scantron_get_line
 6349: 
 6350:    Returns the correct version of the scanline
 6351: 
 6352:  Arguments:
 6353:     $scanlines - hash ref that looks like the first return value from
 6354:                  &scantron_getfile()
 6355:     $scan_data - hash ref that looks like the second return value from
 6356:                  &scantron_getfile()
 6357:     $i         - number of the requested line (starts at 0)
 6358: 
 6359:  Returns:
 6360:    A scanline, (either the original or the corrected one if it
 6361:    exists), or undef if the requested scanline should be
 6362:    skipped. (Either because it's an skipped scanline, or it's an
 6363:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6364:    pass.
 6365: 
 6366: =cut
 6367: 
 6368: sub scantron_get_line {
 6369:     my ($scanlines,$scan_data,$i)=@_;
 6370:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6371:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6372:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6373:     return $scanlines->{'orig'}[$i]; 
 6374: }
 6375: 
 6376: =pod
 6377: 
 6378: =item scantron_todo_count
 6379: 
 6380:     Counts the number of scanlines that need processing.
 6381: 
 6382:  Arguments:
 6383:     $scanlines - hash ref that looks like the first return value from
 6384:                  &scantron_getfile()
 6385:     $scan_data - hash ref that looks like the second return value from
 6386:                  &scantron_getfile()
 6387: 
 6388:  Returns:
 6389:     $count - number of scanlines to process
 6390: 
 6391: =cut
 6392: 
 6393: sub get_todo_count {
 6394:     my ($scanlines,$scan_data)=@_;
 6395:     my $count=0;
 6396:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6397: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6398: 	if ($line=~/^[\s\cz]*$/) { next; }
 6399: 	$count++;
 6400:     }
 6401:     return $count;
 6402: }
 6403: 
 6404: =pod
 6405: 
 6406: =item scantron_put_line
 6407: 
 6408:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6409:     data file.
 6410: 
 6411:  Arguments:
 6412:     $scanlines - hash ref that looks like the first return value from
 6413:                  &scantron_getfile()
 6414:     $scan_data - hash ref that looks like the second return value from
 6415:                  &scantron_getfile()
 6416:     $i         - line number to update
 6417:     $newline   - contents of the updated scanline
 6418:     $skip      - if true make the line for skipping and update the
 6419:                  'skipped' file
 6420: 
 6421: =cut
 6422: 
 6423: sub scantron_put_line {
 6424:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6425:     if ($skip) {
 6426: 	$scanlines->{'skipped'}[$i]=$newline;
 6427: 	&start_skipping($scan_data,$i);
 6428: 	return;
 6429:     }
 6430:     $scanlines->{'corrected'}[$i]=$newline;
 6431: }
 6432: 
 6433: =pod
 6434: 
 6435: =item scantron_clear_skip
 6436: 
 6437:    Remove a line from the 'skipped' file
 6438: 
 6439:  Arguments:
 6440:     $scanlines - hash ref that looks like the first return value from
 6441:                  &scantron_getfile()
 6442:     $scan_data - hash ref that looks like the second return value from
 6443:                  &scantron_getfile()
 6444:     $i         - line number to update
 6445: 
 6446: =cut
 6447: 
 6448: sub scantron_clear_skip {
 6449:     my ($scanlines,$scan_data,$i)=@_;
 6450:     if (exists($scanlines->{'skipped'}[$i])) {
 6451: 	undef($scanlines->{'skipped'}[$i]);
 6452: 	return 1;
 6453:     }
 6454:     return 0;
 6455: }
 6456: 
 6457: =pod
 6458: 
 6459: =item scantron_filter_not_exam
 6460: 
 6461:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6462:    filter out resources that are not marked as 'exam' mode
 6463: 
 6464: =cut
 6465: 
 6466: sub scantron_filter_not_exam {
 6467:     my ($curres)=@_;
 6468:     
 6469:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6470: 	# if the user has asked to not have either hidden
 6471: 	# or 'randomout' controlled resources to be graded
 6472: 	# don't include them
 6473: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6474: 	    && $curres->randomout) {
 6475: 	    return 0;
 6476: 	}
 6477: 	return 1;
 6478:     }
 6479:     return 0;
 6480: }
 6481: 
 6482: =pod
 6483: 
 6484: =item scantron_validate_sequence
 6485: 
 6486:     Validates the selected sequence, checking for resource that are
 6487:     not set to exam mode.
 6488: 
 6489: =cut
 6490: 
 6491: sub scantron_validate_sequence {
 6492:     my ($r,$currentphase) = @_;
 6493: 
 6494:     my $navmap=Apache::lonnavmaps::navmap->new();
 6495:     my (undef,undef,$sequence)=
 6496: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6497: 
 6498:     my $map=$navmap->getResourceByUrl($sequence);
 6499: 
 6500:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6501:                                     value="ignore" />');
 6502:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6503: 	my @resources=
 6504: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6505: 	if (@resources) {
 6506: 	    $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>");
 6507: 	    return (1,$currentphase);
 6508: 	}
 6509:     }
 6510: 
 6511:     return (0,$currentphase+1);
 6512: }
 6513: 
 6514: =pod
 6515: 
 6516: =item scantron_validate_ID
 6517: 
 6518:    Validates all scanlines in the selected file to not have any
 6519:    invalid or underspecified student IDs
 6520: 
 6521: =cut
 6522: 
 6523: sub scantron_validate_ID {
 6524:     my ($r,$currentphase) = @_;
 6525:     
 6526:     #get student info
 6527:     my $classlist=&Apache::loncoursedata::get_classlist();
 6528:     my %idmap=&username_to_idmap($classlist);
 6529: 
 6530:     #get scantron line setup
 6531:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6532:     my ($scanlines,$scan_data)=&scantron_getfile();
 6533:     
 6534:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6535: 
 6536:     my %found=('ids'=>{},'usernames'=>{});
 6537:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6538: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6539: 	if ($line=~/^[\s\cz]*$/) { next; }
 6540: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6541: 						 $scan_data);
 6542: 	my $id=$$scan_record{'scantron.ID'};
 6543: 	my $found;
 6544: 	foreach my $checkid (keys(%idmap)) {
 6545: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6546: 	}
 6547: 	if ($found) {
 6548: 	    my $username=$idmap{$found};
 6549: 	    if ($found{'ids'}{$found}) {
 6550: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6551: 					 $line,'duplicateID',$found);
 6552: 		return(1,$currentphase);
 6553: 	    } elsif ($found{'usernames'}{$username}) {
 6554: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6555: 					 $line,'duplicateID',$username);
 6556: 		return(1,$currentphase);
 6557: 	    }
 6558: 	    #FIXME store away line we previously saw the ID on to use above
 6559: 	    $found{'ids'}{$found}++;
 6560: 	    $found{'usernames'}{$username}++;
 6561: 	} else {
 6562: 	    if ($id =~ /^\s*$/) {
 6563: 		my $username=&scan_data($scan_data,"$i.user");
 6564: 		if (defined($username) && $found{'usernames'}{$username}) {
 6565: 		    &scantron_get_correction($r,$i,$scan_record,
 6566: 					     \%scantron_config,
 6567: 					     $line,'duplicateID',$username);
 6568: 		    return(1,$currentphase);
 6569: 		} elsif (!defined($username)) {
 6570: 		    &scantron_get_correction($r,$i,$scan_record,
 6571: 					     \%scantron_config,
 6572: 					     $line,'incorrectID');
 6573: 		    return(1,$currentphase);
 6574: 		}
 6575: 		$found{'usernames'}{$username}++;
 6576: 	    } else {
 6577: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6578: 					 $line,'incorrectID');
 6579: 		return(1,$currentphase);
 6580: 	    }
 6581: 	}
 6582:     }
 6583: 
 6584:     return (0,$currentphase+1);
 6585: }
 6586: 
 6587: =pod
 6588: 
 6589: =item scantron_get_correction
 6590: 
 6591:    Builds the interface screen to interact with the operator to fix a
 6592:    specific error condition in a specific scanline
 6593: 
 6594:  Arguments:
 6595:     $r           - Apache request object
 6596:     $i           - number of the current scanline
 6597:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6598:     $scan_config - hash ref as returned from &get_scantron_config()
 6599:     $line        - full contents of the current scanline
 6600:     $error       - error condition, valid values are
 6601:                    'incorrectCODE', 'duplicateCODE',
 6602:                    'doublebubble', 'missingbubble',
 6603:                    'duplicateID', 'incorrectID'
 6604:     $arg         - extra information needed
 6605:        For errors:
 6606:          - duplicateID   - paper number that this studentID was seen before on
 6607:          - duplicateCODE - array ref of the paper numbers this CODE was
 6608:                            seen on before
 6609:          - incorrectCODE - current incorrect CODE 
 6610:          - doublebubble  - array ref of the bubble lines that have double
 6611:                            bubble errors
 6612:          - missingbubble - array ref of the bubble lines that have missing
 6613:                            bubble errors
 6614: 
 6615: =cut
 6616: 
 6617: sub scantron_get_correction {
 6618:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6619: #FIXME in the case of a duplicated ID the previous line, probably need
 6620: #to show both the current line and the previous one and allow skipping
 6621: #the previous one or the current one
 6622: 
 6623:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6624: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6625: 			    " for PaperID <tt>[_1]</tt>",
 6626: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6627:     } else {
 6628: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6629: 			    " in scanline [_1] <pre>[_2]</pre>",
 6630: 			    $i,$line)."</p> \n");
 6631:     }
 6632:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6633: 			  "The name on the paper is [_2],[_3]",
 6634: 			  $$scan_record{'scantron.ID'},
 6635: 			  $$scan_record{'scantron.LastName'},
 6636: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6637: 
 6638:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6639:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6640:                            # Array populated for doublebubble or
 6641:     my @lines_to_correct;  # missingbubble errors to build javascript
 6642:                            # to validate radio button checking   
 6643: 
 6644:     if ($error =~ /ID$/) {
 6645: 	if ($error eq 'incorrectID') {
 6646: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6647: 		      "</p>\n");
 6648: 	} elsif ($error eq 'duplicateID') {
 6649: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6650: 	}
 6651: 	$r->print($message);
 6652: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6653: 	$r->print("\n<ul><li> ");
 6654: 	#FIXME it would be nice if this sent back the user ID and
 6655: 	#could do partial userID matches
 6656: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6657: 				       'scantron_username','scantron_domain'));
 6658: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6659: 	$r->print("\n@".
 6660: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6661: 
 6662: 	$r->print('</li>');
 6663:     } elsif ($error =~ /CODE$/) {
 6664: 	if ($error eq 'incorrectCODE') {
 6665: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6666: 	} elsif ($error eq 'duplicateCODE') {
 6667: 	    $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");
 6668: 	}
 6669: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6670: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6671: 	$r->print($message);
 6672: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6673: 	$r->print("\n<br /> ");
 6674: 	my $i=0;
 6675: 	if ($error eq 'incorrectCODE' 
 6676: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6677: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6678: 	    if ($closest > 0) {
 6679: 		foreach my $testcode (@{$closest}) {
 6680: 		    my $checked='';
 6681: 		    if (!$i) { $checked=' checked="checked" '; }
 6682: 		    $r->print("
 6683:    <label>
 6684:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6685:        ".&mt("Use the similar CODE [_1] instead.",
 6686: 	    "<b><tt>".$testcode."</tt></b>")."
 6687:     </label>
 6688:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6689: 		    $r->print("\n<br />");
 6690: 		    $i++;
 6691: 		}
 6692: 	    }
 6693: 	}
 6694: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6695: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6696: 	    $r->print("
 6697:     <label>
 6698:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6699:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6700: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6701:     </label>");
 6702: 	    $r->print("\n<br />");
 6703: 	}
 6704: 
 6705: 	$r->print(<<ENDSCRIPT);
 6706: <script type="text/javascript">
 6707: function change_radio(field) {
 6708:     var slct=document.scantronupload.scantron_CODE_resolution;
 6709:     var i;
 6710:     for (i=0;i<slct.length;i++) {
 6711:         if (slct[i].value==field) { slct[i].checked=true; }
 6712:     }
 6713: }
 6714: </script>
 6715: ENDSCRIPT
 6716: 	my $href="/adm/pickcode?".
 6717: 	   "form=".&escape("scantronupload").
 6718: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6719: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6720: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6721: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6722: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6723: 	    $r->print("
 6724:     <label>
 6725:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6726:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6727: 	     "<a target='_blank' href='$href'>","</a>")."
 6728:     </label> 
 6729:     ".&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')\" />"));
 6730: 	    $r->print("\n<br />");
 6731: 	}
 6732: 	$r->print("
 6733:     <label>
 6734:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6735:        ".&mt("Use [_1] as the CODE.",
 6736: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6737: 	$r->print("\n<br /><br />");
 6738:     } elsif ($error eq 'doublebubble') {
 6739: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6740: 
 6741: 	# The form field scantron_questions is acutally a list of line numbers.
 6742: 	# represented by this form so:
 6743: 
 6744: 	my $line_list = &questions_to_line_list($arg);
 6745: 
 6746: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6747: 		  $line_list.'" />');
 6748: 	$r->print($message);
 6749: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6750: 	foreach my $question (@{$arg}) {
 6751: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6752:                                                    $scan_record, $error);
 6753:             push (@lines_to_correct,@linenums);
 6754: 	}
 6755:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6756:     } elsif ($error eq 'missingbubble') {
 6757: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6758: 	$r->print($message);
 6759: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6760: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6761: 
 6762: 	# The form field scantron_questions is actually a list of line numbers not
 6763: 	# a list of question numbers. Therefore:
 6764: 	#
 6765: 	
 6766: 	my $line_list = &questions_to_line_list($arg);
 6767: 
 6768: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6769: 		  $line_list.'" />');
 6770: 	foreach my $question (@{$arg}) {
 6771: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6772:                                                    $scan_record, $error);
 6773:             push (@lines_to_correct,@linenums);
 6774: 	}
 6775:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6776:     } else {
 6777: 	$r->print("\n<ul>");
 6778:     }
 6779:     $r->print("\n</li></ul>");
 6780: }
 6781: 
 6782: sub verify_bubbles_checked {
 6783:     my (@ansnums) = @_;
 6784:     my $ansnumstr = join('","',@ansnums);
 6785:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6786:     my $output = (<<ENDSCRIPT);
 6787: <script type="text/javascript">
 6788: function verify_bubble_radio(form) {
 6789:     var ansnumArray = new Array ("$ansnumstr");
 6790:     var need_bubble_count = 0;
 6791:     for (var i=0; i<ansnumArray.length; i++) {
 6792:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6793:             var bubble_picked = 0; 
 6794:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6795:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6796:                     bubble_picked = 1;
 6797:                 }
 6798:             }
 6799:             if (bubble_picked == 0) {
 6800:                 need_bubble_count ++;
 6801:             }
 6802:         }
 6803:     }
 6804:     if (need_bubble_count) {
 6805:         alert("$warning");
 6806:         return;
 6807:     }
 6808:     form.submit(); 
 6809: }
 6810: </script>
 6811: ENDSCRIPT
 6812:     return $output;
 6813: }
 6814: 
 6815: =pod
 6816: 
 6817: =item  questions_to_line_list
 6818: 
 6819: Converts a list of questions into a string of comma separated
 6820: line numbers in the answer sheet used by the questions.  This is
 6821: used to fill in the scantron_questions form field.
 6822: 
 6823:   Arguments:
 6824:      questions    - Reference to an array of questions.
 6825: 
 6826: =cut
 6827: 
 6828: 
 6829: sub questions_to_line_list {
 6830:     my ($questions) = @_;
 6831:     my @lines;
 6832: 
 6833:     foreach my $item (@{$questions}) {
 6834:         my $question = $item;
 6835:         my ($first,$count,$last);
 6836:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6837:             $question = $1;
 6838:             my $subquestion = $2;
 6839:             $first = $first_bubble_line{$question-1} + 1;
 6840:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6841:             my $subcount = 1;
 6842:             while ($subcount<$subquestion) {
 6843:                 $first += $subans[$subcount-1];
 6844:                 $subcount ++;
 6845:             }
 6846:             $count = $subans[$subquestion-1];
 6847:         } else {
 6848: 	    $first   = $first_bubble_line{$question-1} + 1;
 6849: 	    $count   = $bubble_lines_per_response{$question-1};
 6850:         }
 6851:         $last = $first+$count-1;
 6852:         push(@lines, ($first..$last));
 6853:     }
 6854:     return join(',', @lines);
 6855: }
 6856: 
 6857: =pod 
 6858: 
 6859: =item prompt_for_corrections
 6860: 
 6861: Prompts for a potentially multiline correction to the
 6862: user's bubbling (factors out common code from scantron_get_correction
 6863: for multi and missing bubble cases).
 6864: 
 6865:  Arguments:
 6866:    $r           - Apache request object.
 6867:    $question    - The question number to prompt for.
 6868:    $scan_config - The scantron file configuration hash.
 6869:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6870:    $error       - Type of error
 6871: 
 6872:  Implicit inputs:
 6873:    %bubble_lines_per_response   - Starting line numbers for each question.
 6874:                                   Numbered from 0 (but question numbers are from
 6875:                                   1.
 6876:    %first_bubble_line           - Starting bubble line for each question.
 6877:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6878:                                   type problems render as separate sub-questions, 
 6879:                                   in exam mode. This hash contains a 
 6880:                                   comma-separated list of the lines per 
 6881:                                   sub-question.
 6882:    %responsetype_per_response   - essayresponse, formularesponse,
 6883:                                   stringresponse, imageresponse, reactionresponse,
 6884:                                   and organicresponse type problem parts can have
 6885:                                   multiple lines per response if the weight
 6886:                                   assigned exceeds 10.  In this case, only
 6887:                                   one bubble per line is permitted, but more 
 6888:                                   than one line might contain bubbles, e.g.
 6889:                                   bubbling of: line 1 - J, line 2 - J, 
 6890:                                   line 3 - B would assign 22 points.  
 6891: 
 6892: =cut
 6893: 
 6894: sub prompt_for_corrections {
 6895:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 6896:     my ($current_line,$lines);
 6897:     my @linenums;
 6898:     my $questionnum = $question;
 6899:     if ($question =~ /^(\d+)\.(\d+)$/) {
 6900:         $question = $1;
 6901:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6902:         my $subquestion = $2;
 6903:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6904:         my $subcount = 1;
 6905:         while ($subcount<$subquestion) {
 6906:             $current_line += $subans[$subcount-1];
 6907:             $subcount ++;
 6908:         }
 6909:         $lines = $subans[$subquestion-1];
 6910:     } else {
 6911:         $current_line = $first_bubble_line{$question-1} + 1 ;
 6912:         $lines        = $bubble_lines_per_response{$question-1};
 6913:     }
 6914:     if ($lines > 1) {
 6915:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 6916:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 6917:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 6918:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 6919:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 6920:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 6921:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 6922:             $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 />');
 6923:         } else {
 6924:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 6925:         }
 6926:     }
 6927:     for (my $i =0; $i < $lines; $i++) {
 6928:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 6929: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 6930: 	        		  $questionnum,$error,split('', $selected));
 6931:         push (@linenums,$current_line);
 6932: 	$current_line++;
 6933:     }
 6934:     if ($lines > 1) {
 6935: 	$r->print("<hr /><br />");
 6936:     }
 6937:     return @linenums;
 6938: }
 6939: 
 6940: =pod
 6941: 
 6942: =item scantron_bubble_selector
 6943:   
 6944:    Generates the html radiobuttons to correct a single bubble line
 6945:    possibly showing the existing the selected bubbles if known
 6946: 
 6947:  Arguments:
 6948:     $r           - Apache request object
 6949:     $scan_config - hash from &get_scantron_config()
 6950:     $line        - Number of the line being displayed.
 6951:     $questionnum - Question number (may include subquestion)
 6952:     $error       - Type of error.
 6953:     @selected    - Array of bubbles picked on this line.
 6954: 
 6955: =cut
 6956: 
 6957: sub scantron_bubble_selector {
 6958:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 6959:     my $max=$$scan_config{'Qlength'};
 6960: 
 6961:     my $scmode=$$scan_config{'Qon'};
 6962:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6963: 
 6964:     my @alphabet=('A'..'Z');
 6965:     $r->print(&Apache::loncommon::start_data_table().
 6966:               &Apache::loncommon::start_data_table_row());
 6967:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 6968:     for (my $i=0;$i<$max+1;$i++) {
 6969: 	$r->print("\n".'<td align="center">');
 6970: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 6971: 	else { $r->print('&nbsp;'); }
 6972: 	$r->print('</td>');
 6973:     }
 6974:     $r->print(&Apache::loncommon::end_data_table_row().
 6975:               &Apache::loncommon::start_data_table_row());
 6976:     for (my $i=0;$i<$max;$i++) {
 6977: 	$r->print("\n".
 6978: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 6979: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6980:     }
 6981:     my $nobub_checked = ' ';
 6982:     if ($error eq 'missingbubble') {
 6983:         $nobub_checked = ' checked = "checked" ';
 6984:     }
 6985:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 6986: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 6987:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 6988:               $line.'" value="'.$questionnum.'" /></td>');
 6989:     $r->print(&Apache::loncommon::end_data_table_row().
 6990:               &Apache::loncommon::end_data_table());
 6991: }
 6992: 
 6993: =pod
 6994: 
 6995: =item num_matches
 6996: 
 6997:    Counts the number of characters that are the same between the two arguments.
 6998: 
 6999:  Arguments:
 7000:    $orig - CODE from the scanline
 7001:    $code - CODE to match against
 7002: 
 7003:  Returns:
 7004:    $count - integer count of the number of same characters between the
 7005:             two arguments
 7006: 
 7007: =cut
 7008: 
 7009: sub num_matches {
 7010:     my ($orig,$code) = @_;
 7011:     my @code=split(//,$code);
 7012:     my @orig=split(//,$orig);
 7013:     my $same=0;
 7014:     for (my $i=0;$i<scalar(@code);$i++) {
 7015: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7016:     }
 7017:     return $same;
 7018: }
 7019: 
 7020: =pod
 7021: 
 7022: =item scantron_get_closely_matching_CODEs
 7023: 
 7024:    Cycles through all CODEs and finds the set that has the greatest
 7025:    number of same characters as the provided CODE
 7026: 
 7027:  Arguments:
 7028:    $allcodes - hash ref returned by &get_codes()
 7029:    $CODE     - CODE from the current scanline
 7030: 
 7031:  Returns:
 7032:    2 element list
 7033:     - first elements is number of how closely matching the best fit is 
 7034:       (5 means best set has 5 matching characters)
 7035:     - second element is an arrary ref containing the set of valid CODEs
 7036:       that best fit the passed in CODE
 7037: 
 7038: =cut
 7039: 
 7040: sub scantron_get_closely_matching_CODEs {
 7041:     my ($allcodes,$CODE)=@_;
 7042:     my @CODEs;
 7043:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7044: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7045:     }
 7046: 
 7047:     return ($#CODEs,$CODEs[-1]);
 7048: }
 7049: 
 7050: =pod
 7051: 
 7052: =item get_codes
 7053: 
 7054:    Builds a hash which has keys of all of the valid CODEs from the selected
 7055:    set of remembered CODEs.
 7056: 
 7057:  Arguments:
 7058:   $old_name - name of the set of remembered CODEs
 7059:   $cdom     - domain of the course
 7060:   $cnum     - internal course name
 7061: 
 7062:  Returns:
 7063:   %allcodes - keys are the valid CODEs, values are all 1
 7064: 
 7065: =cut
 7066: 
 7067: sub get_codes {
 7068:     my ($old_name, $cdom, $cnum) = @_;
 7069:     if (!$old_name) {
 7070: 	$old_name=$env{'form.scantron_CODElist'};
 7071:     }
 7072:     if (!$cdom) {
 7073: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7074:     }
 7075:     if (!$cnum) {
 7076: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7077:     }
 7078:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7079: 				    $cdom,$cnum);
 7080:     my %allcodes;
 7081:     if ($result{"type\0$old_name"} eq 'number') {
 7082: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7083:     } else {
 7084: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7085:     }
 7086:     return %allcodes;
 7087: }
 7088: 
 7089: =pod
 7090: 
 7091: =item scantron_validate_CODE
 7092: 
 7093:    Validates all scanlines in the selected file to not have any
 7094:    invalid or underspecified CODEs and that none of the codes are
 7095:    duplicated if this was requested.
 7096: 
 7097: =cut
 7098: 
 7099: sub scantron_validate_CODE {
 7100:     my ($r,$currentphase) = @_;
 7101:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7102:     if ($scantron_config{'CODElocation'} &&
 7103: 	$scantron_config{'CODEstart'} &&
 7104: 	$scantron_config{'CODElength'}) {
 7105: 	if (!defined($env{'form.scantron_CODElist'})) {
 7106: 	    &FIXME_blow_up()
 7107: 	}
 7108:     } else {
 7109: 	return (0,$currentphase+1);
 7110:     }
 7111:     
 7112:     my %usedCODEs;
 7113: 
 7114:     my %allcodes=&get_codes();
 7115: 
 7116:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7117: 
 7118:     my ($scanlines,$scan_data)=&scantron_getfile();
 7119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7120: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7121: 	if ($line=~/^[\s\cz]*$/) { next; }
 7122: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7123: 						 $scan_data);
 7124: 	my $CODE=$$scan_record{'scantron.CODE'};
 7125: 	my $error=0;
 7126: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7127: 	    &scantron_get_correction($r,$i,$scan_record,
 7128: 				     \%scantron_config,
 7129: 				     $line,'incorrectCODE',\%allcodes);
 7130: 	    return(1,$currentphase);
 7131: 	}
 7132: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7133: 	    && !$$scan_record{'scantron.useCODE'}) {
 7134: 	    &scantron_get_correction($r,$i,$scan_record,
 7135: 				     \%scantron_config,
 7136: 				     $line,'incorrectCODE',\%allcodes);
 7137: 	    return(1,$currentphase);
 7138: 	}
 7139: 	if (exists($usedCODEs{$CODE}) 
 7140: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7141: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7142: 	    &scantron_get_correction($r,$i,$scan_record,
 7143: 				     \%scantron_config,
 7144: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7145: 	    return(1,$currentphase);
 7146: 	}
 7147: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7148:     }
 7149:     return (0,$currentphase+1);
 7150: }
 7151: 
 7152: =pod
 7153: 
 7154: =item scantron_validate_doublebubble
 7155: 
 7156:    Validates all scanlines in the selected file to not have any
 7157:    bubble lines with multiple bubbles marked.
 7158: 
 7159: =cut
 7160: 
 7161: sub scantron_validate_doublebubble {
 7162:     my ($r,$currentphase) = @_;
 7163:     #get student info
 7164:     my $classlist=&Apache::loncoursedata::get_classlist();
 7165:     my %idmap=&username_to_idmap($classlist);
 7166: 
 7167:     #get scantron line setup
 7168:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7169:     my ($scanlines,$scan_data)=&scantron_getfile();
 7170:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7171: 
 7172:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7173: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7174: 	if ($line=~/^[\s\cz]*$/) { next; }
 7175: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7176: 						 $scan_data);
 7177: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7178: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7179: 				 'doublebubble',
 7180: 				 $$scan_record{'scantron.doubleerror'});
 7181:     	return (1,$currentphase);
 7182:     }
 7183:     return (0,$currentphase+1);
 7184: }
 7185: 
 7186: =pod
 7187: 
 7188: =item scantron_get_maxbubble
 7189: 
 7190:    Returns the maximum number of bubble lines that are expected to
 7191:    occur. Does this by walking the selected sequence rendering the
 7192:    resource and then checking &Apache::lonxml::get_problem_counter()
 7193:    for what the current value of the problem counter is.
 7194: 
 7195:    Caches the results to $env{'form.scantron_maxbubble'},
 7196:    $env{'form.scantron.bubble_lines.n'}, 
 7197:    $env{'form.scantron.first_bubble_line.n'} and
 7198:    $env{"form.scantron.sub_bubblelines.n"}
 7199:    which are the total number of bubble, lines, the number of bubble
 7200:    lines for response n and number of the first bubble line for response n,
 7201:    and a comma separated list of numbers of bubble lines for sub-questions
 7202:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7203: 
 7204: =cut
 7205: 
 7206: sub scantron_get_maxbubble {
 7207:     if (defined($env{'form.scantron_maxbubble'}) &&
 7208: 	$env{'form.scantron_maxbubble'}) {
 7209: 	&restore_bubble_lines();
 7210: 	return $env{'form.scantron_maxbubble'};
 7211:     }
 7212: 
 7213:     my (undef, undef, $sequence) =
 7214: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7215: 
 7216:     my $navmap=Apache::lonnavmaps::navmap->new();
 7217:     my $map=$navmap->getResourceByUrl($sequence);
 7218:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7219: 
 7220:     &Apache::lonxml::clear_problem_counter();
 7221: 
 7222:     my $uname       = $env{'form.student'};
 7223:     my $udom        = $env{'form.userdom'};
 7224:     my $cid         = $env{'request.course.id'};
 7225:     my $total_lines = 0;
 7226:     %bubble_lines_per_response = ();
 7227:     %first_bubble_line         = ();
 7228:     %subdivided_bubble_lines   = ();
 7229:     %responsetype_per_response = ();
 7230:   
 7231:     my $response_number = 0;
 7232:     my $bubble_line     = 0;
 7233:     foreach my $resource (@resources) {
 7234:         # Need to retrieve part IDs and response IDs because essayresponse,
 7235:         # reactionresponse and organicresponse items are not included in 
 7236:         # $analysis{'parts'} from lonnet::ssi.  
 7237:         my %possible_part_ids; 
 7238:         if (ref($resource->parts()) eq 'ARRAY') { 
 7239:             foreach my $part (@{$resource->parts()}) {
 7240:                 my @resp_ids = $resource->responseIds($part);
 7241:                 foreach my $id (@resp_ids) {
 7242:                     $possible_part_ids{$part.'.'.$id} = 1;
 7243:                 }
 7244:             }
 7245:         }
 7246: 	my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7247: 					('symb' => $resource->symb()),
 7248: 					('grade_target' => 'analyze'),
 7249: 					('grade_courseid' => $cid),
 7250: 					('grade_domain' => $udom),
 7251: 					('grade_username' => $uname));
 7252: 	my (undef, $an) =
 7253: 	    split(/_HASH_REF__/,$result, 2);
 7254: 
 7255:         my @parts;
 7256: 
 7257: 	my %analysis = &Apache::lonnet::str2hash($an);
 7258: 
 7259:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7260:             @parts = @{$analysis{'parts'}};
 7261:         }
 7262:         # Add part_ids for any essayresponse items. 
 7263:         foreach my $part_id (keys(%possible_part_ids)) {
 7264:             if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
 7265:                 ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
 7266:                 ($analysis{$part_id.'.type'} eq 'organicresponse')) {
 7267:                 if (!grep(/^\Q$part_id\E$/,@parts)) {
 7268:                     push (@parts,$part_id);
 7269:                 }
 7270:             }
 7271:         }
 7272: 
 7273: 	foreach my $part_id (@parts) {
 7274:             my $lines = $analysis{"$part_id.bubble_lines"};
 7275: 
 7276: 	    # TODO - make this a persistent hash not an array.
 7277: 
 7278:             # optionresponse, matchresponse and rankresponse type items 
 7279:             # render as separate sub-questions in exam mode.
 7280:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
 7281:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
 7282:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
 7283:                 my ($numbub,$numshown);
 7284:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
 7285:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
 7286:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
 7287:                     }
 7288:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
 7289:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
 7290:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
 7291:                     }
 7292:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
 7293:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
 7294:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
 7295:                     }
 7296:                 }
 7297:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
 7298:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
 7299:                 }
 7300:                 my $bubbles_per_line = 10;
 7301:                 my $inner_bubble_lines = int($numshown/$bubbles_per_line);
 7302:                 if (($numshown % $bubbles_per_line) != 0) {
 7303:                     $inner_bubble_lines++;
 7304:                 }
 7305:                 for (my $i=0; $i<$numshown; $i++) {
 7306:                     $subdivided_bubble_lines{$response_number} .= 
 7307:                         $inner_bubble_lines.',';
 7308:                 }
 7309:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7310:             } 
 7311: 
 7312:             $first_bubble_line{$response_number} = $bubble_line;
 7313: 	    $bubble_lines_per_response{$response_number} = $lines;
 7314:             $responsetype_per_response{$response_number} = 
 7315:                 $analysis{$part_id.'.type'};
 7316: 	    $response_number++;
 7317: 
 7318: 	    $bubble_line +=  $lines;
 7319: 	    $total_lines +=  $lines;
 7320: 	}
 7321: 
 7322:     }
 7323:     &Apache::lonnet::delenv('scantron\.');
 7324: 
 7325:     &save_bubble_lines();
 7326:     $env{'form.scantron_maxbubble'} =
 7327: 	$total_lines;
 7328:     return $env{'form.scantron_maxbubble'};
 7329: }
 7330: 
 7331: =pod
 7332: 
 7333: =item scantron_validate_missingbubbles
 7334: 
 7335:    Validates all scanlines in the selected file to not have any
 7336:     answers that don't have bubbles that have not been verified
 7337:     to be bubble free.
 7338: 
 7339: =cut
 7340: 
 7341: sub scantron_validate_missingbubbles {
 7342:     my ($r,$currentphase) = @_;
 7343:     #get student info
 7344:     my $classlist=&Apache::loncoursedata::get_classlist();
 7345:     my %idmap=&username_to_idmap($classlist);
 7346: 
 7347:     #get scantron line setup
 7348:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7349:     my ($scanlines,$scan_data)=&scantron_getfile();
 7350:     my $max_bubble=&scantron_get_maxbubble();
 7351:     if (!$max_bubble) { $max_bubble=2**31; }
 7352:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7353: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7354: 	if ($line=~/^[\s\cz]*$/) { next; }
 7355: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7356: 						 $scan_data);
 7357: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7358: 	my @to_correct;
 7359: 	
 7360: 	# Probably here's where the error is...
 7361: 
 7362: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7363:             my $lastbubble;
 7364:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7365:                my $question = $1;
 7366:                my $subquestion = $2;
 7367:                if (!defined($first_bubble_line{$question -1})) { next; }
 7368:                my $first = $first_bubble_line{$question-1};
 7369:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7370:                my $subcount = 1;
 7371:                while ($subcount<$subquestion) {
 7372:                    $first += $subans[$subcount-1];
 7373:                    $subcount ++;
 7374:                }
 7375:                my $count = $subans[$subquestion-1];
 7376:                $lastbubble = $first + $count;
 7377:             } else {
 7378:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7379:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7380:             }
 7381:             if ($lastbubble > $max_bubble) { next; }
 7382: 	    push(@to_correct,$missing);
 7383: 	}
 7384: 	if (@to_correct) {
 7385: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7386: 				     $line,'missingbubble',\@to_correct);
 7387: 	    return (1,$currentphase);
 7388: 	}
 7389: 
 7390:     }
 7391:     return (0,$currentphase+1);
 7392: }
 7393: 
 7394: =pod
 7395: 
 7396: =item scantron_process_students
 7397: 
 7398:    Routine that does the actual grading of the bubble sheet information.
 7399: 
 7400:    The parsed scanline hash is added to %env 
 7401: 
 7402:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7403:    foreach resource , with the form data of
 7404: 
 7405: 	'submitted'     =>'scantron' 
 7406: 	'grade_target'  =>'grade',
 7407: 	'grade_username'=> username of student
 7408: 	'grade_domain'  => domain of student
 7409: 	'grade_courseid'=> of course
 7410: 	'grade_symb'    => symb of resource to grade
 7411: 
 7412:     This triggers a grading pass. The problem grading code takes care
 7413:     of converting the bubbled letter information (now in %env) into a
 7414:     valid submission.
 7415: 
 7416: =cut
 7417: 
 7418: sub scantron_process_students {
 7419:     my ($r) = @_;
 7420: 
 7421:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7422:     my ($symb)=&get_symb($r);
 7423:     if (!$symb) {
 7424: 	return '';
 7425:     }
 7426:     my $default_form_data=&defaultFormData($symb);
 7427: 
 7428:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7429:     my ($scanlines,$scan_data)=&scantron_getfile();
 7430:     my $classlist=&Apache::loncoursedata::get_classlist();
 7431:     my %idmap=&username_to_idmap($classlist);
 7432:     my $navmap=Apache::lonnavmaps::navmap->new();
 7433:     my $map=$navmap->getResourceByUrl($sequence);
 7434:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7435: #    $r->print("geto ".scalar(@resources)."<br />");
 7436:     my $result= <<SCANTRONFORM;
 7437: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7438:   <input type="hidden" name="command" value="scantron_configphase" />
 7439:   $default_form_data
 7440: SCANTRONFORM
 7441:     $r->print($result);
 7442: 
 7443:     my @delayqueue;
 7444:     my %completedstudents;
 7445:     
 7446:     my $count=&get_todo_count($scanlines,$scan_data);
 7447:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7448:  				    'Scantron Progress',$count,
 7449: 				    'inline',undef,'scantronupload');
 7450:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7451: 					  'Processing first student');
 7452:     my $start=&Time::HiRes::time();
 7453:     my $i=-1;
 7454:     my ($uname,$udom,$started);
 7455: 
 7456:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7457:     
 7458: 
 7459:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7460:     # the user and return.
 7461: 
 7462:     if ($ssi_error) {
 7463: 	$r->print("</form>");
 7464: 	&ssi_print_error($r);
 7465: 	$r->print(&show_grading_menu_form($symb));
 7466: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7467:     }
 7468: 
 7469:     while ($i<$scanlines->{'count'}) {
 7470:  	($uname,$udom)=('','');
 7471:  	$i++;
 7472:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7473:  	if ($line=~/^[\s\cz]*$/) { next; }
 7474: 	if ($started) {
 7475: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7476: 						     'last student');
 7477: 	}
 7478: 	$started=1;
 7479:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7480:  						 $scan_data);
 7481:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7482:  					      \%idmap,$i)) {
 7483:   	    &scantron_add_delay(\@delayqueue,$line,
 7484:  				'Unable to find a student that matches',1);
 7485:  	    next;
 7486:   	}
 7487:  	if (exists $completedstudents{$uname}) {
 7488:  	    &scantron_add_delay(\@delayqueue,$line,
 7489:  				'Student '.$uname.' has multiple sheets',2);
 7490:  	    next;
 7491:  	}
 7492:   	($uname,$udom)=split(/:/,$uname);
 7493: 
 7494: 	&Apache::lonxml::clear_problem_counter();
 7495:   	&Apache::lonnet::appenv($scan_record);
 7496: 
 7497: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7498: 	    &scantron_putfile($scanlines,$scan_data);
 7499: 	}
 7500: 	
 7501: 	my $i=0;
 7502: 	foreach my $resource (@resources) {
 7503: 	    $i++;
 7504: 	    my %form=('submitted'     =>'scantron',
 7505: 		      'grade_target'  =>'grade',
 7506: 		      'grade_username'=>$uname,
 7507: 		      'grade_domain'  =>$udom,
 7508: 		      'grade_courseid'=>$env{'request.course.id'},
 7509: 		      'grade_symb'    =>$resource->symb());
 7510: 	    if (exists($scan_record->{'scantron.CODE'})
 7511: 		&& 
 7512: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 7513: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 7514: 	    } else {
 7515: 		$form{'CODE'}='';
 7516: 	    } 
 7517: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
 7518: 	    if ($ssi_error) {
 7519: 		$ssi_error = 0;	# So end of handler error message does not trigger.
 7520: 		$r->print("</form>");
 7521: 		&ssi_print_error($r);
 7522: 		$r->print(&show_grading_menu_form($symb));
 7523: 		return '';	# Why return ''?  Beats me.
 7524: 	    }
 7525: 
 7526: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 7527: 	}
 7528: 	$completedstudents{$uname}={'line'=>$line};
 7529: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7530:     } continue {
 7531: 	&Apache::lonxml::clear_problem_counter();
 7532: 	&Apache::lonnet::delenv('scantron\.');
 7533:     }
 7534:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7535: #    my $lasttime = &Time::HiRes::time()-$start;
 7536: #    $r->print("<p>took $lasttime</p>");
 7537: 
 7538:     $r->print("</form>");
 7539:     $r->print(&show_grading_menu_form($symb));
 7540:     return '';
 7541: }
 7542: 
 7543: =pod
 7544: 
 7545: =item scantron_upload_scantron_data
 7546: 
 7547:     Creates the screen for adding a new bubble sheet data file to a course.
 7548: 
 7549: =cut
 7550: 
 7551: sub scantron_upload_scantron_data {
 7552:     my ($r)=@_;
 7553:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7554:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7555: 							  'domainid',
 7556: 							  'coursename');
 7557:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7558: 						   'domainid');
 7559:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7560:     $r->print('
 7561: <script type="text/javascript" language="javascript">
 7562:     function checkUpload(formname) {
 7563: 	if (formname.upfile.value == "") {
 7564: 	    alert("Please use the browse button to select a file from your local directory.");
 7565: 	    return false;
 7566: 	}
 7567: 	formname.submit();
 7568:     }
 7569: </script>
 7570: 
 7571: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7572: '.$default_form_data.'
 7573: <table>
 7574: <tr><td>'.$select_link.'                             </td></tr>
 7575: <tr><td>'.&mt('Course ID:').'     </td>
 7576:     <td><input name="courseid"   type="text" />      </td></tr>
 7577: <tr><td>'.&mt('Course Name:').'   </td>
 7578:     <td><input name="coursename" type="text" />      </td></tr>
 7579: <tr><td>'.&mt('Domain:').'        </td>
 7580:     <td>'.$domsel.'                                  </td></tr>
 7581: <tr><td>'.&mt('File to upload:').'</td>
 7582:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7583: </table>
 7584: <input name="command" value="scantronupload_save" type="hidden" />
 7585: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7586: </form>
 7587: ');
 7588:     return '';
 7589: }
 7590: 
 7591: =pod
 7592: 
 7593: =item scantron_upload_scantron_data_save
 7594: 
 7595:    Adds a provided bubble information data file to the course if user
 7596:    has the correct privileges to do so.  
 7597: 
 7598: =cut
 7599: 
 7600: sub scantron_upload_scantron_data_save {
 7601:     my($r)=@_;
 7602:     my ($symb)=&get_symb($r,1);
 7603:     my $doanotherupload=
 7604: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7605: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7606: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7607: 	'</form>'."\n";
 7608:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7609: 	!&Apache::lonnet::allowed('usc',
 7610: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7611: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7612: 	if ($symb) {
 7613: 	    $r->print(&show_grading_menu_form($symb));
 7614: 	} else {
 7615: 	    $r->print($doanotherupload);
 7616: 	}
 7617: 	return '';
 7618:     }
 7619:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7620:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7621:     my $fname=$env{'form.upfile.filename'};
 7622:     #FIXME
 7623:     #copied from lonnet::userfileupload()
 7624:     #make that function able to target a specified course
 7625:     # Replace Windows backslashes by forward slashes
 7626:     $fname=~s/\\/\//g;
 7627:     # Get rid of everything but the actual filename
 7628:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7629:     # Replace spaces by underscores
 7630:     $fname=~s/\s+/\_/g;
 7631:     # Replace all other weird characters by nothing
 7632:     $fname=~s/[^\w\.\-]//g;
 7633:     # See if there is anything left
 7634:     unless ($fname) { return 'error: no uploaded file'; }
 7635:     my $uploadedfile=$fname;
 7636:     $fname='scantron_orig_'.$fname;
 7637:     if (length($env{'form.upfile'}) < 2) {
 7638: 	$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>"));
 7639:     } else {
 7640: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7641: 	if ($result =~ m|^/uploaded/|) {
 7642: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7643: 			  (length($env{'form.upfile'})-1),
 7644: 			  '<span class="LC_filename">'.$result."</span>"));
 7645: 	} else {
 7646: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7647: 			  $result,
 7648: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7649: 
 7650: 	}
 7651:     }
 7652:     if ($symb) {
 7653: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7654:     } else {
 7655: 	$r->print($doanotherupload);
 7656:     }
 7657:     return '';
 7658: }
 7659: 
 7660: =pod
 7661: 
 7662: =item valid_file
 7663: 
 7664:    Validates that the requested bubble data file exists in the course.
 7665: 
 7666: =cut
 7667: 
 7668: sub valid_file {
 7669:     my ($requested_file)=@_;
 7670:     foreach my $filename (sort(&scantron_filenames())) {
 7671: 	if ($requested_file eq $filename) { return 1; }
 7672:     }
 7673:     return 0;
 7674: }
 7675: 
 7676: =pod
 7677: 
 7678: =item scantron_download_scantron_data
 7679: 
 7680:    Shows a list of the three internal files (original, corrected,
 7681:    skipped) for a specific bubble sheet data file that exists in the
 7682:    course.
 7683: 
 7684: =cut
 7685: 
 7686: sub scantron_download_scantron_data {
 7687:     my ($r)=@_;
 7688:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7689:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7690:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7691:     my $file=$env{'form.scantron_selectfile'};
 7692:     if (! &valid_file($file)) {
 7693: 	$r->print('
 7694: 	<p>
 7695: 	    '.&mt('The requested file name was invalid.').'
 7696:         </p>
 7697: ');
 7698: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7699: 	return;
 7700:     }
 7701:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7702:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7703:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7704:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7705:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7706:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7707:     $r->print('
 7708:     <p>
 7709: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7710: 	      '<a href="'.$orig.'">','</a>').'
 7711:     </p>
 7712:     <p>
 7713: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7714: 	      '<a href="'.$corrected.'">','</a>').'
 7715:     </p>
 7716:     <p>
 7717: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7718: 	      '<a href="'.$skipped.'">','</a>').'
 7719:     </p>
 7720: ');
 7721:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7722:     return '';
 7723: }
 7724: 
 7725: =pod
 7726: 
 7727: =back
 7728: 
 7729: =cut
 7730: 
 7731: #-------- end of section for handling grading scantron forms -------
 7732: #
 7733: #-------------------------------------------------------------------
 7734: 
 7735: #-------------------------- Menu interface -------------------------
 7736: #
 7737: #--- Show a Grading Menu button - Calls the next routine ---
 7738: sub show_grading_menu_form {
 7739:     my ($symb)=@_;
 7740:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7741: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7742: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7743: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7744: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 7745: 	'</form>'."\n";
 7746:     return $result;
 7747: }
 7748: 
 7749: # -- Retrieve choices for grading form
 7750: sub savedState {
 7751:     my %savedState = ();
 7752:     if ($env{'form.saveState'}) {
 7753: 	foreach (split(/:/,$env{'form.saveState'})) {
 7754: 	    my ($key,$value) = split(/=/,$_,2);
 7755: 	    $savedState{$key} = $value;
 7756: 	}
 7757:     }
 7758:     return \%savedState;
 7759: }
 7760: 
 7761: sub grading_menu {
 7762:     my ($request) = @_;
 7763:     my ($symb)=&get_symb($request);
 7764:     if (!$symb) {return '';}
 7765:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7766:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7767: 
 7768:     $request->print($table);
 7769:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7770:                   'handgrade'=>$hdgrade,
 7771:                   'probTitle'=>$probTitle,
 7772:                   'command'=>'submit_options',
 7773:                   'saveState'=>"",
 7774:                   'gradingMenu'=>1,
 7775:                   'showgrading'=>"yes");
 7776:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7777:     my @menu = ({ url => $url,
 7778:                      name => &mt('Manual Grading/View Submissions'),
 7779:                      short_description => 
 7780:     &mt('Start the process of hand grading submissions.'),
 7781:                  });
 7782:     $fields{'command'} = 'csvform';
 7783:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7784:     push (@menu, { url => $url,
 7785:                    name => &mt('Upload Scores'),
 7786:                    short_description => 
 7787:             &mt('Specify a file containing the class scores for current resource.')});
 7788:     $fields{'command'} = 'processclicker';
 7789:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7790:     push (@menu, { url => $url,
 7791:                    name => &mt('Process Clicker'),
 7792:                    short_description => 
 7793:             &mt('Specify a file containing the clicker information for this resource.')});
 7794:     $fields{'command'} = 'scantron_selectphase';
 7795:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7796:     push (@menu, { url => $url,
 7797:                    name => &mt('Grade/Manage Scantron Forms'),
 7798:                    short_description => 
 7799:             &mt('')});
 7800:     $fields{'command'} = 'verify';
 7801:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7802:     push (@menu, { url => "",
 7803:                    name => &mt('Verify Receipt'),
 7804:                    short_description => 
 7805:             &mt('')});
 7806:     #
 7807:     # Create the menu
 7808:     my $Str;
 7809:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7810:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7811:     $Str .= '<input type="hidden" name="command" value="" />'.
 7812:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7813: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7814: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7815: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7816: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7817: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7818: 
 7819:     foreach my $menudata (@menu) {
 7820:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7821:             $Str .='    <h3><a '.
 7822:                 $menudata->{'jscript'}.
 7823:                 ' href="'.
 7824:                 $menudata->{'url'}.'" >'.
 7825:                 $menudata->{'name'}."</a></h3>\n";
 7826:         } else {
 7827:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 7828:                 $menudata->{'jscript'}.
 7829:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 7830:                 ' /> '.
 7831: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 7832:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7833:         }
 7834:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7835:             "\n";
 7836:     }
 7837:     $Str .="</form>\n";
 7838:     $request->print(<<GRADINGMENUJS);
 7839: <script type="text/javascript" language="javascript">
 7840:     function checkChoice(formname,val,cmdx) {
 7841: 	if (val <= 2) {
 7842: 	    var cmd = radioSelection(formname.radioChoice);
 7843: 	    var cmdsave = cmd;
 7844: 	} else {
 7845: 	    cmd = cmdx;
 7846: 	    cmdsave = 'submission';
 7847: 	}
 7848: 	formname.command.value = cmd;
 7849: 	if (val < 5) formname.submit();
 7850: 	if (val == 5) {
 7851: 	    if (!checkReceiptNo(formname,'notOK')) { 
 7852: 	        return false;
 7853: 	    } else {
 7854: 	        formname.submit();
 7855: 	    }
 7856: 	}
 7857:     }
 7858: 
 7859:     function checkReceiptNo(formname,nospace) {
 7860: 	var receiptNo = formname.receipt.value;
 7861: 	var checkOpt = false;
 7862: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7863: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7864: 	if (checkOpt) {
 7865: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7866: 	    formname.receipt.value = "";
 7867: 	    formname.receipt.focus();
 7868: 	    return false;
 7869: 	}
 7870: 	return true;
 7871:     }
 7872: </script>
 7873: GRADINGMENUJS
 7874:     &commonJSfunctions($request);
 7875:     return $Str;    
 7876: }
 7877: 
 7878: 
 7879: #--- Displays the submissions first page -------
 7880: sub submit_options {
 7881:     my ($request) = @_;
 7882:     my ($symb)=&get_symb($request);
 7883:     if (!$symb) {return '';}
 7884:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7885: 
 7886:     $request->print(<<GRADINGMENUJS);
 7887: <script type="text/javascript" language="javascript">
 7888:     function checkChoice(formname,val,cmdx) {
 7889: 	if (val <= 2) {
 7890: 	    var cmd = radioSelection(formname.radioChoice);
 7891: 	    var cmdsave = cmd;
 7892: 	} else {
 7893: 	    cmd = cmdx;
 7894: 	    cmdsave = 'submission';
 7895: 	}
 7896: 	formname.command.value = cmd;
 7897: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7898: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7899: 	if (val < 5) formname.submit();
 7900: 	if (val == 5) {
 7901: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7902: 	    formname.submit();
 7903: 	}
 7904: 	if (val < 7) formname.submit();
 7905:     }
 7906: 
 7907:     function checkReceiptNo(formname,nospace) {
 7908: 	var receiptNo = formname.receipt.value;
 7909: 	var checkOpt = false;
 7910: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7911: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7912: 	if (checkOpt) {
 7913: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7914: 	    formname.receipt.value = "";
 7915: 	    formname.receipt.focus();
 7916: 	    return false;
 7917: 	}
 7918: 	return true;
 7919:     }
 7920: </script>
 7921: GRADINGMENUJS
 7922:     &commonJSfunctions($request);
 7923:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7924:     my $result;
 7925:     my (undef,$sections) = &getclasslist('all','0');
 7926:     my $savedState = &savedState();
 7927:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7928:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7929:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7930:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7931: 
 7932:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7933: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7934: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7935: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7936: 	'<input type="hidden" name="command"     value="" />'."\n".
 7937: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7938: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7939: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7940: 
 7941:     $result.='
 7942:     <div class="LC_grade_select_mode">
 7943:       <div class="LC_grade_select_mode_current">
 7944:         <h2>
 7945:           '.&mt('Grade Current Resource').'
 7946:         </h2>
 7947:         <div class="LC_grade_select_mode_body">
 7948:           <div class="LC_grades_resource_info">
 7949:            '.$table.'
 7950:           </div>
 7951:           <div class="LC_grade_select_mode_selector">
 7952:              <div class="LC_grade_select_mode_selector_header">
 7953:                 '.&mt('Sections').'
 7954:              </div>
 7955:              <div class="LC_grade_select_mode_selector_body">
 7956: 	       <select name="section" multiple="multiple" size="5">'."\n";
 7957:     if (ref($sections)) {
 7958: 	foreach my $section (sort (@$sections)) {
 7959: 	    $result.='<option value="'.$section.'" '.
 7960: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 7961: 	}
 7962:     }
 7963:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7964:     $result.='
 7965:              </div>
 7966:           </div>
 7967:           <div class="LC_grade_select_mode_selector">
 7968:              <div class="LC_grade_select_mode_selector_header">
 7969:                 '.&mt('Groups').'
 7970:              </div>
 7971:              <div class="LC_grade_select_mode_selector_body">
 7972:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 7973:              </div>
 7974:           </div>
 7975:           <div class="LC_grade_select_mode_selector">
 7976:              <div class="LC_grade_select_mode_selector_header">
 7977:                 '.&mt('Access Status').'
 7978:              </div>
 7979:              <div class="LC_grade_select_mode_selector_body">
 7980:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 7981:              </div>
 7982:           </div>
 7983:           <div class="LC_grade_select_mode_selector">
 7984:              <div class="LC_grade_select_mode_selector_header">
 7985:                 '.&mt('Submission Status').'
 7986:              </div>
 7987:              <div class="LC_grade_select_mode_selector_body">
 7988:                <select name="submitonly" size="5">
 7989: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 7990: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 7991: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 7992: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 7993:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 7994:                </select>
 7995:              </div>
 7996:           </div>
 7997:           <div class="LC_grade_select_mode_type_body">
 7998:             <div class="LC_grade_select_mode_type">
 7999:               <label>
 8000:                 <input type="radio" name="radioChoice" value="submission" '.
 8001:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8002:              &mt('Select individual students to grade and view submissions.').'
 8003: 	      </label> 
 8004:             </div>
 8005:             <div class="LC_grade_select_mode_type">
 8006: 	      <label>
 8007:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8008:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8009:                     &mt('Grade all selected students in a grading table.').'
 8010:               </label>
 8011:             </div>
 8012:             <div class="LC_grade_select_mode_type">
 8013: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8014:             </div>
 8015:           </div>
 8016:         </div>
 8017:       </div>
 8018:       <div class="LC_grade_select_mode_page">
 8019:         <h2>
 8020:          '.&mt('Grade Complete Folder for One Student').'
 8021:         </h2>
 8022:         <div class="LC_grades_select_mode_body">
 8023:           <div class="LC_grade_select_mode_type_body">
 8024:             <div class="LC_grade_select_mode_type">
 8025:               <label>
 8026:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8027: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8028:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8029:               </label>
 8030:             </div>
 8031:             <div class="LC_grade_select_mode_type">
 8032: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8033:             </div>
 8034:           </div>
 8035:         </div>
 8036:       </div>
 8037:     </div>
 8038:   </form>';
 8039:     $result .= &show_grading_menu_form($symb);
 8040:     return $result;
 8041: }
 8042: 
 8043: sub reset_perm {
 8044:     undef(%perm);
 8045: }
 8046: 
 8047: sub init_perm {
 8048:     &reset_perm();
 8049:     foreach my $test_perm ('vgr','mgr','opa') {
 8050: 
 8051: 	my $scope = $env{'request.course.id'};
 8052: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8053: 
 8054: 	    $scope .= '/'.$env{'request.course.sec'};
 8055: 	    if ( $perm{$test_perm}=
 8056: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8057: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8058: 	    } else {
 8059: 		delete($perm{$test_perm});
 8060: 	    }
 8061: 	}
 8062:     }
 8063: }
 8064: 
 8065: sub gather_clicker_ids {
 8066:     my %clicker_ids;
 8067: 
 8068:     my $classlist = &Apache::loncoursedata::get_classlist();
 8069: 
 8070:     # Set up a couple variables.
 8071:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8072:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8073:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8074: 
 8075:     foreach my $student (keys(%$classlist)) {
 8076:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8077:         my $username = $classlist->{$student}->[$username_idx];
 8078:         my $domain   = $classlist->{$student}->[$domain_idx];
 8079:         my $clickers =
 8080: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8081:         foreach my $id (split(/\,/,$clickers)) {
 8082:             $id=~s/^[\#0]+//;
 8083:             $id=~s/[\-\:]//g;
 8084:             if (exists($clicker_ids{$id})) {
 8085: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8086:             } else {
 8087: 		$clicker_ids{$id}=$username.':'.$domain;
 8088:             }
 8089:         }
 8090:     }
 8091:     return %clicker_ids;
 8092: }
 8093: 
 8094: sub gather_adv_clicker_ids {
 8095:     my %clicker_ids;
 8096:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8097:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8098:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8099:     foreach my $element (sort(keys(%coursepersonnel))) {
 8100:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8101:             my ($puname,$pudom)=split(/\:/,$person);
 8102:             my $clickers =
 8103: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8104:             foreach my $id (split(/\,/,$clickers)) {
 8105: 		$id=~s/^[\#0]+//;
 8106:                 $id=~s/[\-\:]//g;
 8107: 		if (exists($clicker_ids{$id})) {
 8108: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8109: 		} else {
 8110: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8111: 		}
 8112:             }
 8113:         }
 8114:     }
 8115:     return %clicker_ids;
 8116: }
 8117: 
 8118: sub clicker_grading_parameters {
 8119:     return ('gradingmechanism' => 'scalar',
 8120:             'upfiletype' => 'scalar',
 8121:             'specificid' => 'scalar',
 8122:             'pcorrect' => 'scalar',
 8123:             'pincorrect' => 'scalar');
 8124: }
 8125: 
 8126: sub process_clicker {
 8127:     my ($r)=@_;
 8128:     my ($symb)=&get_symb($r);
 8129:     if (!$symb) {return '';}
 8130:     my $result=&checkforfile_js();
 8131:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8132:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8133:     $result.=$table;
 8134:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8135:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8136:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8137:         '.</b></td></tr>'."\n";
 8138:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8139: # Attempt to restore parameters from last session, set defaults if not present
 8140:     my %Saveable_Parameters=&clicker_grading_parameters();
 8141:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8142:                                                  \%Saveable_Parameters);
 8143:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8144:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8145:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8146:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8147: 
 8148:     my %checked;
 8149:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 8150:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8151:           $checked{$gradingmechanism}="checked='checked'";
 8152:        }
 8153:     }
 8154: 
 8155:     my $upload=&mt("Upload File");
 8156:     my $type=&mt("Type");
 8157:     my $attendance=&mt("Award points just for participation");
 8158:     my $personnel=&mt("Correctness determined from response by course personnel");
 8159:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8160:     my $pcorrect=&mt("Percentage points for correct solution");
 8161:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8162:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8163: 						   ('iclicker' => 'i>clicker',
 8164:                                                     'interwrite' => 'interwrite PRS'));
 8165:     $symb = &Apache::lonenc::check_encrypt($symb);
 8166:     $result.=<<ENDUPFORM;
 8167: <script type="text/javascript">
 8168: function sanitycheck() {
 8169: // Accept only integer percentages
 8170:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8171:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8172: // Find out grading choice
 8173:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8174:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8175:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8176:       }
 8177:    }
 8178: // By default, new choice equals user selection
 8179:    newgradingchoice=gradingchoice;
 8180: // Not good to give more points for false answers than correct ones
 8181:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8182:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8183:    }
 8184: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8185:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8186:       document.forms.gradesupload.pcorrect.value=100;
 8187:       document.forms.gradesupload.pincorrect.value=100;
 8188:    }
 8189: // If the values are different, cannot be attendance only
 8190:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8191:        (gradingchoice=='attendance')) {
 8192:        newgradingchoice='personnel';
 8193:    }
 8194: // Change grading choice to new one
 8195:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8196:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8197:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8198:       } else {
 8199:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8200:       }
 8201:    }
 8202: // Remember the old state
 8203:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8204: }
 8205: </script>
 8206: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8207: <input type="hidden" name="symb" value="$symb" />
 8208: <input type="hidden" name="command" value="processclickerfile" />
 8209: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8210: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8211: <input type="file" name="upfile" size="50" />
 8212: <br /><label>$type: $selectform</label>
 8213: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8214: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8215: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8216: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8217: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8218: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8219: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8220: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8221: </form>
 8222: ENDUPFORM
 8223:     $result.='</td></tr></table>'."\n".
 8224:              '</td></tr></table><br /><br />'."\n";
 8225:     $result.=&show_grading_menu_form($symb);
 8226:     return $result;
 8227: }
 8228: 
 8229: sub process_clicker_file {
 8230:     my ($r)=@_;
 8231:     my ($symb)=&get_symb($r);
 8232:     if (!$symb) {return '';}
 8233: 
 8234:     my %Saveable_Parameters=&clicker_grading_parameters();
 8235:     &Apache::loncommon::store_course_settings('grades_clicker',
 8236:                                               \%Saveable_Parameters);
 8237: 
 8238:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8239:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8240: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8241: 	return $result.&show_grading_menu_form($symb);
 8242:     }
 8243:     my %clicker_ids=&gather_clicker_ids();
 8244:     my %correct_ids;
 8245:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8246: 	%correct_ids=&gather_adv_clicker_ids();
 8247:     }
 8248:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8249: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8250: 	   $correct_id=~tr/a-z/A-Z/;
 8251: 	   $correct_id=~s/\s//gs;
 8252: 	   $correct_id=~s/^[\#0]+//;
 8253:            $correct_id=~s/[\-\:]//g;
 8254:            if ($correct_id) {
 8255: 	      $correct_ids{$correct_id}='specified';
 8256:            }
 8257:         }
 8258:     }
 8259:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8260: 	$result.=&mt('Score based on attendance only');
 8261:     } else {
 8262: 	my $number=0;
 8263: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8264: 	foreach my $id (sort(keys(%correct_ids))) {
 8265: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8266: 	    if ($correct_ids{$id} eq 'specified') {
 8267: 		$result.=&mt('specified');
 8268: 	    } else {
 8269: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8270: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8271: 	    }
 8272: 	    $number++;
 8273: 	}
 8274:         $result.="</p>\n";
 8275: 	if ($number==0) {
 8276: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8277: 	    return $result.&show_grading_menu_form($symb);
 8278: 	}
 8279:     }
 8280:     if (length($env{'form.upfile'}) < 2) {
 8281:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8282: 		     '<span class="LC_error">',
 8283: 		     '</span>',
 8284: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8285:         return $result.&show_grading_menu_form($symb);
 8286:     }
 8287: 
 8288: # Were able to get all the info needed, now analyze the file
 8289: 
 8290:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8291:     $symb = &Apache::lonenc::check_encrypt($symb);
 8292:     my $heading=&mt('Scanning clicker file');
 8293:     $result.=(<<ENDHEADER);
 8294: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8295: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8296: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8297: <form method="post" action="/adm/grades" name="clickeranalysis">
 8298: <input type="hidden" name="symb" value="$symb" />
 8299: <input type="hidden" name="command" value="assignclickergrades" />
 8300: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8301: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8302: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8303: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8304: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8305: ENDHEADER
 8306:     my %responses;
 8307:     my @questiontitles;
 8308:     my $errormsg='';
 8309:     my $number=0;
 8310:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8311: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8312:     }
 8313:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8314:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8315:     }
 8316:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8317:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8318:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8319:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8320:              '<br />';
 8321: # Remember Question Titles
 8322: # FIXME: Possibly need delimiter other than ":"
 8323:     for (my $i=0;$i<$number;$i++) {
 8324:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8325:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8326:     }
 8327:     my $correct_count=0;
 8328:     my $student_count=0;
 8329:     my $unknown_count=0;
 8330: # Match answers with usernames
 8331: # FIXME: Possibly need delimiter other than ":"
 8332:     foreach my $id (keys(%responses)) {
 8333:        if ($correct_ids{$id}) {
 8334:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8335:           $correct_count++;
 8336:        } elsif ($clicker_ids{$id}) {
 8337:           if ($clicker_ids{$id}=~/\,/) {
 8338: # More than one user with the same clicker!
 8339:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8340:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8341:                            "<select name='multi".$id."'>";
 8342:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8343:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8344:              }
 8345:              $result.='</select>';
 8346:              $unknown_count++;
 8347:           } else {
 8348: # Good: found one and only one user with the right clicker
 8349:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8350:              $student_count++;
 8351:           }
 8352:        } else {
 8353:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8354:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8355:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8356:                    "\n".&mt("Domain").": ".
 8357:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8358:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8359:           $unknown_count++;
 8360:        }
 8361:     }
 8362:     $result.='<hr />'.
 8363:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8364:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 8365:        if ($correct_count==0) {
 8366:           $errormsg.="Found no correct answers answers for grading!";
 8367:        } elsif ($correct_count>1) {
 8368:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8369:        }
 8370:     }
 8371:     if ($number<1) {
 8372:        $errormsg.="Found no questions.";
 8373:     }
 8374:     if ($errormsg) {
 8375:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8376:     } else {
 8377:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8378:     }
 8379:     $result.='</form></td></tr></table>'."\n".
 8380:              '</td></tr></table><br /><br />'."\n";
 8381:     return $result.&show_grading_menu_form($symb);
 8382: }
 8383: 
 8384: sub iclicker_eval {
 8385:     my ($questiontitles,$responses)=@_;
 8386:     my $number=0;
 8387:     my $errormsg='';
 8388:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8389:         my %components=&Apache::loncommon::record_sep($line);
 8390:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8391: 	if ($entries[0] eq 'Question') {
 8392: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8393: 		$$questiontitles[$number]=$entries[$i];
 8394: 		$number++;
 8395: 	    }
 8396: 	}
 8397: 	if ($entries[0]=~/^\#/) {
 8398: 	    my $id=$entries[0];
 8399: 	    my @idresponses;
 8400: 	    $id=~s/^[\#0]+//;
 8401: 	    for (my $i=0;$i<$number;$i++) {
 8402: 		my $idx=3+$i*6;
 8403: 		push(@idresponses,$entries[$idx]);
 8404: 	    }
 8405: 	    $$responses{$id}=join(',',@idresponses);
 8406: 	}
 8407:     }
 8408:     return ($errormsg,$number);
 8409: }
 8410: 
 8411: sub interwrite_eval {
 8412:     my ($questiontitles,$responses)=@_;
 8413:     my $number=0;
 8414:     my $errormsg='';
 8415:     my $skipline=1;
 8416:     my $questionnumber=0;
 8417:     my %idresponses=();
 8418:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8419:         my %components=&Apache::loncommon::record_sep($line);
 8420:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8421:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8422:         if ($entries[1] eq 'Response') { $skipline=1; }
 8423:         next if $skipline;
 8424:         if ($entries[0]!=$questionnumber) {
 8425:            $questionnumber=$entries[0];
 8426:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8427:            $number++;
 8428:         }
 8429:         my $id=$entries[4];
 8430:         $id=~s/^[\#0]+//;
 8431:         $id=~s/^v\d*\://i;
 8432:         $id=~s/[\-\:]//g;
 8433:         $idresponses{$id}[$number]=$entries[6];
 8434:     }
 8435:     foreach my $id (keys %idresponses) {
 8436:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8437:        $$responses{$id}=~s/^\s*\,//;
 8438:     }
 8439:     return ($errormsg,$number);
 8440: }
 8441: 
 8442: sub assign_clicker_grades {
 8443:     my ($r)=@_;
 8444:     my ($symb)=&get_symb($r);
 8445:     if (!$symb) {return '';}
 8446: # See which part we are saving to
 8447:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8448: # FIXME: This should probably look for the first handgradeable part
 8449:     my $part=$$partlist[0];
 8450: # Start screen output
 8451:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8452: 
 8453:     my $heading=&mt('Assigning grades based on clicker file');
 8454:     $result.=(<<ENDHEADER);
 8455: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8456: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8457: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8458: ENDHEADER
 8459: # Get correct result
 8460: # FIXME: Possibly need delimiter other than ":"
 8461:     my @correct=();
 8462:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8463:     my $number=$env{'form.number'};
 8464:     if ($gradingmechanism ne 'attendance') {
 8465:        foreach my $key (keys(%env)) {
 8466:           if ($key=~/^form\.correct\:/) {
 8467:              my @input=split(/\,/,$env{$key});
 8468:              for (my $i=0;$i<=$#input;$i++) {
 8469:                  if (($correct[$i]) && ($input[$i]) &&
 8470:                      ($correct[$i] ne $input[$i])) {
 8471:                     $result.='<br /><span class="LC_warning">'.
 8472:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8473:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8474:                  } elsif ($input[$i]) {
 8475:                     $correct[$i]=$input[$i];
 8476:                  }
 8477:              }
 8478:           }
 8479:        }
 8480:        for (my $i=0;$i<$number;$i++) {
 8481:           if (!$correct[$i]) {
 8482:              $result.='<br /><span class="LC_error">'.
 8483:                       &mt('No correct result given for question "[_1]"!',
 8484:                           $env{'form.question:'.$i}).'</span>';
 8485:           }
 8486:        }
 8487:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8488:     }
 8489: # Start grading
 8490:     my $pcorrect=$env{'form.pcorrect'};
 8491:     my $pincorrect=$env{'form.pincorrect'};
 8492:     my $storecount=0;
 8493:     foreach my $key (keys(%env)) {
 8494:        my $user='';
 8495:        if ($key=~/^form\.student\:(.*)$/) {
 8496:           $user=$1;
 8497:        }
 8498:        if ($key=~/^form\.unknown\:(.*)$/) {
 8499:           my $id=$1;
 8500:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8501:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8502:           } elsif ($env{'form.multi'.$id}) {
 8503:              $user=$env{'form.multi'.$id};
 8504:           }
 8505:        }
 8506:        if ($user) { 
 8507:           my @answer=split(/\,/,$env{$key});
 8508:           my $sum=0;
 8509:           for (my $i=0;$i<$number;$i++) {
 8510:              if ($answer[$i]) {
 8511:                 if ($gradingmechanism eq 'attendance') {
 8512:                    $sum+=$pcorrect;
 8513:                 } else {
 8514:                    if ($answer[$i] eq $correct[$i]) {
 8515:                       $sum+=$pcorrect;
 8516:                    } else {
 8517:                       $sum+=$pincorrect;
 8518:                    }
 8519:                 }
 8520:              }
 8521:           }
 8522:           my $ave=$sum/(100*$number);
 8523: # Store
 8524:           my ($username,$domain)=split(/\:/,$user);
 8525:           my %grades=();
 8526:           $grades{"resource.$part.solved"}='correct_by_override';
 8527:           $grades{"resource.$part.awarded"}=$ave;
 8528:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8529:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8530:                                                  $env{'request.course.id'},
 8531:                                                  $domain,$username);
 8532:           if ($returncode ne 'ok') {
 8533:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8534:           } else {
 8535:              $storecount++;
 8536:           }
 8537:        }
 8538:     }
 8539: # We are done
 8540:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8541:              '</td></tr></table>'."\n".
 8542:              '</td></tr></table><br /><br />'."\n";
 8543:     return $result.&show_grading_menu_form($symb);
 8544: }
 8545: 
 8546: sub handler {
 8547:     my $request=$_[0];
 8548:     &reset_caches();
 8549:     if ($env{'browser.mathml'}) {
 8550: 	&Apache::loncommon::content_type($request,'text/xml');
 8551:     } else {
 8552: 	&Apache::loncommon::content_type($request,'text/html');
 8553:     }
 8554:     $request->send_http_header;
 8555:     return '' if $request->header_only;
 8556:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8557:     my $symb=&get_symb($request,1);
 8558:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8559:     my $command=$commands[0];
 8560: 
 8561:     if ($#commands > 0) {
 8562: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8563:     }
 8564: 
 8565:     $ssi_error = 0;
 8566:     $request->print(&Apache::loncommon::start_page('Grading'));
 8567:     if ($symb eq '' && $command eq '') {
 8568: 	if ($env{'user.adv'}) {
 8569: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8570: 		($env{'form.codethree'})) {
 8571: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8572: 		    $env{'form.codethree'};
 8573: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8574: 		    &Apache::lonnet::checkin($token);
 8575: 		if ($tsymb) {
 8576: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8577: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8578: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8579: 					  ('grade_username' => $tuname,
 8580: 					   'grade_domain' => $tudom,
 8581: 					   'grade_courseid' => $tcrsid,
 8582: 					   'grade_symb' => $tsymb)));
 8583: 		    } else {
 8584: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8585: 		    }
 8586: 		} else {
 8587: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8588: 		}
 8589: 	    } else {
 8590: 		$request->print(&Apache::lonxml::tokeninputfield());
 8591: 	    }
 8592: 	}
 8593:     } else {
 8594: 	&init_perm();
 8595: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8596: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8597: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8598: 	    &pickStudentPage($request);
 8599: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8600: 	    &displayPage($request);
 8601: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8602: 	    &updateGradeByPage($request);
 8603: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8604: 	    &processGroup($request);
 8605: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8606: 	    $request->print(&grading_menu($request));
 8607: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8608: 	    $request->print(&submit_options($request));
 8609: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8610: 	    $request->print(&viewgrades($request));
 8611: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8612: 	    $request->print(&processHandGrade($request));
 8613: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8614: 	    $request->print(&editgrades($request));
 8615: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8616: 	    $request->print(&verifyreceipt($request));
 8617:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8618:             $request->print(&process_clicker($request));
 8619:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8620:             $request->print(&process_clicker_file($request));
 8621:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8622:             $request->print(&assign_clicker_grades($request));
 8623: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8624: 	    $request->print(&upcsvScores_form($request));
 8625: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8626: 	    $request->print(&csvupload($request));
 8627: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8628: 	    $request->print(&csvuploadmap($request));
 8629: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8630: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8631: 		$request->print(&csvuploadoptions($request));
 8632: 	    } else {
 8633: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8634: 		    $env{'form.upfile_associate'} = 'reverse';
 8635: 		} else {
 8636: 		    $env{'form.upfile_associate'} = 'forward';
 8637: 		}
 8638: 		$request->print(&csvuploadmap($request));
 8639: 	    }
 8640: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8641: 	    $request->print(&csvuploadassign($request));
 8642: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8643: 	    $request->print(&scantron_selectphase($request));
 8644:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8645:  	    $request->print(&scantron_do_warning($request));
 8646: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8647: 	    $request->print(&scantron_validate_file($request));
 8648: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8649: 	    $request->print(&scantron_process_students($request));
 8650:  	} elsif ($command eq 'scantronupload' && 
 8651:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8652: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8653:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8654:  	} elsif ($command eq 'scantronupload_save' &&
 8655:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8656: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8657:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8658:  	} elsif ($command eq 'scantron_download' &&
 8659: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8660:  	    $request->print(&scantron_download_scantron_data($request));
 8661: 	} elsif ($command) {
 8662: 	    $request->print("Access Denied ($command)");
 8663: 	}
 8664:     }
 8665:     if ($ssi_error) {
 8666: 	&ssi_print_error($request);
 8667:     }
 8668:     $request->print(&Apache::loncommon::end_page());
 8669:     &reset_caches();
 8670:     return '';
 8671: }
 8672: 
 8673: 1;
 8674: 
 8675: __END__;

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