File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.528.2.14: download - view: text, annotated - select for diffs
Wed Jun 17 18:41:31 2009 UTC (14 years, 10 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.528: preferred, unified
- Reverse one change in backports included in 1.528.2.11.
  - Change to pass @resources by reference (in 1.554) to &grade_student_bubbles() should not be part of 2.8.X.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.528.2.14 2009/06/17 18:41:31 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::lonpickcode;
   39: use Apache::loncoursedata;
   40: use Apache::lonmsg();
   41: use Apache::Constants qw(:common);
   42: use Apache::lonlocal;
   43: use Apache::lonenc;
   44: use String::Similarity;
   45: use LONCAPA;
   46: 
   47: use POSIX qw(floor);
   48: 
   49: 
   50: 
   51: my %perm=();
   52: 
   53: #  These variables are used to recover from ssi errors
   54: 
   55: my $ssi_retries = 5;
   56: my $ssi_error;
   57: my $ssi_error_resource;
   58: my $ssi_error_message;
   59: 
   60: 
   61: #  Do an ssi with retries:
   62: #  While I'd love to factor out this with the vesrion in lonprintout,
   63: #  that would either require a data coupling between modules, which I refuse to perpetuate
   64: #  (there's quite enough of that already), or would require the invention of another infrastructure
   65: #  I'm not quite ready to invent (e.g. an ssi_with_retry object).
   66: #
   67: # At least the logic that drives this has been pulled out into loncommon.
   68: 
   69: 
   70: #
   71: #   ssi_with_retries - Does the server side include of a resource.
   72: #                      if the ssi call returns an error we'll retry it up to
   73: #                      the number of times requested by the caller.
   74: #                      If we still have a proble, no text is appended to the
   75: #                      output and we set some global variables.
   76: #                      to indicate to the caller an SSI error occurred.  
   77: #                      All of this is supposed to deal with the issues described
   78: #                      in LonCAPA BZ 5631 see:
   79: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
   80: #                      by informing the user that this happened.
   81: #
   82: # Parameters:
   83: #   resource   - The resource to include.  This is passed directly, without
   84: #                interpretation to lonnet::ssi.
   85: #   form       - The form hash parameters that guide the interpretation of the resource
   86: #                
   87: #   retries    - Number of retries allowed before giving up completely.
   88: # Returns:
   89: #   On success, returns the rendered resource identified by the resource parameter.
   90: # Side Effects:
   91: #   The following global variables can be set:
   92: #    ssi_error                - If an unrecoverable error occurred this becomes true.
   93: #                               It is up to the caller to initialize this to false
   94: #                               if desired.
   95: #    ssi_error_resource  - If an unrecoverable error occurred, this is the value
   96: #                               of the resource that could not be rendered by the ssi
   97: #                               call.
   98: #    ssi_error_message   - The error string fetched from the ssi response
   99: #                               in the event of an error.
  100: #
  101: sub ssi_with_retries {
  102:     my ($resource, $retries, %form) = @_;
  103:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  104:     if ($response->is_error) {
  105: 	$ssi_error          = 1;
  106: 	$ssi_error_resource = $resource;
  107: 	$ssi_error_message  = $response->code . " " . $response->message;
  108:     }
  109: 
  110:     return $content;
  111: 
  112: }
  113: #
  114: #  Prodcuces an ssi retry failure error message to the user:
  115: #
  116: 
  117: sub ssi_print_error {
  118:     my ($r) = @_;
  119:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
  120:     $r->print('
  121: <br />
  122: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
  123: <p>
  124: '.&mt('Unable to retrieve a resource from a server:').'<br />
  125: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
  126: '.&mt('Error:').' '.$ssi_error_message.'
  127: </p>
  128: <p>'.
  129: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
  130: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  131: '</p>');
  132:     return;
  133: }
  134: 
  135: #
  136: # --- Retrieve the parts from the metadata file.---
  137: sub getpartlist {
  138:     my ($symb) = @_;
  139: 
  140:     my $navmap   = Apache::lonnavmaps::navmap->new();
  141:     my $res      = $navmap->getBySymb($symb);
  142:     my $partlist = $res->parts();
  143:     my $url      = $res->src();
  144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  145: 
  146:     my @stores;
  147:     foreach my $part (@{ $partlist }) {
  148: 	foreach my $key (@metakeys) {
  149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  150: 	}
  151:     }
  152:     return @stores;
  153: }
  154: 
  155: # --- Get the symbolic name of a problem and the url
  156: sub get_symb {
  157:     my ($request,$silent) = @_;
  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  160:     if ($symb eq '') { 
  161: 	if (!$silent) {
  162: 	    $request->print("Unable to handle ambiguous references:$url:.");
  163: 	    return ();
  164: 	}
  165:     }
  166:     &Apache::lonenc::check_decrypt(\$symb);
  167:     return ($symb);
  168: }
  169: 
  170: #--- Format fullname, username:domain if different for display
  171: #--- Use anywhere where the student names are listed
  172: sub nameUserString {
  173:     my ($type,$fullname,$uname,$udom) = @_;
  174:     if ($type eq 'header') {
  175: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  176:     } else {
  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  179:     }
  180: }
  181: 
  182: #--- Get the partlist and the response type for a given problem. ---
  183: #--- Indicate if a response type is coded handgraded or not. ---
  184: sub response_type {
  185:     my ($symb) = shift;
  186: 
  187:     my $navmap = Apache::lonnavmaps::navmap->new();
  188:     my $res = $navmap->getBySymb($symb);
  189:     my $partlist = $res->parts();
  190:     my %vPart = 
  191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  192:     my (%response_types,%handgrade);
  193:     foreach my $part (@{ $partlist }) {
  194: 	next if (%vPart && !exists($vPart{$part}));
  195: 
  196: 	my @types = $res->responseType($part);
  197: 	my @ids = $res->responseIds($part);
  198: 	for (my $i=0; $i < scalar(@ids); $i++) {
  199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  200: 	    $handgrade{$part.'_'.$ids[$i]} = 
  201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  202: 				     '.handgrade',$symb);
  203: 	}
  204:     }
  205:     return ($partlist,\%handgrade,\%response_types);
  206: }
  207: 
  208: sub flatten_responseType {
  209:     my ($responseType) = @_;
  210:     my @part_response_id =
  211: 	map { 
  212: 	    my $part = $_;
  213: 	    map {
  214: 		[$part,$_]
  215: 		} sort(keys(%{ $responseType->{$part} }));
  216: 	} sort(keys(%$responseType));
  217:     return @part_response_id;
  218: }
  219: 
  220: sub get_display_part {
  221:     my ($partID,$symb)=@_;
  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  223:     if (defined($display) and $display ne '') {
  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  225:     } else {
  226: 	$display=$partID;
  227:     }
  228:     return $display;
  229: }
  230: 
  231: #--- Show resource title
  232: #--- and parts and response type
  233: sub showResourceInfo {
  234:     my ($symb,$probTitle,$checkboxes) = @_;
  235:     my $col=3;
  236:     if ($checkboxes) { $col=4; }
  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  238:     $result .='<table border="0">';
  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  240:     my %resptype = ();
  241:     my $hdgrade='no';
  242:     my %partsseen;
  243:     foreach my $partID (sort(keys(%$responseType))) {
  244: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  246: 	    my $responsetype = $responseType->{$partID}->{$resID};
  247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  248: 	    $result.='<tr>';
  249: 	    if ($checkboxes) {
  250: 		if (exists($partsseen{$partID})) {
  251: 		    $result.="<td>&nbsp;</td>";
  252: 		} else {
  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  254: 		}
  255: 		$partsseen{$partID}=1;
  256: 	    }
  257: 	    my $display_part=&get_display_part($partID,$symb);
  258: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
  259:                      ' <span class="LC_internal_info">'.$resID.'</span></td>'.
  260: 		     '<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
  261: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  262: 	}
  263:     }
  264:     $result.='</table>'."\n";
  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  266: }
  267: 
  268: sub reset_caches {
  269:     &reset_analyze_cache();
  270:     &reset_perm();
  271: }
  272: 
  273: {
  274:     my %analyze_cache;
  275: 
  276:     sub reset_analyze_cache {
  277: 	undef(%analyze_cache);
  278:     }
  279: 
  280:     sub get_analyze {
  281: 	my ($symb,$uname,$udom,$no_increment)=@_;
  282: 	my $key = "$symb\0$uname\0$udom";
  283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  284: 
  285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  286: 	$url=&Apache::lonnet::clutter($url);
  287: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  288: 					   ('grade_target' => 'analyze',
  289: 					    'grade_domain' => $udom,
  290: 					    'grade_symb' => $symb,
  291: 					    'grade_courseid' => 
  292: 					    $env{'request.course.id'},
  293: 					    'grade_username' => $uname,
  294:                                             'grade_noincrement' => $no_increment));
  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  297: 	return $analyze_cache{$key} = \%analyze;
  298:     }
  299: 
  300:     sub get_order {
  301: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  302: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  303: 	return $analyze->{"$partid.$respid.shown"};
  304:     }
  305: 
  306:     sub get_radiobutton_correct_foil {
  307: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  308: 	my $analyze = &get_analyze($symb,$uname,$udom);
  309:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
  310:         if (ref($foils) eq 'ARRAY') {
  311:             foreach my $foil (@{$foils}) {
  312:                 if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  313:                     return $foil;
  314:                 }
  315:             }
  316:         }
  317:     }
  318: }
  319: 
  320: #--- Clean response type for display
  321: #--- Currently filters option/rank/radiobutton/match/essay/Task
  322: #        response types only.
  323: sub cleanRecord {
  324:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  325: 	$uname,$udom) = @_;
  326:     my $grayFont = '<span class="LC_internal_info">';
  327:     if ($response =~ /^(option|rank)$/) {
  328: 	my %answer=&Apache::lonnet::str2hash($answer);
  329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  330: 	my ($toprow,$bottomrow);
  331: 	foreach my $foil (@$order) {
  332: 	    if ($grading{$foil} == 1) {
  333: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  334: 	    } else {
  335: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  336: 	    }
  337: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  338: 	}
  339: 	return '<blockquote><table border="1">'.
  340: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  341: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  342: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  343:     } elsif ($response eq 'match') {
  344: 	my %answer=&Apache::lonnet::str2hash($answer);
  345: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  346: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  347: 	my ($toprow,$middlerow,$bottomrow);
  348: 	foreach my $foil (@$order) {
  349: 	    my $item=shift(@items);
  350: 	    if ($grading{$foil} == 1) {
  351: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  352: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  353: 	    } else {
  354: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  355: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  356: 	    }
  357: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  358: 	}
  359: 	return '<blockquote><table border="1">'.
  360: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  361: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  362: 	    $middlerow.'</tr>'.
  363: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  364: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  365:     } elsif ($response eq 'radiobutton') {
  366: 	my %answer=&Apache::lonnet::str2hash($answer);
  367: 	my ($toprow,$bottomrow);
  368: 	my $correct = 
  369: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  370: 	foreach my $foil (@$order) {
  371: 	    if (exists($answer{$foil})) {
  372: 		if ($foil eq $correct) {
  373: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  374: 		} else {
  375: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  376: 		}
  377: 	    } else {
  378: 		$toprow.='<td>'.&mt('false').'</td>';
  379: 	    }
  380: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  381: 	}
  382: 	return '<blockquote><table border="1">'.
  383: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  384: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  385: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  386:     } elsif ($response eq 'essay') {
  387: 	if (! exists ($env{'form.'.$symb})) {
  388: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  389: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  390: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  391: 
  392: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  393: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  394: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  395: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  396: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  397: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  398: 	}
  399: 	$answer =~ s-\n-<br />-g;
  400: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  401:     } elsif ( $response eq 'organic') {
  402: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  403: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  404: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  405: 	return $result;
  406:     } elsif ( $response eq 'Task') {
  407: 	if ( $answer eq 'SUBMITTED') {
  408: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  409: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  410: 	    return $result;
  411: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  412: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  413: 			       keys(%{$record}));
  414: 	    return join('<br />',($version,@matches));
  415: 			       
  416: 			       
  417: 	} else {
  418: 	    my $result =
  419: 		'<p>'
  420: 		.&mt('Overall result: [_1]',
  421: 		     $record->{$version."resource.$respid.$partid.status"})
  422: 		.'</p>';
  423: 	    
  424: 	    $result .= '<ul>';
  425: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  426: 			     keys(%{$record}));
  427: 	    foreach my $grade (sort(@grade)) {
  428: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  429: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  430: 				     $dim, $record->{$grade}).
  431: 			  '</li>';
  432: 	    }
  433: 	    $result.='</ul>';
  434: 	    return $result;
  435: 	}
  436:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  437: 	$answer = 
  438: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  439: 							      $answer);
  440:     }
  441:     return $answer;
  442: }
  443: 
  444: #-- A couple of common js functions
  445: sub commonJSfunctions {
  446:     my $request = shift;
  447:     $request->print(<<COMMONJSFUNCTIONS);
  448: <script type="text/javascript" language="javascript">
  449:     function radioSelection(radioButton) {
  450: 	var selection=null;
  451: 	if (radioButton.length > 1) {
  452: 	    for (var i=0; i<radioButton.length; i++) {
  453: 		if (radioButton[i].checked) {
  454: 		    return radioButton[i].value;
  455: 		}
  456: 	    }
  457: 	} else {
  458: 	    if (radioButton.checked) return radioButton.value;
  459: 	}
  460: 	return selection;
  461:     }
  462: 
  463:     function pullDownSelection(selectOne) {
  464: 	var selection="";
  465: 	if (selectOne.length > 1) {
  466: 	    for (var i=0; i<selectOne.length; i++) {
  467: 		if (selectOne[i].selected) {
  468: 		    return selectOne[i].value;
  469: 		}
  470: 	    }
  471: 	} else {
  472:             // only one value it must be the selected one
  473: 	    return selectOne.value;
  474: 	}
  475:     }
  476: </script>
  477: COMMONJSFUNCTIONS
  478: }
  479: 
  480: #--- Dumps the class list with usernames,list of sections,
  481: #--- section, ids and fullnames for each user.
  482: sub getclasslist {
  483:     my ($getsec,$filterlist,$getgroup) = @_;
  484:     my @getsec;
  485:     my @getgroup;
  486:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  487:     if (!ref($getsec)) {
  488: 	if ($getsec ne '' && $getsec ne 'all') {
  489: 	    @getsec=($getsec);
  490: 	}
  491:     } else {
  492: 	@getsec=@{$getsec};
  493:     }
  494:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  495:     if (!ref($getgroup)) {
  496: 	if ($getgroup ne '' && $getgroup ne 'all') {
  497: 	    @getgroup=($getgroup);
  498: 	}
  499:     } else {
  500: 	@getgroup=@{$getgroup};
  501:     }
  502:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  503: 
  504:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  505:     # Bail out if we were unable to get the classlist
  506:     return if (! defined($classlist));
  507:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  508:     #
  509:     my %sections;
  510:     my %fullnames;
  511:     foreach my $student (keys(%$classlist)) {
  512:         my $end      = 
  513:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  514:         my $start    = 
  515:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  516:         my $id       = 
  517:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  518:         my $section  = 
  519:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  520:         my $fullname = 
  521:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  522:         my $status   = 
  523:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  524:         my $group   = 
  525:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  526: 	# filter students according to status selected
  527: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  528: 	    if (!($stu_status =~ $status)) {
  529: 		delete($classlist->{$student});
  530: 		next;
  531: 	    }
  532: 	}
  533: 	# filter students according to groups selected
  534: 	my @stu_groups = split(/,/,$group);
  535: 	if (@getgroup) {
  536: 	    my $exclude = 1;
  537: 	    foreach my $grp (@getgroup) {
  538: 	        foreach my $stu_group (@stu_groups) {
  539: 	            if ($stu_group eq $grp) {
  540: 	                $exclude = 0;
  541:     	            } 
  542: 	        }
  543:     	        if (($grp eq 'none') && !$group) {
  544:         	        $exclude = 0;
  545:         	}
  546: 	    }
  547: 	    if ($exclude) {
  548: 	        delete($classlist->{$student});
  549: 	    }
  550: 	}
  551: 	$section = ($section ne '' ? $section : 'none');
  552: 	if (&canview($section)) {
  553: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  554: 		$sections{$section}++;
  555: 		if ($classlist->{$student}) {
  556: 		    $fullnames{$student}=$fullname;
  557: 		}
  558: 	    } else {
  559: 		delete($classlist->{$student});
  560: 	    }
  561: 	} else {
  562: 	    delete($classlist->{$student});
  563: 	}
  564:     }
  565:     my %seen = ();
  566:     my @sections = sort(keys(%sections));
  567:     return ($classlist,\@sections,\%fullnames);
  568: }
  569: 
  570: sub canmodify {
  571:     my ($sec)=@_;
  572:     if ($perm{'mgr'}) {
  573: 	if (!defined($perm{'mgr_section'})) {
  574: 	    # can modify whole class
  575: 	    return 1;
  576: 	} else {
  577: 	    if ($sec eq $perm{'mgr_section'}) {
  578: 		#can modify the requested section
  579: 		return 1;
  580: 	    } else {
  581: 		# can't modify the request section
  582: 		return 0;
  583: 	    }
  584: 	}
  585:     }
  586:     #can't modify
  587:     return 0;
  588: }
  589: 
  590: sub canview {
  591:     my ($sec)=@_;
  592:     if ($perm{'vgr'}) {
  593: 	if (!defined($perm{'vgr_section'})) {
  594: 	    # can modify whole class
  595: 	    return 1;
  596: 	} else {
  597: 	    if ($sec eq $perm{'vgr_section'}) {
  598: 		#can modify the requested section
  599: 		return 1;
  600: 	    } else {
  601: 		# can't modify the request section
  602: 		return 0;
  603: 	    }
  604: 	}
  605:     }
  606:     #can't modify
  607:     return 0;
  608: }
  609: 
  610: #--- Retrieve the grade status of a student for all the parts
  611: sub student_gradeStatus {
  612:     my ($symb,$udom,$uname,$partlist) = @_;
  613:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  614:     my %partstatus = ();
  615:     foreach (@$partlist) {
  616: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  617: 	$status              = 'nothing' if ($status eq '');
  618: 	$partstatus{$_}      = $status;
  619: 	my $subkey           = "resource.$_.submitted_by";
  620: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  621:     }
  622:     return %partstatus;
  623: }
  624: 
  625: # hidden form and javascript that calls the form
  626: # Use by verifyscript and viewgrades
  627: # Shows a student's view of problem and submission
  628: sub jscriptNform {
  629:     my ($symb) = @_;
  630:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  631:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  632: 	'    function viewOneStudent(user,domain) {'."\n".
  633: 	'	document.onestudent.student.value = user;'."\n".
  634: 	'	document.onestudent.userdom.value = domain;'."\n".
  635: 	'	document.onestudent.submit();'."\n".
  636: 	'    }'."\n".
  637: 	'</script>'."\n";
  638:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  640: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  641: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  643: 	'<input type="hidden" name="command" value="submission" />'."\n".
  644: 	'<input type="hidden" name="student" value="" />'."\n".
  645: 	'<input type="hidden" name="userdom" value="" />'."\n".
  646: 	'</form>'."\n";
  647:     return $jscript;
  648: }
  649: 
  650: 
  651: 
  652: # Given the score (as a number [0-1] and the weight) what is the final
  653: # point value? This function will round to the nearest tenth, third,
  654: # or quarter if one of those is within the tolerance of .00001.
  655: sub compute_points {
  656:     my ($score, $weight) = @_;
  657:     
  658:     my $tolerance = .00001;
  659:     my $points = $score * $weight;
  660: 
  661:     # Check for nearness to 1/x.
  662:     my $check_for_nearness = sub {
  663:         my ($factor) = @_;
  664:         my $num = ($points * $factor) + $tolerance;
  665:         my $floored_num = floor($num);
  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  667:             return $floored_num / $factor;
  668:         }
  669:         return $points;
  670:     };
  671: 
  672:     $points = $check_for_nearness->(10);
  673:     $points = $check_for_nearness->(3);
  674:     $points = $check_for_nearness->(4);
  675:     
  676:     return $points;
  677: }
  678: 
  679: #------------------ End of general use routines --------------------
  680: 
  681: #
  682: # Find most similar essay
  683: #
  684: 
  685: sub most_similar {
  686:     my ($uname,$udom,$uessay,$old_essays)=@_;
  687: 
  688: # ignore spaces and punctuation
  689: 
  690:     $uessay=~s/\W+/ /gs;
  691: 
  692: # ignore empty submissions (occuring when only files are sent)
  693: 
  694:     unless ($uessay=~/\w+/) { return ''; }
  695: 
  696: # these will be returned. Do not care if not at least 50 percent similar
  697:     my $limit=0.6;
  698:     my $sname='';
  699:     my $sdom='';
  700:     my $scrsid='';
  701:     my $sessay='';
  702: # go through all essays ...
  703:     foreach my $tkey (keys(%$old_essays)) {
  704: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  705: # ... except the same student
  706:         next if (($tname eq $uname) && ($tdom eq $udom));
  707: 	my $tessay=$old_essays->{$tkey};
  708: 	$tessay=~s/\W+/ /gs;
  709: # String similarity gives up if not even limit
  710: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  711: # Found one
  712: 	if ($tsimilar>$limit) {
  713: 	    $limit=$tsimilar;
  714: 	    $sname=$tname;
  715: 	    $sdom=$tdom;
  716: 	    $scrsid=$tcrsid;
  717: 	    $sessay=$old_essays->{$tkey};
  718: 	}
  719:     }
  720:     if ($limit>0.6) {
  721:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  722:     } else {
  723:        return ('','','','',0);
  724:     }
  725: }
  726: 
  727: #-------------------------------------------------------------------
  728: 
  729: #------------------------------------ Receipt Verification Routines
  730: #
  731: #--- Check whether a receipt number is valid.---
  732: sub verifyreceipt {
  733:     my $request  = shift;
  734: 
  735:     my $courseid = $env{'request.course.id'};
  736:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  737: 	$env{'form.receipt'};
  738:     $receipt     =~ s/[^\-\d]//g;
  739:     my ($symb)   = &get_symb($request);
  740: 
  741:     my $title.=
  742: 	'<h3><span class="LC_info">'.
  743: 	&mt('Verifying Receipt No. [_1]',$receipt).
  744: 	'</span></h3>'."\n".
  745: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  746: 	'</h4>'."\n";
  747: 
  748:     my ($string,$contents,$matches) = ('','',0);
  749:     my (undef,undef,$fullname) = &getclasslist('all','0');
  750:     
  751:     my $receiptparts=0;
  752:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  753: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  754:     my $parts=['0'];
  755:     if ($receiptparts) { ($parts)=&response_type($symb); }
  756:     
  757:     my $header = 
  758: 	&Apache::loncommon::start_data_table().
  759: 	&Apache::loncommon::start_data_table_header_row().
  760: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  761: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  762: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  763:     if ($receiptparts) {
  764: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  765:     }
  766:     $header.=
  767: 	&Apache::loncommon::end_data_table_header_row();
  768: 
  769:     foreach (sort 
  770: 	     {
  771: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  772: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  773: 		 }
  774: 		 return $a cmp $b;
  775: 	     } (keys(%$fullname))) {
  776: 	my ($uname,$udom)=split(/\:/);
  777: 	foreach my $part (@$parts) {
  778: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  779: 		$contents.=
  780: 		    &Apache::loncommon::start_data_table_row().
  781: 		    '<td>&nbsp;'."\n".
  782: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  783: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  784: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  785: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  786: 		if ($receiptparts) {
  787: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  788: 		}
  789: 		$contents.= 
  790: 		    &Apache::loncommon::end_data_table_row()."\n";
  791: 		
  792: 		$matches++;
  793: 	    }
  794: 	}
  795:     }
  796:     if ($matches == 0) {
  797: 	$string = $title.&mt('No match found for the above receipt.');
  798:     } else {
  799: 	$string = &jscriptNform($symb).$title.
  800: 	    '<p>'.
  801: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  802: 	    '</p>'.
  803: 	    $header.
  804: 	    $contents.
  805: 	    &Apache::loncommon::end_data_table()."\n";
  806:     }
  807:     return $string.&show_grading_menu_form($symb);
  808: }
  809: 
  810: #--- This is called by a number of programs.
  811: #--- Called from the Grading Menu - View/Grade an individual student
  812: #--- Also called directly when one clicks on the subm button 
  813: #    on the problem page.
  814: sub listStudents {
  815:     my ($request) = shift;
  816: 
  817:     my ($symb) = &get_symb($request);
  818:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  819:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  820:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  821:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  822:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  823:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  824:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  825: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  826: 
  827:     my $result='<h3><span class="LC_info">&nbsp;'.
  828: 	&mt("$viewgrade Submissions for a Student or a Group of Students")
  829: 	.'</span></h3>';
  830: 
  831:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  832: 
  833:     my %lt = &Apache::lonlocal::texthash (
  834:                 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
  835:                 'single'   => 'Please select the student before clicking on the Next button.',
  836:              );
  837:     $request->print(<<LISTJAVASCRIPT);
  838: <script type="text/javascript" language="javascript">
  839:     function checkSelect(checkBox) {
  840: 	var ctr=0;
  841: 	var sense="";
  842: 	if (checkBox.length > 1) {
  843: 	    for (var i=0; i<checkBox.length; i++) {
  844: 		if (checkBox[i].checked) {
  845: 		    ctr++;
  846: 		}
  847: 	    }
  848: 	    sense = '$lt{'multiple'}';
  849: 	} else {
  850: 	    if (checkBox.checked) {
  851: 		ctr = 1;
  852: 	    }
  853: 	    sense = '$lt{'single'}';
  854: 	}
  855: 	if (ctr == 0) {
  856: 	    alert(sense);
  857: 	    return false;
  858: 	}
  859: 	document.gradesub.submit();
  860:     }
  861: 
  862:     function reLoadList(formname) {
  863: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  864: 	formname.command.value = 'submission';
  865: 	formname.submit();
  866:     }
  867: </script>
  868: LISTJAVASCRIPT
  869: 
  870:     &commonJSfunctions($request);
  871:     $request->print($result);
  872: 
  873:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  874:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  875:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  876: 	"\n".$table;
  877: 	
  878:     $gradeTable .= 
  879: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
  880: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  881: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
  882: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
  883:     $gradeTable .= 
  884: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
  885: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
  886: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
  887: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
  888: 
  889:     my $submission_options;
  890:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  891: 	$submission_options.=
  892: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
  893:     }
  894:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  895:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  896:     $env{'form.Status'} = $saveStatus;
  897:     $submission_options.=
  898: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
  899: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
  900: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
  901: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
  902:     $gradeTable .= 
  903: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
  904: 
  905:     $gradeTable .= 
  906:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
  907: 	    '<select name="increment">'.
  908: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
  909: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
  910: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
  911: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
  912: 	    '</select>';
  913:     
  914:     $gradeTable .= 
  915:         &build_section_inputs().
  916: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  917: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  918: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  919: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  920: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  921: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  922: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  923: 
  924:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  925: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  926:     } else {
  927: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
  928: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
  929:     }
  930: 
  931:     $gradeTable.=&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.").'<br />'."\n".
  932: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  933: 
  934: # checkall buttons
  935:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  936:     $gradeTable.='<input type="button" '."\n".
  937: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  938: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
  939:     $gradeTable.=&check_buttons();
  940:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  942:     $gradeTable.= &Apache::loncommon::start_data_table().
  943: 	&Apache::loncommon::start_data_table_header_row();
  944:     my $loop = 0;
  945:     while ($loop < 2) {
  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
  947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
  948: 	if ($env{'form.showgrading'} eq 'yes' 
  949: 	    && $submitonly ne 'queued'
  950: 	    && $submitonly ne 'all') {
  951: 	    foreach my $part (sort(@$partlist)) {
  952: 		my $display_part=
  953: 		    &get_display_part((split(/_/,$part))[0],$symb);
  954: 		$gradeTable.=
  955: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
  956: 	    }
  957: 	} elsif ($submitonly eq 'queued') {
  958: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
  959: 	}
  960: 	$loop++;
  961: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  962:     }
  963:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
  964: 
  965:     my $ctr = 0;
  966:     foreach my $student (sort 
  967: 			 {
  968: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  969: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  970: 			     }
  971: 			     return $a cmp $b;
  972: 			 }
  973: 			 (keys(%$fullname))) {
  974: 	my ($uname,$udom) = split(/:/,$student);
  975: 
  976: 	my %status = ();
  977: 
  978: 	if ($submitonly eq 'queued') {
  979: 	    my %queue_status = 
  980: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  981: 							$udom,$uname);
  982: 	    next if (!defined($queue_status{'gradingqueue'}));
  983: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  984: 	}
  985: 
  986: 	if ($env{'form.showgrading'} eq 'yes' 
  987: 	    && $submitonly ne 'queued'
  988: 	    && $submitonly ne 'all') {
  989: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  990: 	    my $submitted = 0;
  991: 	    my $graded = 0;
  992: 	    my $incorrect = 0;
  993: 	    foreach (keys(%status)) {
  994: 		$submitted = 1 if ($status{$_} ne 'nothing');
  995: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  996: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  997: 		
  998: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  999: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1000: 		    $submitted = 0;
 1001: 		    my ($part)=split(/\./,$partid);
 1002: 		    $gradeTable.='<input type="hidden" name="'.
 1003: 			$student.':'.$part.':submitted_by" value="'.
 1004: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1005: 		}
 1006: 	    }
 1007: 	    
 1008: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1009: 				     $submitonly eq 'incorrect' ||
 1010: 				     $submitonly eq 'graded'));
 1011: 	    next if (!$graded && ($submitonly eq 'graded'));
 1012: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1013: 	}
 1014: 
 1015: 	$ctr++;
 1016: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1017:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1018: 	if ( $perm{'vgr'} eq 'F' ) {
 1019: 	    if ($ctr%2 ==1) {
 1020: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1021: 	    }
 1022: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1023:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1024:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1025: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1026: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1027: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1028: 
 1029: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1030: 		foreach (sort(keys(%status))) {
 1031: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1032: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1033: 		}
 1034: 	    }
 1035: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1036: 	    if ($ctr%2 ==0) {
 1037: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1038: 	    }
 1039: 	}
 1040:     }
 1041:     if ($ctr%2 ==1) {
 1042: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1043: 	    if ($env{'form.showgrading'} eq 'yes' 
 1044: 		&& $submitonly ne 'queued'
 1045: 		&& $submitonly ne 'all') {
 1046: 		foreach (@$partlist) {
 1047: 		    $gradeTable.='<td>&nbsp;</td>';
 1048: 		}
 1049: 	    } elsif ($submitonly eq 'queued') {
 1050: 		$gradeTable.='<td>&nbsp;</td>';
 1051: 	    }
 1052: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1053:     }
 1054: 
 1055:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1056: 	'<input type="button" '.
 1057: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1058: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
 1059:     if ($ctr == 0) {
 1060: 	my $num_students=(scalar(keys(%$fullname)));
 1061: 	if ($num_students eq 0) {
 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1063: 	} else {
 1064: 	    my $submissions='submissions';
 1065: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1066: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1067: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1068: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1069: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1070: 		    $num_students).
 1071: 		'</span><br />';
 1072: 	}
 1073:     } elsif ($ctr == 1) {
 1074: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1075:     }
 1076:     $gradeTable.=&show_grading_menu_form($symb);
 1077:     $request->print($gradeTable);
 1078:     return '';
 1079: }
 1080: 
 1081: #---- Called from the listStudents routine
 1082: 
 1083: sub check_script {
 1084:     my ($form, $type)=@_;
 1085:     my $chkallscript='<script type="text/javascript">
 1086:     function checkall() {
 1087:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1088:             ele = document.forms.'.$form.'.elements[i];
 1089:             if (ele.name == "'.$type.'") {
 1090:             document.forms.'.$form.'.elements[i].checked=true;
 1091:                                        }
 1092:         }
 1093:     }
 1094: 
 1095:     function checksec() {
 1096:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1097:             ele = document.forms.'.$form.'.elements[i];
 1098:            string = document.forms.'.$form.'.chksec.value;
 1099:            if
 1100:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1101:               document.forms.'.$form.'.elements[i].checked=true;
 1102:             }
 1103:         }
 1104:     }
 1105: 
 1106: 
 1107:     function uncheckall() {
 1108:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1109:             ele = document.forms.'.$form.'.elements[i];
 1110:             if (ele.name == "'.$type.'") {
 1111:             document.forms.'.$form.'.elements[i].checked=false;
 1112:                                        }
 1113:         }
 1114:     }
 1115: 
 1116: </script>'."\n";
 1117:     return $chkallscript;
 1118: }
 1119: 
 1120: sub check_buttons {
 1121:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1122:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1123:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1124:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1125:     return $buttons;
 1126: }
 1127: 
 1128: #     Displays the submissions for one student or a group of students
 1129: sub processGroup {
 1130:     my ($request)  = shift;
 1131:     my $ctr        = 0;
 1132:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1133:     my $total      = scalar(@stuchecked)-1;
 1134: 
 1135:     foreach my $student (@stuchecked) {
 1136: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1137: 	$env{'form.student'}        = $uname;
 1138: 	$env{'form.userdom'}        = $udom;
 1139: 	$env{'form.fullname'}       = $fullname;
 1140: 	&submission($request,$ctr,$total);
 1141: 	$ctr++;
 1142:     }
 1143:     return '';
 1144: }
 1145: 
 1146: #------------------------------------------------------------------------------------
 1147: #
 1148: #-------------------------- Next few routines handles grading by student, essentially
 1149: #                           handles essay response type problem/part
 1150: #
 1151: #--- Javascript to handle the submission page functionality ---
 1152: sub sub_page_js {
 1153:     my $request = shift;
 1154:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 1155:     $request->print(<<SUBJAVASCRIPT);
 1156: <script type="text/javascript" language="javascript">
 1157:     function updateRadio(formname,id,weight) {
 1158: 	var gradeBox = formname["GD_BOX"+id];
 1159: 	var radioButton = formname["RADVAL"+id];
 1160: 	var oldpts = formname["oldpts"+id].value;
 1161: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1162: 	gradeBox.value = pts;
 1163: 	var resetbox = false;
 1164: 	if (isNaN(pts) || pts < 0) {
 1165: 	    alert("$alertmsg"+pts);
 1166: 	    for (var i=0; i<radioButton.length; i++) {
 1167: 		if (radioButton[i].checked) {
 1168: 		    gradeBox.value = i;
 1169: 		    resetbox = true;
 1170: 		}
 1171: 	    }
 1172: 	    if (!resetbox) {
 1173: 		formtextbox.value = "";
 1174: 	    }
 1175: 	    return;
 1176: 	}
 1177: 
 1178: 	if (pts > weight) {
 1179: 	    var resp = confirm("You entered a value ("+pts+
 1180: 			       ") greater than the weight for the part. Accept?");
 1181: 	    if (resp == false) {
 1182: 		gradeBox.value = oldpts;
 1183: 		return;
 1184: 	    }
 1185: 	}
 1186: 
 1187: 	for (var i=0; i<radioButton.length; i++) {
 1188: 	    radioButton[i].checked=false;
 1189: 	    if (pts == i && pts != "") {
 1190: 		radioButton[i].checked=true;
 1191: 	    }
 1192: 	}
 1193: 	updateSelect(formname,id);
 1194: 	formname["stores"+id].value = "0";
 1195:     }
 1196: 
 1197:     function writeBox(formname,id,pts) {
 1198: 	var gradeBox = formname["GD_BOX"+id];
 1199: 	if (checkSolved(formname,id) == 'update') {
 1200: 	    gradeBox.value = pts;
 1201: 	} else {
 1202: 	    var oldpts = formname["oldpts"+id].value;
 1203: 	    gradeBox.value = oldpts;
 1204: 	    var radioButton = formname["RADVAL"+id];
 1205: 	    for (var i=0; i<radioButton.length; i++) {
 1206: 		radioButton[i].checked=false;
 1207: 		if (i == oldpts) {
 1208: 		    radioButton[i].checked=true;
 1209: 		}
 1210: 	    }
 1211: 	}
 1212: 	formname["stores"+id].value = "0";
 1213: 	updateSelect(formname,id);
 1214: 	return;
 1215:     }
 1216: 
 1217:     function clearRadBox(formname,id) {
 1218: 	if (checkSolved(formname,id) == 'noupdate') {
 1219: 	    updateSelect(formname,id);
 1220: 	    return;
 1221: 	}
 1222: 	gradeSelect = formname["GD_SEL"+id];
 1223: 	for (var i=0; i<gradeSelect.length; i++) {
 1224: 	    if (gradeSelect[i].selected) {
 1225: 		var selectx=i;
 1226: 	    }
 1227: 	}
 1228: 	var stores = formname["stores"+id];
 1229: 	if (selectx == stores.value) { return };
 1230: 	var gradeBox = formname["GD_BOX"+id];
 1231: 	gradeBox.value = "";
 1232: 	var radioButton = formname["RADVAL"+id];
 1233: 	for (var i=0; i<radioButton.length; i++) {
 1234: 	    radioButton[i].checked=false;
 1235: 	}
 1236: 	stores.value = selectx;
 1237:     }
 1238: 
 1239:     function checkSolved(formname,id) {
 1240: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1241: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1242: 	    if (!reply) {return "noupdate";}
 1243: 	    formname.overRideScore.value = 'yes';
 1244: 	}
 1245: 	return "update";
 1246:     }
 1247: 
 1248:     function updateSelect(formname,id) {
 1249: 	formname["GD_SEL"+id][0].selected = true;
 1250: 	return;
 1251:     }
 1252: 
 1253: //=========== Check that a point is assigned for all the parts  ============
 1254:     function checksubmit(formname,val,total,parttot) {
 1255: 	formname.gradeOpt.value = val;
 1256: 	if (val == "Save & Next") {
 1257: 	    for (i=0;i<=total;i++) {
 1258: 		for (j=0;j<parttot;j++) {
 1259: 		    var partid = formname["partid"+i+"_"+j].value;
 1260: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1261: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1262: 			if (points == "") {
 1263: 			    var name = formname["name"+i].value;
 1264: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1265: 			    var resp = confirm("You did not assign a score for "+studentID+
 1266: 					       ", part "+partid+". Continue?");
 1267: 			    if (resp == false) {
 1268: 				formname["GD_BOX"+i+"_"+partid].focus();
 1269: 				return false;
 1270: 			    }
 1271: 			}
 1272: 		    }
 1273: 		    
 1274: 		}
 1275: 	    }
 1276: 	    
 1277: 	}
 1278: 	if (val == "Grade Student") {
 1279: 	    formname.showgrading.value = "yes";
 1280: 	    if (formname.Status.value == "") {
 1281: 		formname.Status.value = "Active";
 1282: 	    }
 1283: 	    formname.studentNo.value = total;
 1284: 	}
 1285: 	formname.submit();
 1286:     }
 1287: 
 1288: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1289:     function checkSubmitPage(formname,total) {
 1290: 	noscore = new Array(100);
 1291: 	var ptr = 0;
 1292: 	for (i=1;i<total;i++) {
 1293: 	    var partid = formname["q_"+i].value;
 1294: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1295: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1296: 		var status = formname["solved"+i+"_"+partid].value;
 1297: 		if (points == "" && status != "correct_by_student") {
 1298: 		    noscore[ptr] = i;
 1299: 		    ptr++;
 1300: 		}
 1301: 	    }
 1302: 	}
 1303: 	if (ptr != 0) {
 1304: 	    var sense = ptr == 1 ? ": " : "s: ";
 1305: 	    var prolist = "";
 1306: 	    if (ptr == 1) {
 1307: 		prolist = noscore[0];
 1308: 	    } else {
 1309: 		var i = 0;
 1310: 		while (i < ptr-1) {
 1311: 		    prolist += noscore[i]+", ";
 1312: 		    i++;
 1313: 		}
 1314: 		prolist += "and "+noscore[i];
 1315: 	    }
 1316: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1317: 	    if (resp == false) {
 1318: 		return false;
 1319: 	    }
 1320: 	}
 1321: 
 1322: 	formname.submit();
 1323:     }
 1324: </script>
 1325: SUBJAVASCRIPT
 1326: }
 1327: 
 1328: #--- javascript for essay type problem --
 1329: sub sub_page_kw_js {
 1330:     my $request = shift;
 1331:     my $iconpath = $request->dir_config('lonIconsURL');
 1332:     &commonJSfunctions($request);
 1333: 
 1334:     my $inner_js_msg_central=<<INNERJS;
 1335:     <script text="text/javascript">
 1336:     function checkInput() {
 1337:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1338:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1339:       var usrctr = document.msgcenter.usrctr.value;
 1340:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1341:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1342: 
 1343:       var msgchk = "";
 1344:       if (document.msgcenter.subchk.checked) {
 1345:          msgchk = "msgsub,";
 1346:       }
 1347:       var includemsg = 0;
 1348:       for (var i=1; i<=nmsg; i++) {
 1349:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1350:           var frmmsg = document.msgcenter["msg"+i];
 1351:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1352:           var showflg = opener.document.SCORE["shownOnce"+i];
 1353:           showflg.value = "1";
 1354:           var chkbox = document.msgcenter["msgn"+i];
 1355:           if (chkbox.checked) {
 1356:              msgchk += "savemsg"+i+",";
 1357:              includemsg = 1;
 1358:           }
 1359:       }
 1360:       if (document.msgcenter.newmsgchk.checked) {
 1361:          msgchk += "newmsg"+usrctr;
 1362:          includemsg = 1;
 1363:       }
 1364:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1365:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1366:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1367:       includemsg.value = msgchk;
 1368: 
 1369:       self.close()
 1370: 
 1371:     }
 1372:     </script>
 1373: INNERJS
 1374: 
 1375:     my $inner_js_highlight_central=<<INNERJS;
 1376:  <script type="text/javascript">
 1377:     function updateChoice(flag) {
 1378:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1379:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1380:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1381:       opener.document.SCORE.refresh.value = "on";
 1382:       if (opener.document.SCORE.keywords.value!=""){
 1383:          opener.document.SCORE.submit();
 1384:       }
 1385:       self.close()
 1386:     }
 1387: </script>
 1388: INNERJS
 1389: 
 1390:     my $start_page_msg_central = 
 1391:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1392: 				       {'js_ready'  => 1,
 1393: 					'only_body' => 1,
 1394: 					'bgcolor'   =>'#FFFFFF',});
 1395:     my $end_page_msg_central = 
 1396: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1397: 
 1398: 
 1399:     my $start_page_highlight_central = 
 1400:         &Apache::loncommon::start_page('Highlight Central',
 1401: 				       $inner_js_highlight_central,
 1402: 				       {'js_ready'  => 1,
 1403: 					'only_body' => 1,
 1404: 					'bgcolor'   =>'#FFFFFF',});
 1405:     my $end_page_highlight_central = 
 1406: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1407: 
 1408:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1409:     $docopen=~s/^document\.//;
 1410:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
 1411:     $request->print(<<SUBJAVASCRIPT);
 1412: <script type="text/javascript" language="javascript">
 1413: 
 1414: //===================== Show list of keywords ====================
 1415:   function keywords(formname) {
 1416:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1417:     if (nret==null) return;
 1418:     formname.keywords.value = nret;
 1419: 
 1420:     if (formname.keywords.value != "") {
 1421: 	formname.refresh.value = "on";
 1422: 	formname.submit();
 1423:     }
 1424:     return;
 1425:   }
 1426: 
 1427: //===================== Script to view submitted by ==================
 1428:   function viewSubmitter(submitter) {
 1429:     document.SCORE.refresh.value = "on";
 1430:     document.SCORE.NCT.value = "1";
 1431:     document.SCORE.unamedom0.value = submitter;
 1432:     document.SCORE.submit();
 1433:     return;
 1434:   }
 1435: 
 1436: //===================== Script to add keyword(s) ==================
 1437:   function getSel() {
 1438:     if (document.getSelection) txt = document.getSelection();
 1439:     else if (document.selection) txt = document.selection.createRange().text;
 1440:     else return;
 1441:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1442:     if (cleantxt=="") {
 1443: 	alert("$alertmsg");
 1444: 	return;
 1445:     }
 1446:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1447:     if (nret==null) return;
 1448:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1449:     if (document.SCORE.keywords.value != "") {
 1450: 	document.SCORE.refresh.value = "on";
 1451: 	document.SCORE.submit();
 1452:     }
 1453:     return;
 1454:   }
 1455: 
 1456: //====================== Script for composing message ==============
 1457:    // preload images
 1458:    img1 = new Image();
 1459:    img1.src = "$iconpath/mailbkgrd.gif";
 1460:    img2 = new Image();
 1461:    img2.src = "$iconpath/mailto.gif";
 1462: 
 1463:   function msgCenter(msgform,usrctr,fullname) {
 1464:     var Nmsg  = msgform.savemsgN.value;
 1465:     savedMsgHeader(Nmsg,usrctr,fullname);
 1466:     var subject = msgform.msgsub.value;
 1467:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1468:     re = /msgsub/;
 1469:     var shwsel = "";
 1470:     if (re.test(msgchk)) { shwsel = "checked" }
 1471:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1472:     displaySubject(checkEntities(subject),shwsel);
 1473:     for (var i=1; i<=Nmsg; i++) {
 1474: 	var testmsg = "savemsg"+i+",";
 1475: 	re = new RegExp(testmsg,"g");
 1476: 	shwsel = "";
 1477: 	if (re.test(msgchk)) { shwsel = "checked" }
 1478: 	var message = document.SCORE["savemsg"+i].value;
 1479: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1480: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1481: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1482:     }
 1483:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1484:     shwsel = "";
 1485:     re = /newmsg/;
 1486:     if (re.test(msgchk)) { shwsel = "checked" }
 1487:     newMsg(newmsg,shwsel);
 1488:     msgTail(); 
 1489:     return;
 1490:   }
 1491: 
 1492:   function checkEntities(strx) {
 1493:     if (strx.length == 0) return strx;
 1494:     var orgStr = ["&", "<", ">", '"']; 
 1495:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1496:     var counter = 0;
 1497:     while (counter < 4) {
 1498: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1499: 	counter++;
 1500:     }
 1501:     return strx;
 1502:   }
 1503: 
 1504:   function strReplace(strx, orgStr, newStr) {
 1505:     return strx.split(orgStr).join(newStr);
 1506:   }
 1507: 
 1508:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1509:     var height = 70*Nmsg+250;
 1510:     var scrollbar = "no";
 1511:     if (height > 600) {
 1512: 	height = 600;
 1513: 	scrollbar = "yes";
 1514:     }
 1515:     var xpos = (screen.width-600)/2;
 1516:     xpos = (xpos < 0) ? '0' : xpos;
 1517:     var ypos = (screen.height-height)/2-30;
 1518:     ypos = (ypos < 0) ? '0' : ypos;
 1519: 
 1520:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1521:     pWin.focus();
 1522:     pDoc = pWin.document;
 1523:     pDoc.$docopen;
 1524:     pDoc.write('$start_page_msg_central');
 1525: 
 1526:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1527:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1528:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1529: 
 1530:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1531:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1532:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1533: }
 1534:     function displaySubject(msg,shwsel) {
 1535:     pDoc = pWin.document;
 1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1537:     pDoc.write("<td>Subject<\\/td>");
 1538:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1539:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1540: }
 1541: 
 1542:   function displaySavedMsg(ctr,msg,shwsel) {
 1543:     pDoc = pWin.document;
 1544:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1545:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1546:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1547:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1548: }
 1549: 
 1550:   function newMsg(newmsg,shwsel) {
 1551:     pDoc = pWin.document;
 1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1553:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1554:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1555:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1556: }
 1557: 
 1558:   function msgTail() {
 1559:     pDoc = pWin.document;
 1560:     pDoc.write("<\\/table>");
 1561:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1562:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1563:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1564:     pDoc.write("<\\/form>");
 1565:     pDoc.write('$end_page_msg_central');
 1566:     pDoc.close();
 1567: }
 1568: 
 1569: //====================== Script for keyword highlight options ==============
 1570:   function kwhighlight() {
 1571:     var kwclr    = document.SCORE.kwclr.value;
 1572:     var kwsize   = document.SCORE.kwsize.value;
 1573:     var kwstyle  = document.SCORE.kwstyle.value;
 1574:     var redsel = "";
 1575:     var grnsel = "";
 1576:     var blusel = "";
 1577:     if (kwclr=="red")   {var redsel="checked"};
 1578:     if (kwclr=="green") {var grnsel="checked"};
 1579:     if (kwclr=="blue")  {var blusel="checked"};
 1580:     var sznsel = "";
 1581:     var sz1sel = "";
 1582:     var sz2sel = "";
 1583:     if (kwsize=="0")  {var sznsel="checked"};
 1584:     if (kwsize=="+1") {var sz1sel="checked"};
 1585:     if (kwsize=="+2") {var sz2sel="checked"};
 1586:     var synsel = "";
 1587:     var syisel = "";
 1588:     var sybsel = "";
 1589:     if (kwstyle=="")    {var synsel="checked"};
 1590:     if (kwstyle=="<i>") {var syisel="checked"};
 1591:     if (kwstyle=="<b>") {var sybsel="checked"};
 1592:     highlightCentral();
 1593:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1594:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1595:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1596:     highlightend();
 1597:     return;
 1598:   }
 1599: 
 1600:   function highlightCentral() {
 1601: //    if (window.hwdWin) window.hwdWin.close();
 1602:     var xpos = (screen.width-400)/2;
 1603:     xpos = (xpos < 0) ? '0' : xpos;
 1604:     var ypos = (screen.height-330)/2-30;
 1605:     ypos = (ypos < 0) ? '0' : ypos;
 1606: 
 1607:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1608:     hwdWin.focus();
 1609:     var hDoc = hwdWin.document;
 1610:     hDoc.$docopen;
 1611:     hDoc.write('$start_page_highlight_central');
 1612:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1613:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1614: 
 1615:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1616:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1617:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1618:   }
 1619: 
 1620:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1621:     var hDoc = hwdWin.document;
 1622:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1623:     hDoc.write("<td align=\\"left\\">");
 1624:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1625:     hDoc.write("<td align=\\"left\\">");
 1626:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1627:     hDoc.write("<td align=\\"left\\">");
 1628:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1629:     hDoc.write("<\\/tr>");
 1630:   }
 1631: 
 1632:   function highlightend() { 
 1633:     var hDoc = hwdWin.document;
 1634:     hDoc.write("<\\/table>");
 1635:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1636:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1637:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1638:     hDoc.write("<\\/form>");
 1639:     hDoc.write('$end_page_highlight_central');
 1640:     hDoc.close();
 1641:   }
 1642: 
 1643: </script>
 1644: SUBJAVASCRIPT
 1645: }
 1646: 
 1647: sub get_increment {
 1648:     my $increment = $env{'form.increment'};
 1649:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1650:         $increment != .1) {
 1651:         $increment = 1;
 1652:     }
 1653:     return $increment;
 1654: }
 1655: 
 1656: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1657: sub gradeBox {
 1658:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1659:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1660: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1661:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1662:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1663:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1664:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1665:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1666: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1667:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1668:     my $display_part= &get_display_part($partid,$symb);
 1669:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1670: 				       [$partid]);
 1671:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1672:     if ($last_resets{$partid}) {
 1673:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1674:     }
 1675:     $result.='<table border="0"><tr>';
 1676:     my $ctr = 0;
 1677:     my $thisweight = 0;
 1678:     my $increment = &get_increment();
 1679: 
 1680:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1681:     while ($thisweight<=$wgt) {
 1682: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1683: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1684: 	    $thisweight.')" value="'.$thisweight.'" '.
 1685: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1686: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1687:         $thisweight += $increment;
 1688: 	$ctr++;
 1689:     }
 1690:     $radio.='</tr></table>';
 1691: 
 1692:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1693: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1694: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1695: 	$wgt.')" /></td>'."\n";
 1696:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1697: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1698: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
 1699:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1700: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1701:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1702: 	$line.='<option></option>'.
 1703: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1704:     } else {
 1705: 	$line.='<option selected="selected"></option>'.
 1706: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1707:     }
 1708:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1709: 
 1710: 
 1711:     $result .= 
 1712:             '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
 1713:     
 1714:     $result.='</tr></table>'."\n";
 1715:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1716: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1717: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1718: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1719:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1720:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1721:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1722:         $aggtries.'" />'."\n";
 1723:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1724:     return $result;
 1725: }
 1726: 
 1727: sub handback_box {
 1728:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1729:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1730:     my (@respids);
 1731:      my @part_response_id = &flatten_responseType($responseType);
 1732:     foreach my $part_response_id (@part_response_id) {
 1733:     	my ($part,$resp) = @{ $part_response_id };
 1734:         if ($part eq $partid) {
 1735:             push(@respids,$resp);
 1736:         }
 1737:     }
 1738:     my $result;
 1739:     foreach my $respid (@respids) {
 1740: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1741: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1742: 	next if (!@$files);
 1743: 	my $file_counter = 1;
 1744: 	foreach my $file (@$files) {
 1745: 	    if ($file =~ /\/portfolio\//) {
 1746:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1747:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1748:     	        $file_disp = "$name.$ext";
 1749:     	        $file = $file_path.$file_disp;
 1750:     	        $result.=&mt('Return commented version of [_1] to student.',
 1751:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1752:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1753:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1754:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1755:     	        $file_counter++;
 1756: 	    }
 1757: 	}
 1758:     }
 1759:     return $result;    
 1760: }
 1761: 
 1762: sub show_problem {
 1763:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1764:     my $rendered;
 1765:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1766:     &Apache::lonxml::remember_problem_counter();
 1767:     if ($mode eq 'both' or $mode eq 'text') {
 1768: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1769: 						       $env{'request.course.id'},
 1770: 						       undef,\%form);
 1771:     }
 1772:     if ($removeform) {
 1773: 	$rendered=~s|<form(.*?)>||g;
 1774: 	$rendered=~s|</form>||g;
 1775: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1776:     }
 1777:     my $companswer;
 1778:     if ($mode eq 'both' or $mode eq 'answer') {
 1779: 	&Apache::lonxml::restore_problem_counter();
 1780: 	$companswer=
 1781: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1782: 						    $env{'request.course.id'},
 1783: 						    %form);
 1784:     }
 1785:     if ($removeform) {
 1786: 	$companswer=~s|<form(.*?)>||g;
 1787: 	$companswer=~s|</form>||g;
 1788: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1789:     }
 1790:     $rendered=
 1791: 	'<div class="LC_grade_show_problem_header">'.
 1792: 	&mt('View of the problem').
 1793: 	'</div><div class="LC_grade_show_problem_problem">'.
 1794: 	$rendered.
 1795: 	'</div>';
 1796:     $companswer=
 1797: 	'<div class="LC_grade_show_problem_header">'.
 1798: 	&mt('Correct answer').
 1799: 	'</div><div class="LC_grade_show_problem_problem">'.
 1800: 	$companswer.
 1801: 	'</div>';
 1802:     my $result;
 1803:     if ($mode eq 'both') {
 1804: 	$result=$rendered.$companswer;
 1805:     } elsif ($mode eq 'text') {
 1806: 	$result=$rendered;
 1807:     } elsif ($mode eq 'answer') {
 1808: 	$result=$companswer;
 1809:     }
 1810:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1811:     return $result;
 1812: }
 1813: 
 1814: sub files_exist {
 1815:     my ($r, $symb) = @_;
 1816:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1817: 
 1818:     foreach my $student (@students) {
 1819:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1820:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1821: 					      $udom,$uname);
 1822:         my ($string,$timestamp)= &get_last_submission(\%record);
 1823:         foreach my $submission (@$string) {
 1824:             my ($partid,$respid) =
 1825: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1826:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1827: 					   \%record);
 1828:             return 1 if (@$files);
 1829:         }
 1830:     }
 1831:     return 0;
 1832: }
 1833: 
 1834: sub download_all_link {
 1835:     my ($r,$symb) = @_;
 1836:     my $all_students = 
 1837: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1838: 
 1839:     my $parts =
 1840: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1841: 
 1842:     my $identifier = &Apache::loncommon::get_cgi_id();
 1843:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1844:                              'cgi.'.$identifier.'.symb' => $symb,
 1845:                              'cgi.'.$identifier.'.parts' => $parts,});
 1846:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1847: 	      &mt('Download All Submitted Documents').'</a>');
 1848:     return
 1849: }
 1850: 
 1851: sub build_section_inputs {
 1852:     my $section_inputs;
 1853:     if ($env{'form.section'} eq '') {
 1854:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1855:     } else {
 1856:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1857:         foreach my $section (@sections) {
 1858:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1859:         }
 1860:     }
 1861:     return $section_inputs;
 1862: }
 1863: 
 1864: # --------------------------- show submissions of a student, option to grade 
 1865: sub submission {
 1866:     my ($request,$counter,$total) = @_;
 1867:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1868:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1869:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1870:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1871:     my $symb = &get_symb($request); 
 1872:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1873: 
 1874:     if (!&canview($usec)) {
 1875: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1876: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1877: 			$env{'request.course.id'}.')</span>');
 1878: 	$request->print(&show_grading_menu_form($symb));
 1879: 	return;
 1880:     }
 1881: 
 1882:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1883:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1884:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1885:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1886:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1887: 	'" src="'.$request->dir_config('lonIconsURL').
 1888: 	'/check.gif" height="16" border="0" />';
 1889: 
 1890:     my %old_essays;
 1891:     # header info
 1892:     if ($counter == 0) {
 1893: 	&sub_page_js($request);
 1894: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1895: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1896: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1897: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1898: 	    &download_all_link($request, $symb);
 1899: 	}
 1900: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 1901: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 1902: 
 1903: 	# option to display problem, only once else it cause problems 
 1904:         # with the form later since the problem has a form.
 1905: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1906: 	    my $mode;
 1907: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1908: 		$mode='both';
 1909: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1910: 		$mode='text';
 1911: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1912: 		$mode='answer';
 1913: 	    }
 1914: 	    &Apache::lonxml::clear_problem_counter();
 1915: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1916: 	}
 1917: 
 1918: 	# kwclr is the only variable that is guaranteed to be non blank 
 1919:         # if this subroutine has been called once.
 1920: 	my %keyhash = ();
 1921: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1922: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1923: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1924: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1925: 
 1926: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1927: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1928: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1929: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1930: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1931: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1932: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1933: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1934: 	}
 1935: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1936: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1937: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1938: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1939: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1940: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1941: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1942: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1943: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1944: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1945: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1946: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1947: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1948: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1949: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1950: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1951: 			&build_section_inputs().
 1952: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1953: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1954: 			'<input type="hidden" name="NCT"'.
 1955: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1956: 	if ($env{'form.handgrade'} eq 'yes') {
 1957: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1958: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1959: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1960: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1961: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1962: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1963: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1964: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1965: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1966: 	    }
 1967: 	}
 1968: 	
 1969: 	my ($cts,$prnmsg) = (1,'');
 1970: 	while ($cts <= $env{'form.savemsgN'}) {
 1971: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1972: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1973: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1974: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1975: 		'" />'."\n".
 1976: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1977: 	    $cts++;
 1978: 	}
 1979: 	$request->print($prnmsg);
 1980: 
 1981: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1982: #
 1983: # Print out the keyword options line
 1984: #
 1985: 	    $request->print(<<KEYWORDS);
 1986: &nbsp;<b>Keyword Options:</b>&nbsp;
 1987: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1988: <a href="#" onMouseDown="javascript:getSel(); return false"
 1989:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1990: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1991: KEYWORDS
 1992: #
 1993: # Load the other essays for similarity check
 1994: #
 1995:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1996: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1997: 	    $apath=&escape($apath);
 1998: 	    $apath=~s/\W/\_/gs;
 1999: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2000:         }
 2001:     }
 2002: 
 2003: # This is where output for one specific student would start
 2004:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2005:     $request->print("\n\n".
 2006:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2007: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2008: 		    '<div class="LC_grade_show_user_body">'."\n");
 2009: 
 2010:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2011: 	my $mode;
 2012: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2013: 	    $mode='both';
 2014: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2015: 	    $mode='text';
 2016: 	} elsif ($env{'form.vAns'} eq 'all') {
 2017: 	    $mode='answer';
 2018: 	}
 2019: 	&Apache::lonxml::clear_problem_counter();
 2020: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2021:     }
 2022: 
 2023:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2024:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2025: 
 2026:     # Display student info
 2027:     $request->print(($counter == 0 ? '' : '<br />'));
 2028:     my $result='<div class="LC_grade_submissions">';
 2029:     
 2030:     $result.='<div class="LC_grade_submissions_header">';
 2031:     $result.= &mt('Submissions');
 2032:     $result.='<input type="hidden" name="name'.$counter.
 2033: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2034:     if ($env{'form.handgrade'} eq 'no') {
 2035: 	$result.='<span class="LC_grade_check_note">'.
 2036: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2037: 
 2038:     }
 2039: 
 2040: 
 2041: 
 2042:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2043:     my $fullname;
 2044:     my $col_fullnames = [];
 2045:     if ($env{'form.handgrade'} eq 'yes') {
 2046: 	(my $sub_result,$fullname,$col_fullnames)=
 2047: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2048: 				 $counter);
 2049: 	$result.=$sub_result;
 2050:     }
 2051:     $request->print($result."\n");
 2052:     $request->print('</div>'."\n");
 2053:     # print student answer/submission
 2054:     # Options are (1) Handgaded submission only
 2055:     #             (2) Last submission, includes submission that is not handgraded 
 2056:     #                  (for multi-response type part)
 2057:     #             (3) Last submission plus the parts info
 2058:     #             (4) The whole record for this student
 2059:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2060: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2061: 	
 2062: 	my $lastsubonly;
 2063: 
 2064: 	if ($$timestamp eq '') {
 2065: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2066: 	} else {
 2067: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2068: 
 2069: 	    my %seenparts;
 2070: 	    my @part_response_id = &flatten_responseType($responseType);
 2071: 	    foreach my $part (@part_response_id) {
 2072: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2073: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2074: 
 2075: 		my ($partid,$respid) = @{ $part };
 2076: 		my $display_part=&get_display_part($partid,$symb);
 2077: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2078: 		    if (exists($seenparts{$partid})) { next; }
 2079: 		    $seenparts{$partid}=1;
 2080: 		    my $submitby='<b>Part:</b> '.$display_part.
 2081: 			' <b>Collaborative submission by:</b> '.
 2082: 			'<a href="javascript:viewSubmitter(\''.
 2083: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2084: 			'\');" target="_self">'.
 2085: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2086: 		    $request->print($submitby);
 2087: 		    next;
 2088: 		}
 2089: 		my $responsetype = $responseType->{$partid}->{$respid};
 2090: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2091: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2092: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2093: 			' )</span>&nbsp; &nbsp;'.
 2094: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
 2095: 		    next;
 2096: 		}
 2097: 		foreach my $submission (@$string) {
 2098: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2099: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2100: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2101: 		    # Similarity check
 2102: 		    my $similar='';
 2103: 		    if($env{'form.checkPlag'}){
 2104: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2105: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2106: 			if ($osim) {
 2107: 			    $osim=int($osim*100.0);
 2108: 			    my %old_course_desc = 
 2109: 				&Apache::lonnet::coursedescription($ocrsid,
 2110: 								   {'one_time' => 1});
 2111: 
 2112: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2113: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2114: 				    $osim,
 2115: 				    &Apache::loncommon::plainname($oname,$odom),
 2116: 				    $oname,$odom,
 2117: 				    $old_course_desc{'description'},
 2118: 				    $old_course_desc{'num'},
 2119: 				    $old_course_desc{'domain'}).
 2120: 				'</span></h3><blockquote><i>'.
 2121: 				&keywords_highlight($oessay).
 2122: 				'</i></blockquote><hr />';
 2123: 			}
 2124: 		    }
 2125: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2126: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2127: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2128: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2129: 			my $display_part=&get_display_part($partid,$symb);
 2130: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2131: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2132: 			    ' )</span>&nbsp; &nbsp;';
 2133: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2134: 			if (@$files) {
 2135: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
 2136: 			    my $file_counter = 0;
 2137: 			    foreach my $file (@$files) {
 2138: 			        $file_counter++;
 2139: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2140: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2141: 			    }
 2142: 			    $lastsubonly.='<br />';
 2143: 			}
 2144: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2145: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2146: 					 $respid,\%record,$order,undef,$uname,$udom);
 2147: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2148: 			$lastsubonly.='</div>';
 2149: 		    }
 2150: 		}
 2151: 	    }
 2152: 	    $lastsubonly.='</div>'."\n";
 2153: 	}
 2154: 	$request->print($lastsubonly);
 2155:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2156: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2157: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2158:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2159: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2160: 								 $env{'request.course.id'},
 2161: 								 $last,'.submission',
 2162: 								 'Apache::grades::keywords_highlight'));
 2163:     }
 2164: 
 2165:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2166: 	.$udom.'" />'."\n");
 2167:     # return if view submission with no grading option
 2168:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2169: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2170: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2171: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2172: 	$toGrade.='</div>'."\n";
 2173: 	if (($env{'form.command'} eq 'submission') || 
 2174: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2175: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2176: 	}
 2177: 	$request->print($toGrade);
 2178: 	return;
 2179:     } else {
 2180: 	$request->print('</div>'."\n");
 2181:     }
 2182: 
 2183:     # essay grading message center
 2184:     if ($env{'form.handgrade'} eq 'yes') {
 2185: 	my $result='<div class="LC_grade_message_center">';
 2186:     
 2187: 	$result.='<div class="LC_grade_message_center_header">'.
 2188: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2189: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2190: 	my $msgfor = $givenn.' '.$lastname;
 2191: 	if (scalar(@$col_fullnames) > 0) {
 2192: 	    my $lastone = pop(@$col_fullnames);
 2193: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2194: 	}
 2195: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2196: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2197: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2198: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2199: 	    ',\''.$msgfor.'\');" target="_self">'.
 2200: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2201: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2202: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2203: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2204: 	    '<br />&nbsp;('.
 2205: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2206: 	$result.='</div></div>';
 2207: 	$request->print($result);
 2208:     }
 2209: 
 2210:     my %seen = ();
 2211:     my @partlist;
 2212:     my @gradePartRespid;
 2213:     my @part_response_id = &flatten_responseType($responseType);
 2214:     $request->print('<div class="LC_grade_assign">'.
 2215: 		    
 2216: 		    '<div class="LC_grade_assign_header">'.
 2217: 		    &mt('Assign Grades').'</div>'.
 2218: 		    '<div class="LC_grade_assign_body">');
 2219:     foreach my $part_response_id (@part_response_id) {
 2220:     	my ($partid,$respid) = @{ $part_response_id };
 2221: 	my $part_resp = join('_',@{ $part_response_id });
 2222: 	next if ($seen{$partid} > 0);
 2223: 	$seen{$partid}++;
 2224: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2225: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2226: 	push(@partlist,$partid);
 2227: 	push(@gradePartRespid,$partid.'.'.$respid);
 2228: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2229:     }
 2230:     $request->print('</div></div>');
 2231: 
 2232:     $request->print('<div class="LC_grade_info_links">');
 2233:     if ($perm{'vgr'}) {
 2234: 	$request->print(
 2235: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2236: 						   $uname,$udom,'check'));
 2237:     }
 2238:     if ($perm{'opa'}) {
 2239: 	$request->print(
 2240: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2241: 					 $uname,$udom,$symb,'check'));
 2242:     }
 2243:     $request->print('</div>');
 2244: 
 2245:     $result='<input type="hidden" name="partlist'.$counter.
 2246: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2247:     $result.='<input type="hidden" name="gradePartRespid'.
 2248: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2249:     my $ctr = 0;
 2250:     while ($ctr < scalar(@partlist)) {
 2251: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2252: 	    $partlist[$ctr].'" />'."\n";
 2253: 	$ctr++;
 2254:     }
 2255:     $request->print($result.''."\n");
 2256: 
 2257: # Done with printing info for one student
 2258: 
 2259:     $request->print('</div>');#LC_grade_show_user_body
 2260:     $request->print('</div>');#LC_grade_show_user
 2261: 
 2262: 
 2263:     # print end of form
 2264:     if ($counter == $total) {
 2265: 	my $endform='<table border="0"><tr><td>'."\n";
 2266: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2267: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2268: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2269: 	my $ntstu ='<select name="NTSTU">'.
 2270: 	    '<option>1</option><option>2</option>'.
 2271: 	    '<option>3</option><option>5</option>'.
 2272: 	    '<option>7</option><option>10</option></select>'."\n";
 2273: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2274: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2275:         $endform.=&mt('[_1]student(s)',$ntstu);
 2276: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2277: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2278: 	    '<input type="button" value="'.&mt('Next').'" '.
 2279: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2280: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2281:         $endform.="<input type='hidden' value='".&get_increment().
 2282:             "' name='increment' />";
 2283: 	$endform.='</td></tr></table></form>';
 2284: 	$endform.=&show_grading_menu_form($symb);
 2285: 	$request->print($endform);
 2286:     }
 2287:     return '';
 2288: }
 2289: 
 2290: sub check_collaborators {
 2291:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2292:     my ($result,@col_fullnames);
 2293:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2294:     foreach my $part (keys(%$handgrade)) {
 2295: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2296: 					'.maxcollaborators',
 2297: 					$symb,$udom,$uname);
 2298: 	next if ($ncol <= 0);
 2299: 	$part =~ s/\_/\./g;
 2300: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2301: 	my (@good_collaborators, @bad_collaborators);
 2302: 	foreach my $possible_collaborator
 2303: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2304: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2305: 	    next if ($possible_collaborator eq '');
 2306: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2307: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2308: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2309: 	    # Doing this grep allows 'fuzzy' specification
 2310: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2311: 			       keys(%$classlist));
 2312: 	    if (! scalar(@matches)) {
 2313: 		push(@bad_collaborators, $possible_collaborator);
 2314: 	    } else {
 2315: 		push(@good_collaborators, @matches);
 2316: 	    }
 2317: 	}
 2318: 	if (scalar(@good_collaborators) != 0) {
 2319: 	    $result.='<br />'.&mt('Collaborators: ');
 2320: 	    foreach my $name (@good_collaborators) {
 2321: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2322: 		push(@col_fullnames, $givenn.' '.$lastname);
 2323: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2324: 	    }
 2325: 	    $result.='<br />'."\n";
 2326: 	    my ($part)=split(/\./,$part);
 2327: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2328: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2329: 		"\n";
 2330: 	}
 2331: 	if (scalar(@bad_collaborators) > 0) {
 2332: 	    $result.='<div class="LC_warning">';
 2333: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2334: 	    $result .= '</div>';
 2335: 	}         
 2336: 	if (scalar(@bad_collaborators > $ncol)) {
 2337: 	    $result .= '<div class="LC_warning">';
 2338: 	    $result .= &mt('This student has submitted too many '.
 2339: 		'collaborators.  Maximum is [_1].',$ncol);
 2340: 	    $result .= '</div>';
 2341: 	}
 2342:     }
 2343:     return ($result,$fullname,\@col_fullnames);
 2344: }
 2345: 
 2346: #--- Retrieve the last submission for all the parts
 2347: sub get_last_submission {
 2348:     my ($returnhash)=@_;
 2349:     my (@string,$timestamp);
 2350:     if ($$returnhash{'version'}) {
 2351: 	my %lasthash=();
 2352: 	my ($version);
 2353: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2354: 	    foreach my $key (sort(split(/\:/,
 2355: 					$$returnhash{$version.':keys'}))) {
 2356: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2357: 		$timestamp = 
 2358: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
 2359: 	    }
 2360: 	}
 2361: 	foreach my $key (keys(%lasthash)) {
 2362: 	    next if ($key !~ /\.submission$/);
 2363: 
 2364: 	    my ($partid,$foo) = split(/submission$/,$key);
 2365: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2366: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2367: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2368: 	}
 2369:     }
 2370:     if (!@string) {
 2371: 	$string[0] =
 2372: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2373:     }
 2374:     return (\@string,\$timestamp);
 2375: }
 2376: 
 2377: #--- High light keywords, with style choosen by user.
 2378: sub keywords_highlight {
 2379:     my $string    = shift;
 2380:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2381:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2382:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2383:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2384:     foreach my $keyword (@keylist) {
 2385: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2386:     }
 2387:     return $string;
 2388: }
 2389: 
 2390: #--- Called from submission routine
 2391: sub processHandGrade {
 2392:     my ($request) = shift;
 2393:     my $symb   = &get_symb($request);
 2394:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2395:     my $button = $env{'form.gradeOpt'};
 2396:     my $ngrade = $env{'form.NCT'};
 2397:     my $ntstu  = $env{'form.NTSTU'};
 2398:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2399:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2400: 
 2401:     if ($button eq 'Save & Next') {
 2402: 	my $ctr = 0;
 2403: 	while ($ctr < $ngrade) {
 2404: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2405: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2406: 	    if ($errorflag eq 'no_score') {
 2407: 		$ctr++;
 2408: 		next;
 2409: 	    }
 2410: 	    if ($errorflag eq 'not_allowed') {
 2411: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2412: 		$ctr++;
 2413: 		next;
 2414: 	    }
 2415: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2416: 	    my ($subject,$message,$msgstatus) = ('','','');
 2417: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2418:             my ($feedurl,$showsymb) =
 2419: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2420: 	    my $messagetail;
 2421: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2422: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2423: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2424: 		$subject.=' ['.$restitle.']';
 2425: 		my (@msgnum) = split(/,/,$includemsg);
 2426: 		foreach (@msgnum) {
 2427: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2428: 		}
 2429: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2430: 		if ($env{'form.withgrades'.$ctr}) {
 2431: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2432: 		    $messagetail = " for <a href=\"".
 2433: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2434: 		}
 2435: 		$msgstatus = 
 2436:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2437: 						     $message.$messagetail,
 2438:                                                      undef,$feedurl,undef,
 2439:                                                      undef,undef,$showsymb,
 2440:                                                      $restitle);
 2441: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2442: 				$msgstatus);
 2443: 	    }
 2444: 	    if ($env{'form.collaborator'.$ctr}) {
 2445: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2446: 		foreach my $collabstr (@collabstrs) {
 2447: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2448: 		    foreach my $collaborator (@collaborators) {
 2449: 			my ($errorflag,$pts,$wgt) = 
 2450: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2451: 					   $env{'form.unamedom'.$ctr},$part);
 2452: 			if ($errorflag eq 'not_allowed') {
 2453: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2454: 			    next;
 2455: 			} elsif ($message ne '') {
 2456: 			    my ($baseurl,$showsymb) = 
 2457: 				&get_feedurl_and_symb($symb,$collaborator,
 2458: 						      $udom);
 2459: 			    if ($env{'form.withgrades'.$ctr}) {
 2460: 				$messagetail = " for <a href=\"".
 2461:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2462: 			    }
 2463: 			    $msgstatus = 
 2464: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2465: 			}
 2466: 		    }
 2467: 		}
 2468: 	    }
 2469: 	    $ctr++;
 2470: 	}
 2471:     }
 2472: 
 2473:     if ($env{'form.handgrade'} eq 'yes') {
 2474: 	# Keywords sorted in alphabatical order
 2475: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2476: 	my %keyhash = ();
 2477: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2478: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2479: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2480: 	$env{'form.keywords'} = join(' ',@keywords);
 2481: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2482: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2483: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2484: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2485: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2486: 
 2487: 	# message center - Order of message gets changed. Blank line is eliminated.
 2488: 	# New messages are saved in env for the next student.
 2489: 	# All messages are saved in nohist_handgrade.db
 2490: 	my ($ctr,$idx) = (1,1);
 2491: 	while ($ctr <= $env{'form.savemsgN'}) {
 2492: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2493: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2494: 		$idx++;
 2495: 	    }
 2496: 	    $ctr++;
 2497: 	}
 2498: 	$ctr = 0;
 2499: 	while ($ctr < $ngrade) {
 2500: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2501: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2502: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2503: 		$idx++;
 2504: 	    }
 2505: 	    $ctr++;
 2506: 	}
 2507: 	$env{'form.savemsgN'} = --$idx;
 2508: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2509: 	my $putresult = &Apache::lonnet::put
 2510: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2511:     }
 2512:     # Called by Save & Refresh from Highlight Attribute Window
 2513:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2514:     if ($env{'form.refresh'} eq 'on') {
 2515: 	my ($ctr,$total) = (0,0);
 2516: 	while ($ctr < $ngrade) {
 2517: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2518: 	    $ctr++;
 2519: 	}
 2520: 	$env{'form.NTSTU'}=$ngrade;
 2521: 	$ctr = 0;
 2522: 	while ($ctr < $total) {
 2523: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2524: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2525: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2526: 	    &submission($request,$ctr,$total-1);
 2527: 	    $ctr++;
 2528: 	}
 2529: 	return '';
 2530:     }
 2531: 
 2532: # Go directly to grade student - from submission or link from chart page
 2533:     if ($button eq 'Grade Student') {
 2534: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2535: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2536: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2537: 	$env{'form.fullname'} = $$fullname{$processUser};
 2538: 	&submission($request,0,0);
 2539: 	return '';
 2540:     }
 2541: 
 2542:     # Get the next/previous one or group of students
 2543:     my $firststu = $env{'form.unamedom0'};
 2544:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2545:     my $ctr = 2;
 2546:     while ($laststu eq '') {
 2547: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2548: 	$ctr++;
 2549: 	$laststu = $firststu if ($ctr > $ngrade);
 2550:     }
 2551: 
 2552:     my (@parsedlist,@nextlist);
 2553:     my ($nextflg) = 0;
 2554:     foreach my $item (sort 
 2555: 	     {
 2556: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2557: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2558: 		 }
 2559: 		 return $a cmp $b;
 2560: 	     } (keys(%$fullname))) {
 2561: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2562: 	    push(@parsedlist,$item);
 2563: 	}
 2564: 	$nextflg = 1 if ($item eq $laststu);
 2565: 	if ($button eq 'Previous') {
 2566: 	    last if ($item eq $firststu);
 2567: 	    push(@parsedlist,$item);
 2568: 	}
 2569:     }
 2570:     $ctr = 0;
 2571:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2572:     my ($partlist) = &response_type($symb);
 2573:     foreach my $student (@parsedlist) {
 2574: 	my $submitonly=$env{'form.submitonly'};
 2575: 	my ($uname,$udom) = split(/:/,$student);
 2576: 	
 2577: 	if ($submitonly eq 'queued') {
 2578: 	    my %queue_status = 
 2579: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2580: 							$udom,$uname);
 2581: 	    next if (!defined($queue_status{'gradingqueue'}));
 2582: 	}
 2583: 
 2584: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2585: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2586: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2587: 	    my $submitted = 0;
 2588: 	    my $ungraded = 0;
 2589: 	    my $incorrect = 0;
 2590: 	    foreach my $item (keys(%status)) {
 2591: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2592: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2593: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2594: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2595: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2596: 		    $submitted = 0;
 2597: 		}
 2598: 	    }
 2599: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2600: 				     $submitonly eq 'incorrect' ||
 2601: 				     $submitonly eq 'graded'));
 2602: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2603: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2604: 	}
 2605: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2606: 	last if ($ctr == $ntstu);
 2607: 	$ctr++;
 2608:     }
 2609: 
 2610:     $ctr = 0;
 2611:     my $total = scalar(@nextlist)-1;
 2612: 
 2613:     foreach (sort(@nextlist)) {
 2614: 	my ($uname,$udom,$submitter) = split(/:/);
 2615: 	$env{'form.student'}  = $uname;
 2616: 	$env{'form.userdom'}  = $udom;
 2617: 	$env{'form.fullname'} = $$fullname{$_};
 2618: 	&submission($request,$ctr,$total);
 2619: 	$ctr++;
 2620:     }
 2621:     if ($total < 0) {
 2622: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2623: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2624: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2625: 	$the_end.=&show_grading_menu_form($symb);
 2626: 	$request->print($the_end);
 2627:     }
 2628:     return '';
 2629: }
 2630: 
 2631: #---- Save the score and award for each student, if changed
 2632: sub saveHandGrade {
 2633:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2634:     my @version_parts;
 2635:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2636: 					   $env{'request.course.id'});
 2637:     if (!&canmodify($usec)) { return('not_allowed'); }
 2638:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2639:     my @parts_graded;
 2640:     my %newrecord  = ();
 2641:     my ($pts,$wgt) = ('','');
 2642:     my %aggregate = ();
 2643:     my $aggregateflag = 0;
 2644:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2645:     foreach my $new_part (@parts) {
 2646: 	#collaborator ($submi may vary for different parts
 2647: 	if ($submitter && $new_part ne $part) { next; }
 2648: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2649: 	if ($dropMenu eq 'excused') {
 2650: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2651: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2652: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2653: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2654: 		}
 2655: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2656: 	    }
 2657: 	} elsif ($dropMenu eq 'reset status'
 2658: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2659: 	    foreach my $key (keys(%record)) {
 2660: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2661: 	    }
 2662: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2663: 		"$env{'user.name'}:$env{'user.domain'}";
 2664:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2665: 
 2666:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2667: 					       [$new_part]);
 2668:             my $aggtries =$totaltries;
 2669:             if ($last_resets{$new_part}) {
 2670:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2671: 					   $new_part);
 2672:             }
 2673: 
 2674:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2675:             if ($aggtries > 0) {
 2676:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2677:                 $aggregateflag = 1;
 2678:             }
 2679: 	} elsif ($dropMenu eq '') {
 2680: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2681: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2682: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2683: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2684: 		next;
 2685: 	    }
 2686: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2687: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2688: 	    my $partial= $pts/$wgt;
 2689: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2690: 		#do not update score for part if not changed.
 2691:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2692: 		next;
 2693: 	    } else {
 2694: 	        push(@parts_graded,$new_part);
 2695: 	    }
 2696: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2697: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2698: 	    }
 2699: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2700: 	    if ($partial == 0) {
 2701: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2702: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2703: 		}
 2704: 	    } else {
 2705: 		if ($record{$reckey} ne 'correct_by_override') {
 2706: 		    $newrecord{$reckey} = 'correct_by_override';
 2707: 		}
 2708: 	    }	    
 2709: 	    if ($submitter && 
 2710: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2711: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2712: 	    }
 2713: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2714: 		"$env{'user.name'}:$env{'user.domain'}";
 2715: 	}
 2716: 	# unless problem has been graded, set flag to version the submitted files
 2717: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2718: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2719: 	        $dropMenu eq 'reset status')
 2720: 	   {
 2721: 	    push(@version_parts,$new_part);
 2722: 	}
 2723:     }
 2724:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2725:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2726: 
 2727:     if (%newrecord) {
 2728:         if (@version_parts) {
 2729:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2730:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2731: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2732: 	    foreach my $new_part (@version_parts) {
 2733: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2734: 				$new_part,\%newrecord);
 2735: 	    }
 2736:         }
 2737: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2738: 				$env{'request.course.id'},$domain,$stuname);
 2739: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2740: 				     $cdom,$cnum,$domain,$stuname);
 2741:     }
 2742:     if ($aggregateflag) {
 2743:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2744: 			      $cdom,$cnum);
 2745:     }
 2746:     return ('',$pts,$wgt);
 2747: }
 2748: 
 2749: sub check_and_remove_from_queue {
 2750:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2751:     my @ungraded_parts;
 2752:     foreach my $part (@{$parts}) {
 2753: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2754: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2755: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2756: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2757: 		) {
 2758: 	    push(@ungraded_parts, $part);
 2759: 	}
 2760:     }
 2761:     if ( !@ungraded_parts ) {
 2762: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2763: 					       $cnum,$domain,$stuname);
 2764:     }
 2765: }
 2766: 
 2767: sub handback_files {
 2768:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2769:     my $portfolio_root = '/userfiles/portfolio';
 2770:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2771: 
 2772:     my @part_response_id = &flatten_responseType($responseType);
 2773:     foreach my $part_response_id (@part_response_id) {
 2774:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2775: 	my $part_resp = join('_',@{ $part_response_id });
 2776:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2777:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2778:                 my $file_counter = 1;
 2779: 		my $file_msg;
 2780:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2781:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2782:                     my ($directory,$answer_file) = 
 2783:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2784:                     my ($answer_name,$answer_ver,$answer_ext) =
 2785: 		        &file_name_version_ext($answer_file);
 2786: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2787:                     my $getpropath = 1;
 2788: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2789: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2790:                     # fix file name
 2791:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2792:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2793:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2794:             	                                $save_file_name);
 2795:                     if ($result !~ m|^/uploaded/|) {
 2796:                         $request->print('<br /><span class="LC_error">'.
 2797:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
 2798:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
 2799:                                         '</span>');
 2800:                     } else {
 2801:                         # mark the file as read only
 2802:                         my @files = ($save_file_name);
 2803:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2804:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2805: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2806: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2807: 			}
 2808:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2809: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2810: 
 2811:                     }
 2812:                     $request->print("<br />".$fname." will be the uploaded file name");
 2813:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2814:                     $file_counter++;
 2815:                 }
 2816: 		my $subject = "File Handed Back by Instructor ";
 2817: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2818: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2819: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2820: 		$message .= " and can be found in your portfolio space.";
 2821: 		my ($feedurl,$showsymb) = 
 2822: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2823:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2824: 		my $msgstatus = 
 2825:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2826: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2827:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2828:             }
 2829:         }
 2830:     return;
 2831: }
 2832: 
 2833: sub get_feedurl_and_symb {
 2834:     my ($symb,$uname,$udom) = @_;
 2835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2836:     $url = &Apache::lonnet::clutter($url);
 2837:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2838: 					$symb,$udom,$uname);
 2839:     if ($encrypturl =~ /^yes$/i) {
 2840: 	&Apache::lonenc::encrypted(\$url,1);
 2841: 	&Apache::lonenc::encrypted(\$symb,1);
 2842:     }
 2843:     return ($url,$symb);
 2844: }
 2845: 
 2846: sub get_submitted_files {
 2847:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2848:     my @files;
 2849:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2850:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2851:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2852:     	    push(@files,$file_url.$file);
 2853:         }
 2854:     }
 2855:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2856:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2857:     }
 2858:     return (\@files);
 2859: }
 2860: 
 2861: # ----------- Provides number of tries since last reset.
 2862: sub get_num_tries {
 2863:     my ($record,$last_reset,$part) = @_;
 2864:     my $timestamp = '';
 2865:     my $num_tries = 0;
 2866:     if ($$record{'version'}) {
 2867:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2868:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2869:                 $timestamp = $$record{$version.':timestamp'};
 2870:                 if ($timestamp > $last_reset) {
 2871:                     $num_tries ++;
 2872:                 } else {
 2873:                     last;
 2874:                 }
 2875:             }
 2876:         }
 2877:     }
 2878:     return $num_tries;
 2879: }
 2880: 
 2881: # ----------- Determine decrements required in aggregate totals 
 2882: sub decrement_aggs {
 2883:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2884:     my %decrement = (
 2885:                         attempts => 0,
 2886:                         users => 0,
 2887:                         correct => 0
 2888:                     );
 2889:     $decrement{'attempts'} = $aggtries;
 2890:     if ($solvedstatus =~ /^correct/) {
 2891:         $decrement{'correct'} = 1;
 2892:     }
 2893:     if ($aggtries == $totaltries) {
 2894:         $decrement{'users'} = 1;
 2895:     }
 2896:     foreach my $type (keys(%decrement)) {
 2897:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2898:     }
 2899:     return;
 2900: }
 2901: 
 2902: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2903: sub get_last_resets {
 2904:     my ($symb,$courseid,$partids) =@_;
 2905:     my %last_resets;
 2906:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2907:     my $cname = $env{'course.'.$courseid.'.num'};
 2908:     my @keys;
 2909:     foreach my $part (@{$partids}) {
 2910: 	push(@keys,"$symb\0$part\0resettime");
 2911:     }
 2912:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2913: 				     $cdom,$cname);
 2914:     foreach my $part (@{$partids}) {
 2915: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2916:     }
 2917:     return %last_resets;
 2918: }
 2919: 
 2920: # ----------- Handles creating versions for portfolio files as answers
 2921: sub version_portfiles {
 2922:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2923:     my $version_parts = join('|',@$v_flag);
 2924:     my @returned_keys;
 2925:     my $parts = join('|', @$parts_graded);
 2926:     my $portfolio_root = '/userfiles/portfolio';
 2927:     foreach my $key (keys(%$record)) {
 2928:         my $new_portfiles;
 2929:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2930:             my @versioned_portfiles;
 2931:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2932:             foreach my $file (@portfiles) {
 2933:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2934:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2935: 		my ($answer_name,$answer_ver,$answer_ext) =
 2936: 		    &file_name_version_ext($answer_file);
 2937:                 my $getpropath = 1;    
 2938:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 2939:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2940:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2941:                 if ($new_answer ne 'problem getting file') {
 2942:                     push(@versioned_portfiles, $directory.$new_answer);
 2943:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2944:                         [$directory.$new_answer],
 2945:                         [$symb,$env{'request.course.id'},'graded']);
 2946:                 }
 2947:             }
 2948:             $$record{$key} = join(',',@versioned_portfiles);
 2949:             push(@returned_keys,$key);
 2950:         }
 2951:     } 
 2952:     return (@returned_keys);   
 2953: }
 2954: 
 2955: sub get_next_version {
 2956:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2957:     my $version;
 2958:     foreach my $row (@$dir_list) {
 2959:         my ($file) = split(/\&/,$row,2);
 2960:         my ($file_name,$file_version,$file_ext) =
 2961: 	    &file_name_version_ext($file);
 2962:         if (($file_name eq $answer_name) && 
 2963: 	    ($file_ext eq $answer_ext)) {
 2964:                 # gets here if filename and extension match, regardless of version
 2965:                 if ($file_version ne '') {
 2966:                 # a versioned file is found  so save it for later
 2967:                 if ($file_version > $version) {
 2968: 		    $version = $file_version;
 2969: 	        }
 2970:             }
 2971:         }
 2972:     } 
 2973:     $version ++;
 2974:     return($version);
 2975: }
 2976: 
 2977: sub version_selected_portfile {
 2978:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2979:     my ($answer_name,$answer_ver,$answer_ext) =
 2980:         &file_name_version_ext($file_name);
 2981:     my $new_answer;
 2982:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2983:     if($env{'form.copy'} eq '-1') {
 2984:         $new_answer = 'problem getting file';
 2985:     } else {
 2986:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2987:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2988:                             $stu_name,$domain,'copy',
 2989: 		        '/portfolio'.$directory.$new_answer);
 2990:     }    
 2991:     return ($new_answer);
 2992: }
 2993: 
 2994: sub file_name_version_ext {
 2995:     my ($file)=@_;
 2996:     my @file_parts = split(/\./, $file);
 2997:     my ($name,$version,$ext);
 2998:     if (@file_parts > 1) {
 2999: 	$ext=pop(@file_parts);
 3000: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3001: 	    $version=pop(@file_parts);
 3002: 	}
 3003: 	$name=join('.',@file_parts);
 3004:     } else {
 3005: 	$name=join('.',@file_parts);
 3006:     }
 3007:     return($name,$version,$ext);
 3008: }
 3009: 
 3010: #--------------------------------------------------------------------------------------
 3011: #
 3012: #-------------------------- Next few routines handles grading by section or whole class
 3013: #
 3014: #--- Javascript to handle grading by section or whole class
 3015: sub viewgrades_js {
 3016:     my ($request) = shift;
 3017: 
 3018:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
 3019:     $request->print(<<VIEWJAVASCRIPT);
 3020: <script type="text/javascript" language="javascript">
 3021:    function writePoint(partid,weight,point) {
 3022: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3023: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3024: 	if (point == "textval") {
 3025: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3026: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3027: 		alert("$alertmsg"+parseFloat(point));
 3028: 		var resetbox = false;
 3029: 		for (var i=0; i<radioButton.length; i++) {
 3030: 		    if (radioButton[i].checked) {
 3031: 			textbox.value = i;
 3032: 			resetbox = true;
 3033: 		    }
 3034: 		}
 3035: 		if (!resetbox) {
 3036: 		    textbox.value = "";
 3037: 		}
 3038: 		return;
 3039: 	    }
 3040: 	    if (parseFloat(point) > parseFloat(weight)) {
 3041: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3042: 				   ") greater than the weight for the part. Accept?");
 3043: 		if (resp == false) {
 3044: 		    textbox.value = "";
 3045: 		    return;
 3046: 		}
 3047: 	    }
 3048: 	    for (var i=0; i<radioButton.length; i++) {
 3049: 		radioButton[i].checked=false;
 3050: 		if (parseFloat(point) == i) {
 3051: 		    radioButton[i].checked=true;
 3052: 		}
 3053: 	    }
 3054: 
 3055: 	} else {
 3056: 	    textbox.value = parseFloat(point);
 3057: 	}
 3058: 	for (i=0;i<document.classgrade.total.value;i++) {
 3059: 	    var user = document.classgrade["ctr"+i].value;
 3060: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3061: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3062: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3063: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3064: 	    if (saveval != "correct") {
 3065: 		scorename.value = point;
 3066: 		if (selname[0].selected != true) {
 3067: 		    selname[0].selected = true;
 3068: 		}
 3069: 	    }
 3070: 	}
 3071: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3072:     }
 3073: 
 3074:     function writeRadText(partid,weight) {
 3075: 	var selval   = document.classgrade["SELVAL_"+partid];
 3076: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3077:         var override = document.classgrade["FORCE_"+partid].checked;
 3078: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3079: 	if (selval[1].selected || selval[2].selected) {
 3080: 	    for (var i=0; i<radioButton.length; i++) {
 3081: 		radioButton[i].checked=false;
 3082: 
 3083: 	    }
 3084: 	    textbox.value = "";
 3085: 
 3086: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3087: 		var user = document.classgrade["ctr"+i].value;
 3088: 		user = user.replace(new RegExp(':', 'g'),"_");
 3089: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3090: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3091: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3092: 		if ((saveval != "correct") || override) {
 3093: 		    scorename.value = "";
 3094: 		    if (selval[1].selected) {
 3095: 			selname[1].selected = true;
 3096: 		    } else {
 3097: 			selname[2].selected = true;
 3098: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3099: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3100: 		    }
 3101: 		}
 3102: 	    }
 3103: 	} else {
 3104: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3105: 		var user = document.classgrade["ctr"+i].value;
 3106: 		user = user.replace(new RegExp(':', 'g'),"_");
 3107: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3108: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3109: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3110: 		if ((saveval != "correct") || override) {
 3111: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3112: 		    selname[0].selected = true;
 3113: 		}
 3114: 	    }
 3115: 	}	    
 3116:     }
 3117: 
 3118:     function changeSelect(partid,user) {
 3119: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3120: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3121: 	var point  = textbox.value;
 3122: 	var weight = document.classgrade["weight_"+partid].value;
 3123: 
 3124: 	if (isNaN(point) || parseFloat(point) < 0) {
 3125: 	    alert("$alertmsg"+parseFloat(point));
 3126: 	    textbox.value = "";
 3127: 	    return;
 3128: 	}
 3129: 	if (parseFloat(point) > parseFloat(weight)) {
 3130: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3131: 			       ") greater than the weight of the part. Accept?");
 3132: 	    if (resp == false) {
 3133: 		textbox.value = "";
 3134: 		return;
 3135: 	    }
 3136: 	}
 3137: 	selval[0].selected = true;
 3138:     }
 3139: 
 3140:     function changeOneScore(partid,user) {
 3141: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3142: 	if (selval[1].selected || selval[2].selected) {
 3143: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3144: 	    if (selval[2].selected) {
 3145: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3146: 	    }
 3147:         }
 3148:     }
 3149: 
 3150:     function resetEntry(numpart) {
 3151: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3152: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3153: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3154: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3155: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3156: 	    for (var i=0; i<radioButton.length; i++) {
 3157: 		radioButton[i].checked=false;
 3158: 
 3159: 	    }
 3160: 	    textbox.value = "";
 3161: 	    selval[0].selected = true;
 3162: 
 3163: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3164: 		var user = document.classgrade["ctr"+i].value;
 3165: 		user = user.replace(new RegExp(':', 'g'),"_");
 3166: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3167: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3168: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3169: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3170: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3172: 		if (saveselval == "excused") {
 3173: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3174: 		} else {
 3175: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3176: 		}
 3177: 	    }
 3178: 	}
 3179:     }
 3180: 
 3181: </script>
 3182: VIEWJAVASCRIPT
 3183: }
 3184: 
 3185: #--- show scores for a section or whole class w/ option to change/update a score
 3186: sub viewgrades {
 3187:     my ($request) = shift;
 3188:     &viewgrades_js($request);
 3189: 
 3190:     my ($symb) = &get_symb($request);
 3191:     #need to make sure we have the correct data for later EXT calls, 
 3192:     #thus invalidate the cache
 3193:     &Apache::lonnet::devalidatecourseresdata(
 3194:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3195:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3196:     &Apache::lonnet::clear_EXT_cache_status();
 3197: 
 3198:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3199:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3200: 
 3201:     #view individual student submission form - called using Javascript viewOneStudent
 3202:     $result.=&jscriptNform($symb);
 3203: 
 3204:     #beginning of class grading form
 3205:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3206:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3207: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3208: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3209: 	&build_section_inputs().
 3210: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3211: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3212: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3213: 
 3214:     my ($common_header,$specific_header);
 3215:     if ($env{'form.section'} eq 'all') {
 3216:         $common_header = &mt('Assign Common Grade to Class');
 3217:         $specific_header = &mt('Assign Grade to Specific Students in Class');
 3218:     } elsif ($env{'form.section'} eq 'none') {
 3219:         $common_header = &mt('Assign Common Grade to Students in no Section');
 3220:         $specific_header = &mt('Assign Grade to Specific Students in no Section');
 3221:     } else {
 3222:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3223:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
 3224:         $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
 3225:     }
 3226:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
 3227:     #radio buttons/text box for assigning points for a section or class.
 3228:     #handles different parts of a problem
 3229:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3230:     my %weight = ();
 3231:     my $ctsparts = 0;
 3232:     my %seen = ();
 3233:     my @part_response_id = &flatten_responseType($responseType);
 3234:     foreach my $part_response_id (@part_response_id) {
 3235:     	my ($partid,$respid) = @{ $part_response_id };
 3236: 	my $part_resp = join('_',@{ $part_response_id });
 3237: 	next if $seen{$partid};
 3238: 	$seen{$partid}++;
 3239: 	my $handgrade=$$handgrade{$part_resp};
 3240: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3241: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3242: 
 3243: 	my $display_part=&get_display_part($partid,$symb);
 3244: 	my $radio.='<table border="0"><tr>';  
 3245: 	my $ctr = 0;
 3246: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3247: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3248: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3249: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3250: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3251: 	    $ctr++;
 3252: 	}
 3253: 	$radio.='</tr></table>';
 3254: 	my $line = '<input type="text" name="TEXTVAL_'.
 3255: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3256: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3257: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
 3258: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
 3259: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3260: 		$weight{$partid}.')"> '.
 3261: 	    '<option selected="selected"> </option>'.
 3262: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3263: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3264: 	    '</select></td>'.
 3265:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3266: 	$line.='<input type="hidden" name="partid_'.
 3267: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3268: 	$line.='<input type="hidden" name="weight_'.
 3269: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3270: 
 3271: 	$result.=
 3272: 	    &Apache::loncommon::start_data_table_row()."\n".
 3273:             '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
 3274: 	    &Apache::loncommon::end_data_table_row()."\n";
 3275: 	$ctsparts++;
 3276:     }
 3277:     $result.=&Apache::loncommon::end_data_table()."\n".
 3278: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3279:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3280: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3281: 
 3282:     #table listing all the students in a section/class
 3283:     #header of table
 3284:     $result.= '<h3>'.$specific_header.'</h3>'.
 3285:               &Apache::loncommon::start_data_table().
 3286: 	      &Apache::loncommon::start_data_table_header_row().
 3287: 	      '<th>'.&mt('No.').'</th>'.
 3288: 	      '<th>'.&nameUserString('header')."</th>\n";
 3289:     my (@parts) = sort(&getpartlist($symb));
 3290:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3291:     my @partids = ();
 3292:     foreach my $part (@parts) {
 3293: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3294:         my $narrowtext = &mt('Tries').'<br />';
 3295: 	$display =~ s{^Number of Attempts}{$narrowtext}; # makes the column narrower
 3296: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3297: 	my ($partid) = &split_part_type($part);
 3298:         push(@partids,$partid);
 3299: 	my $display_part=&get_display_part($partid,$symb);
 3300: 	if ($display =~ /^Partial Credit Factor/) {
 3301: 	    $result.='<th>'.
 3302: 		&mt('Score Part: [_1] (weight = [_2])',
 3303: 		    $display_part.'<br />',$weight{$partid}).'</th>'."\n";
 3304: 	    next;
 3305: 	    
 3306: 	} else {
 3307: 	    if ($display =~ /Problem Status/) {
 3308: 		my $grade_status_mt = &mt('Grade Status').'<br />';
 3309: 		$display =~ s{Problem Status}{$grade_status_mt};
 3310: 	    }
 3311: 	    my $part_mt = &mt('Part:');
 3312: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3313: 	}
 3314: 
 3315: 	$result.='<th>'.$display.'</th>'."\n";
 3316:     }
 3317:     $result.=&Apache::loncommon::end_data_table_header_row();
 3318: 
 3319:     my %last_resets = 
 3320: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3321: 
 3322:     #get info for each student
 3323:     #list all the students - with points and grade status
 3324:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3325:     my $ctr = 0;
 3326:     foreach (sort 
 3327: 	     {
 3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3330: 		 }
 3331: 		 return $a cmp $b;
 3332: 	     } (keys(%$fullname))) {
 3333: 	$ctr++;
 3334: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3335: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3336:     }
 3337:     $result.=&Apache::loncommon::end_data_table();
 3338:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3339:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3340: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3341:     if (scalar(%$fullname) eq 0) {
 3342: 	my $colspan=3+scalar(@parts);
 3343: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3344:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3345: 	$result='<span class="LC_warning">'.
 3346: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3347: 	        $section_display, $stu_status).
 3348: 	    '</span>';
 3349:     }
 3350:     $result.=&show_grading_menu_form($symb);
 3351:     return $result;
 3352: }
 3353: 
 3354: #--- call by previous routine to display each student
 3355: sub viewstudentgrade {
 3356:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3357:     my ($uname,$udom) = split(/:/,$student);
 3358:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3359:     my %aggregates = (); 
 3360:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3361: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3362: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3363: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3364: 	'\');" target="_self">'.$fullname.'</a> '.
 3365: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3366:     $student=~s/:/_/; # colon doen't work in javascript for names
 3367:     foreach my $apart (@$parts) {
 3368: 	my ($part,$type) = &split_part_type($apart);
 3369: 	my $score=$record{"resource.$part.$type"};
 3370:         $result.='<td align="center">';
 3371:         my ($aggtries,$totaltries);
 3372:         unless (exists($aggregates{$part})) {
 3373: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3374: 
 3375: 	    $aggtries = $totaltries;
 3376:             if ($$last_resets{$part}) {  
 3377:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3378: 					   $part);
 3379:             }
 3380:             $result.='<input type="hidden" name="'.
 3381:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3382:             $result.='<input type="hidden" name="'.
 3383:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3384:             $aggregates{$part} = 1;
 3385:         }
 3386: 	if ($type eq 'awarded') {
 3387: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3388: 	    $result.='<input type="hidden" name="'.
 3389: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3390: 	    $result.='<input type="text" name="'.
 3391: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3392: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3393: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3394: 	} elsif ($type eq 'solved') {
 3395: 	    my ($status,$foo)=split(/_/,$score,2);
 3396: 	    $status = 'nothing' if ($status eq '');
 3397: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3398: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3399: 	    $result.='&nbsp;<select name="'.
 3400: 		'GD_'.$student.'_'.$part.'_solved" '.
 3401: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3402: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3403: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3404: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3405: 	    $result.="</select>&nbsp;</td>\n";
 3406: 	} else {
 3407: 	    $result.='<input type="hidden" name="'.
 3408: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3409: 		    "\n";
 3410: 	    $result.='<input type="text" name="'.
 3411: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3412: 		'value="'.$score.'" size="4" /></td>'."\n";
 3413: 	}
 3414:     }
 3415:     $result.=&Apache::loncommon::end_data_table_row();
 3416:     return $result;
 3417: }
 3418: 
 3419: #--- change scores for all the students in a section/class
 3420: #    record does not get update if unchanged
 3421: sub editgrades {
 3422:     my ($request) = @_;
 3423: 
 3424:     my $symb=&get_symb($request);
 3425:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3426:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3427:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3428:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3429: 
 3430:     my $result= &Apache::loncommon::start_data_table().
 3431: 	&Apache::loncommon::start_data_table_header_row().
 3432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3434:     my %scoreptr = (
 3435: 		    'correct'  =>'correct_by_override',
 3436: 		    'incorrect'=>'incorrect_by_override',
 3437: 		    'excused'  =>'excused',
 3438: 		    'ungraded' =>'ungraded_attempted',
 3439: 		    'nothing'  => '',
 3440: 		    );
 3441:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3442: 
 3443:     my (@partid);
 3444:     my %weight = ();
 3445:     my %columns = ();
 3446:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3447: 
 3448:     my (@parts) = sort(&getpartlist($symb));
 3449:     my $header;
 3450:     while ($ctr < $env{'form.totalparts'}) {
 3451: 	my $partid = $env{'form.partid_'.$ctr};
 3452: 	push(@partid,$partid);
 3453: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3454: 	$ctr++;
 3455:     }
 3456:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3457:     foreach my $partid (@partid) {
 3458: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3459: 	    '<th align="center">'.&mt('New Score').'</th>';
 3460: 	$columns{$partid}=2;
 3461: 	foreach my $stores (@parts) {
 3462: 	    my ($part,$type) = &split_part_type($stores);
 3463: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3464: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3465: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3466: 	    $display =~ s/\[Part: \Q$part\E\]//;
 3467:             my $narrowtext = &mt('Tries');
 3468: 	    $display =~ s{Number of Attempts}{$narrowtext};
 3469: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
 3470: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
 3471: 	    $columns{$partid}+=2;
 3472: 	}
 3473:     }
 3474:     foreach my $partid (@partid) {
 3475: 	my $display_part=&get_display_part($partid,$symb);
 3476: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3477: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3478: 	    '</th>';
 3479: 
 3480:     }
 3481:     $result .= &Apache::loncommon::end_data_table_header_row().
 3482: 	&Apache::loncommon::start_data_table_header_row().
 3483: 	$header.
 3484: 	&Apache::loncommon::end_data_table_header_row();
 3485:     my @noupdate;
 3486:     my ($updateCtr,$noupdateCtr) = (1,1);
 3487:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3488: 	my $line;
 3489: 	my $user = $env{'form.ctr'.$i};
 3490: 	my ($uname,$udom)=split(/:/,$user);
 3491: 	my %newrecord;
 3492: 	my $updateflag = 0;
 3493: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3494: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3495: 	if (!&canmodify($usec)) {
 3496: 	    my $numcols=scalar(@partid)*4+2;
 3497: 	    push(@noupdate,
 3498: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3499: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3500: 	    next;
 3501: 	}
 3502:         my %aggregate = ();
 3503:         my $aggregateflag = 0;
 3504: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3505: 	foreach (@partid) {
 3506: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3507: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3508: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3509: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3510: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3511: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3512: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3513: 	    my $score;
 3514: 	    if ($partial eq '') {
 3515: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3516: 	    } elsif ($partial > 0) {
 3517: 		$score = 'correct_by_override';
 3518: 	    } elsif ($partial == 0) {
 3519: 		$score = 'incorrect_by_override';
 3520: 	    }
 3521: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3522: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3523: 
 3524: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3525: 		"$env{'user.name'}:$env{'user.domain'}";
 3526: 	    if ($dropMenu eq 'reset status' &&
 3527: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3528: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3529: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3530: 		$newrecord{'resource.'.$_.'.award'} = '';
 3531: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3532: 		$updateflag = 1;
 3533:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3534:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3535:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3536:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3537:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3538:                     $aggregateflag = 1;
 3539:                 }
 3540: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3541: 		$updateflag = 1;
 3542: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3543: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3544: 		$rec_update++;
 3545: 	    }
 3546: 
 3547: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3548: 		'<td align="center">'.$awarded.
 3549: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3550: 
 3551: 
 3552: 	    my $partid=$_;
 3553: 	    foreach my $stores (@parts) {
 3554: 		my ($part,$type) = &split_part_type($stores);
 3555: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3556: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3557: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3558: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3559: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3560: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3561: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3562: 		    $updateflag=1;
 3563: 		}
 3564: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3565: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3566: 	    }
 3567: 	}
 3568: 	$line.="\n";
 3569: 
 3570: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3571: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3572: 
 3573: 	if ($updateflag) {
 3574: 	    $count++;
 3575: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3576: 				    $udom,$uname);
 3577: 
 3578: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3579: 					      $cnum,$udom,$uname)) {
 3580: 		# need to figure out if should be in queue.
 3581: 		my %record =  
 3582: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3583: 					     $udom,$uname);
 3584: 		my $all_graded = 1;
 3585: 		my $none_graded = 1;
 3586: 		foreach my $part (@parts) {
 3587: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3588: 			$all_graded = 0;
 3589: 		    } else {
 3590: 			$none_graded = 0;
 3591: 		    }
 3592: 		}
 3593: 
 3594: 		if ($all_graded || $none_graded) {
 3595: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3596: 							   $symb,$cdom,$cnum,
 3597: 							   $udom,$uname);
 3598: 		}
 3599: 	    }
 3600: 
 3601: 	    $result.=&Apache::loncommon::start_data_table_row().
 3602: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3603: 		&Apache::loncommon::end_data_table_row();
 3604: 	    $updateCtr++;
 3605: 	} else {
 3606: 	    push(@noupdate,
 3607: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3608: 	    $noupdateCtr++;
 3609: 	}
 3610:         if ($aggregateflag) {
 3611:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3612: 				  $cdom,$cnum);
 3613:         }
 3614:     }
 3615:     if (@noupdate) {
 3616: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3617: 	my $numcols=scalar(@partid)*4+2;
 3618: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3619: 	    '<td align="center" colspan="'.$numcols.'">'.
 3620: 	    &mt('No Changes Occurred For the Students Below').
 3621: 	    '</td>'.
 3622: 	    &Apache::loncommon::end_data_table_row();
 3623: 	foreach my $line (@noupdate) {
 3624: 	    $result.=
 3625: 		&Apache::loncommon::start_data_table_row().
 3626: 		$line.
 3627: 		&Apache::loncommon::end_data_table_row();
 3628: 	}
 3629:     }
 3630:     $result .= &Apache::loncommon::end_data_table().
 3631: 	&show_grading_menu_form($symb);
 3632:     my $msg = '<p><b>'.
 3633: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3634: 	    $rec_update,$count).'</b><br />'.
 3635: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3636: 	'</b></p>';
 3637:     return $title.$msg.$result;
 3638: }
 3639: 
 3640: sub split_part_type {
 3641:     my ($partstr) = @_;
 3642:     my ($temp,@allparts)=split(/_/,$partstr);
 3643:     my $type=pop(@allparts);
 3644:     my $part=join('_',@allparts);
 3645:     return ($part,$type);
 3646: }
 3647: 
 3648: #------------- end of section for handling grading by section/class ---------
 3649: #
 3650: #----------------------------------------------------------------------------
 3651: 
 3652: 
 3653: #----------------------------------------------------------------------------
 3654: #
 3655: #-------------------------- Next few routines handles grading by csv upload
 3656: #
 3657: #--- Javascript to handle csv upload
 3658: sub csvupload_javascript_reverse_associate {
 3659:     my $error1=&mt('You need to specify the username or ID');
 3660:     my $error2=&mt('You need to specify at least one grading field');
 3661:   return(<<ENDPICK);
 3662:   function verify(vf) {
 3663:     var foundsomething=0;
 3664:     var founduname=0;
 3665:     var foundID=0;
 3666:     for (i=0;i<=vf.nfields.value;i++) {
 3667:       tw=eval('vf.f'+i+'.selectedIndex');
 3668:       if (i==0 && tw!=0) { foundID=1; }
 3669:       if (i==1 && tw!=0) { founduname=1; }
 3670:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3671:     }
 3672:     if (founduname==0 && foundID==0) {
 3673: 	alert('$error1');
 3674: 	return;
 3675:     }
 3676:     if (foundsomething==0) {
 3677: 	alert('$error2');
 3678: 	return;
 3679:     }
 3680:     vf.submit();
 3681:   }
 3682:   function flip(vf,tf) {
 3683:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3684:     var i;
 3685:     for (i=0;i<=vf.nfields.value;i++) {
 3686:       //can not pick the same destination field for both name and domain
 3687:       if (((i ==0)||(i ==1)) && 
 3688:           ((tf==0)||(tf==1)) && 
 3689:           (i!=tf) &&
 3690:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3691:         eval('vf.f'+i+'.selectedIndex=0;')
 3692:       }
 3693:     }
 3694:   }
 3695: ENDPICK
 3696: }
 3697: 
 3698: sub csvupload_javascript_forward_associate {
 3699:     my $error1=&mt('You need to specify the username or ID');
 3700:     my $error2=&mt('You need to specify at least one grading field');
 3701:   return(<<ENDPICK);
 3702:   function verify(vf) {
 3703:     var foundsomething=0;
 3704:     var founduname=0;
 3705:     var foundID=0;
 3706:     for (i=0;i<=vf.nfields.value;i++) {
 3707:       tw=eval('vf.f'+i+'.selectedIndex');
 3708:       if (tw==1) { foundID=1; }
 3709:       if (tw==2) { founduname=1; }
 3710:       if (tw>3) { foundsomething=1; }
 3711:     }
 3712:     if (founduname==0 && foundID==0) {
 3713: 	alert('$error1');
 3714: 	return;
 3715:     }
 3716:     if (foundsomething==0) {
 3717: 	alert('$error2');
 3718: 	return;
 3719:     }
 3720:     vf.submit();
 3721:   }
 3722:   function flip(vf,tf) {
 3723:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3724:     var i;
 3725:     //can not pick the same destination field twice
 3726:     for (i=0;i<=vf.nfields.value;i++) {
 3727:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3728:         eval('vf.f'+i+'.selectedIndex=0;')
 3729:       }
 3730:     }
 3731:   }
 3732: ENDPICK
 3733: }
 3734: 
 3735: sub csvuploadmap_header {
 3736:     my ($request,$symb,$datatoken,$distotal)= @_;
 3737:     my $javascript;
 3738:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3739: 	$javascript=&csvupload_javascript_reverse_associate();
 3740:     } else {
 3741: 	$javascript=&csvupload_javascript_forward_associate();
 3742:     }
 3743: 
 3744:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3745:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3746:     my $ignore=&mt('Ignore First Line');
 3747:     $symb = &Apache::lonenc::check_encrypt($symb);
 3748:     $request->print(<<ENDPICK);
 3749: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3750: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3751: $result
 3752: <hr />
 3753: <h3>Identify fields</h3>
 3754: Total number of records found in file: $distotal <hr />
 3755: Enter as many fields as you can. The system will inform you and bring you back
 3756: to this page if the data selected is insufficient to run your class.<hr />
 3757: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3758: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3759: <input type="hidden" name="associate"  value="" />
 3760: <input type="hidden" name="phase"      value="three" />
 3761: <input type="hidden" name="datatoken"  value="$datatoken" />
 3762: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3763: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3764: <input type="hidden" name="upfile_associate" 
 3765:                                        value="$env{'form.upfile_associate'}" />
 3766: <input type="hidden" name="symb"       value="$symb" />
 3767: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3768: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3769: <input type="hidden" name="command"    value="csvuploadoptions" />
 3770: <hr />
 3771: <script type="text/javascript" language="Javascript">
 3772: $javascript
 3773: </script>
 3774: ENDPICK
 3775:     return '';
 3776: 
 3777: }
 3778: 
 3779: sub csvupload_fields {
 3780:     my ($symb) = @_;
 3781:     my (@parts) = &getpartlist($symb);
 3782:     my @fields=(['ID','Student ID'],
 3783: 		['username','Student Username'],
 3784: 		['domain','Student Domain']);
 3785:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3786:     foreach my $part (sort(@parts)) {
 3787: 	my @datum;
 3788: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3789: 	my $name=$part;
 3790: 	if  (!$display) { $display = $name; }
 3791: 	@datum=($name,$display);
 3792: 	if ($name=~/^stores_(.*)_awarded/) {
 3793: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3794: 	}
 3795: 	push(@fields,\@datum);
 3796:     }
 3797:     return (@fields);
 3798: }
 3799: 
 3800: sub csvuploadmap_footer {
 3801:     my ($request,$i,$keyfields) =@_;
 3802:     $request->print(<<ENDPICK);
 3803: </table>
 3804: <input type="hidden" name="nfields" value="$i" />
 3805: <input type="hidden" name="keyfields" value="$keyfields" />
 3806: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3807: </form>
 3808: ENDPICK
 3809: }
 3810: 
 3811: sub checkforfile_js {
 3812:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
 3813:     my $result =<<CSVFORMJS;
 3814: <script type="text/javascript" language="javascript">
 3815:     function checkUpload(formname) {
 3816: 	if (formname.upfile.value == "") {
 3817: 	    alert("$alertmsg");
 3818: 	    return false;
 3819: 	}
 3820: 	formname.submit();
 3821:     }
 3822:     </script>
 3823: CSVFORMJS
 3824:     return $result;
 3825: }
 3826: 
 3827: sub upcsvScores_form {
 3828:     my ($request) = shift;
 3829:     my ($symb)=&get_symb($request);
 3830:     if (!$symb) {return '';}
 3831:     my $result=&checkforfile_js();
 3832:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3833:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3834:     $result.=$table;
 3835:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3836:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3837:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
 3838: 	'.</b></td></tr>'."\n";
 3839:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3840:     my $upload=&mt("Upload Scores");
 3841:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3842:     my $ignore=&mt('Ignore First Line');
 3843:     $symb = &Apache::lonenc::check_encrypt($symb);
 3844:     $result.=<<ENDUPFORM;
 3845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3846: <input type="hidden" name="symb" value="$symb" />
 3847: <input type="hidden" name="command" value="csvuploadmap" />
 3848: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3849: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3850: $upfile_select
 3851: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3852: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3853: </form>
 3854: ENDUPFORM
 3855:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3856:                            &mt("How do I create a CSV file from a spreadsheet"))
 3857:     .'</td></tr></table>'."\n";
 3858:     $result.='</td></tr></table><br /><br />'."\n";
 3859:     $result.=&show_grading_menu_form($symb);
 3860:     return $result;
 3861: }
 3862: 
 3863: 
 3864: sub csvuploadmap {
 3865:     my ($request)= @_;
 3866:     my ($symb)=&get_symb($request);
 3867:     if (!$symb) {return '';}
 3868: 
 3869:     my $datatoken;
 3870:     if (!$env{'form.datatoken'}) {
 3871: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3872:     } else {
 3873: 	$datatoken=$env{'form.datatoken'};
 3874: 	&Apache::loncommon::load_tmp_file($request);
 3875:     }
 3876:     my @records=&Apache::loncommon::upfile_record_sep();
 3877:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3878:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3879:     my ($i,$keyfields);
 3880:     if (@records) {
 3881: 	my @fields=&csvupload_fields($symb);
 3882: 
 3883: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3884: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3885: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3886: 							  \@fields);
 3887: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3888: 	    chop($keyfields);
 3889: 	} else {
 3890: 	    unshift(@fields,['none','']);
 3891: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3892: 							    \@fields);
 3893:             foreach my $rec (@records) {
 3894:                 my %temp = &Apache::loncommon::record_sep($rec);
 3895:                 if (%temp) {
 3896:                     $keyfields=join(',',sort(keys(%temp)));
 3897:                     last;
 3898:                 }
 3899:             }
 3900: 	}
 3901:     }
 3902:     &csvuploadmap_footer($request,$i,$keyfields);
 3903:     $request->print(&show_grading_menu_form($symb));
 3904: 
 3905:     return '';
 3906: }
 3907: 
 3908: sub csvuploadoptions {
 3909:     my ($request)= @_;
 3910:     my ($symb)=&get_symb($request);
 3911:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3912:     my $ignore=&mt('Ignore First Line');
 3913:     $request->print(<<ENDPICK);
 3914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3915: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3916: <input type="hidden" name="command"    value="csvuploadassign" />
 3917: <!--
 3918: <p>
 3919: <label>
 3920:    <input type="checkbox" name="show_full_results" />
 3921:    Show a table of all changes
 3922: </label>
 3923: </p>
 3924: -->
 3925: <p>
 3926: <label>
 3927:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3928:    Overwrite any existing score
 3929: </label>
 3930: </p>
 3931: ENDPICK
 3932:     my %fields=&get_fields();
 3933:     if (!defined($fields{'domain'})) {
 3934: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3935: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3936:     }
 3937:     foreach my $key (sort(keys(%env))) {
 3938: 	if ($key !~ /^form\.(.*)$/) { next; }
 3939: 	my $cleankey=$1;
 3940: 	if ($cleankey eq 'command') { next; }
 3941: 	$request->print('<input type="hidden" name="'.$cleankey.
 3942: 			'"  value="'.$env{$key}.'" />'."\n");
 3943:     }
 3944:     # FIXME do a check for any duplicated user ids...
 3945:     # FIXME do a check for any invalid user ids?...
 3946:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3947: <hr /></form>'."\n");
 3948:     $request->print(&show_grading_menu_form($symb));
 3949:     return '';
 3950: }
 3951: 
 3952: sub get_fields {
 3953:     my %fields;
 3954:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3955:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3956: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3957: 	    if ($env{'form.f'.$i} ne 'none') {
 3958: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3959: 	    }
 3960: 	} else {
 3961: 	    if ($env{'form.f'.$i} ne 'none') {
 3962: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3963: 	    }
 3964: 	}
 3965:     }
 3966:     return %fields;
 3967: }
 3968: 
 3969: sub csvuploadassign {
 3970:     my ($request)= @_;
 3971:     my ($symb)=&get_symb($request);
 3972:     if (!$symb) {return '';}
 3973:     my $error_msg = '';
 3974:     &Apache::loncommon::load_tmp_file($request);
 3975:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3976:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3977:     my %fields=&get_fields();
 3978:     $request->print('<h3>Assigning Grades</h3>');
 3979:     my $courseid=$env{'request.course.id'};
 3980:     my ($classlist) = &getclasslist('all',0);
 3981:     my @notallowed;
 3982:     my @skipped;
 3983:     my $countdone=0;
 3984:     foreach my $grade (@gradedata) {
 3985: 	my %entries=&Apache::loncommon::record_sep($grade);
 3986: 	my $domain;
 3987: 	if ($entries{$fields{'domain'}}) {
 3988: 	    $domain=$entries{$fields{'domain'}};
 3989: 	} else {
 3990: 	    $domain=$env{'form.default_domain'};
 3991: 	}
 3992: 	$domain=~s/\s//g;
 3993: 	my $username=$entries{$fields{'username'}};
 3994: 	$username=~s/\s//g;
 3995: 	if (!$username) {
 3996: 	    my $id=$entries{$fields{'ID'}};
 3997: 	    $id=~s/\s//g;
 3998: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3999: 	    $username=$ids{$id};
 4000: 	}
 4001: 	if (!exists($$classlist{"$username:$domain"})) {
 4002: 	    my $id=$entries{$fields{'ID'}};
 4003: 	    $id=~s/\s//g;
 4004: 	    if ($id) {
 4005: 		push(@skipped,"$id:$domain");
 4006: 	    } else {
 4007: 		push(@skipped,"$username:$domain");
 4008: 	    }
 4009: 	    next;
 4010: 	}
 4011: 	my $usec=$classlist->{"$username:$domain"}[5];
 4012: 	if (!&canmodify($usec)) {
 4013: 	    push(@notallowed,"$username:$domain");
 4014: 	    next;
 4015: 	}
 4016: 	my %points;
 4017: 	my %grades;
 4018: 	foreach my $dest (keys(%fields)) {
 4019: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4020: 		$dest eq 'domain') { next; }
 4021: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4022: 	    if ($dest=~/stores_(.*)_points/) {
 4023: 		my $part=$1;
 4024: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4025: 					      $symb,$domain,$username);
 4026:                 if ($wgt) {
 4027:                     $entries{$fields{$dest}}=~s/\s//g;
 4028:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4029:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4030:                                           : 'correct_by_override';
 4031:                     $grades{"resource.$part.awarded"}=$pcr;
 4032:                     $grades{"resource.$part.solved"}=$award;
 4033:                     $points{$part}=1;
 4034:                 } else {
 4035:                     $error_msg = "<br />" .
 4036:                         &mt("Some point values were assigned"
 4037:                             ." for problems with a weight "
 4038:                             ."of zero. These values were "
 4039:                             ."ignored.");
 4040:                 }
 4041: 	    } else {
 4042: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4043: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4044: 		my $store_key=$dest;
 4045: 		$store_key=~s/^stores/resource/;
 4046: 		$store_key=~s/_/\./g;
 4047: 		$grades{$store_key}=$entries{$fields{$dest}};
 4048: 	    }
 4049: 	}
 4050: 	if (! %grades) { 
 4051:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4052:         } else {
 4053: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4054: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4055: 					   $env{'request.course.id'},
 4056: 					   $domain,$username);
 4057: 	   if ($result eq 'ok') {
 4058: 	      $request->print('.');
 4059: 	   } else {
 4060: 	      $request->print("<p><span class=\"LC_error\">".
 4061:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4062:                                   "$username:$domain",$result)."</span></p>");
 4063: 	   }
 4064: 	   $request->rflush();
 4065: 	   $countdone++;
 4066:         }
 4067:     }
 4068:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4069:     if (@skipped) {
 4070: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4071: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4072:     }
 4073:     if (@notallowed) {
 4074: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4075: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4076:     }
 4077:     $request->print("<br />\n");
 4078:     $request->print(&show_grading_menu_form($symb));
 4079:     return $error_msg;
 4080: }
 4081: #------------- end of section for handling csv file upload ---------
 4082: #
 4083: #-------------------------------------------------------------------
 4084: #
 4085: #-------------- Next few routines handle grading by page/sequence
 4086: #
 4087: #--- Select a page/sequence and a student to grade
 4088: sub pickStudentPage {
 4089:     my ($request) = shift;
 4090: 
 4091:     my $alertmsg = &mt('Please select the student you wish to grade.');
 4092:     $request->print(<<LISTJAVASCRIPT);
 4093: <script type="text/javascript" language="javascript">
 4094: 
 4095: function checkPickOne(formname) {
 4096:     if (radioSelection(formname.student) == null) {
 4097: 	alert("$alertmsg");
 4098: 	return;
 4099:     }
 4100:     ptr = pullDownSelection(formname.selectpage);
 4101:     formname.page.value = formname["page"+ptr].value;
 4102:     formname.title.value = formname["title"+ptr].value;
 4103:     formname.submit();
 4104: }
 4105: 
 4106: </script>
 4107: LISTJAVASCRIPT
 4108:     &commonJSfunctions($request);
 4109:     my ($symb) = &get_symb($request);
 4110:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4111:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4112:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4113: 
 4114:     my $result='<h3><span class="LC_info">&nbsp;'.
 4115: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4116: 
 4117:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4118:     my ($titles,$symbx) = &getSymbMap();
 4119:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4120: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4121: #    my $type=($curpage =~ /\.(page|sequence)/);
 4122:     my $select = '<select name="selectpage">'."\n";
 4123:     my $ctr=0;
 4124:     foreach (@$titles) {
 4125: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4126: 	$select.='<option value="'.$ctr.'" '.
 4127: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4128: 	    '>'.$showtitle.'</option>'."\n";
 4129: 	$ctr++;
 4130:     }
 4131:     $select.= '</select>';
 4132:     $result.='&nbsp;<b>'.&mt('Problems from').":</b> $select<br />\n";
 4133: 
 4134:     $ctr=0;
 4135:     foreach (@$titles) {
 4136: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4137: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4138: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4139: 	$ctr++;
 4140:     }
 4141:     $result.='<input type="hidden" name="page" />'."\n".
 4142: 	'<input type="hidden" name="title" />'."\n";
 4143: 
 4144:     my $options =
 4145: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4146: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4147:     $result.='&nbsp;<b>'.&mt('View Problem Text').": </b> $options";
 4148: 
 4149:     $options =
 4150: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4151: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4152: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4153:     $result.='&nbsp;>b>'.&mt('Submissions').": </b>$options";
 4154:     
 4155:     $result.=&build_section_inputs();
 4156:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4157:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4158: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4159: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4160: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4161: 
 4162:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /><br />'."\n";
 4163: 
 4164:     $result.='&nbsp;<input type="button" '.
 4165: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
 4166: 
 4167:     $request->print($result);
 4168: 
 4169:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4170: 	&Apache::loncommon::start_data_table().
 4171: 	&Apache::loncommon::start_data_table_header_row().
 4172: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4173: 	'<th>'.&nameUserString('header').'</th>'.
 4174: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4175: 	'<th>'.&nameUserString('header').'</th>'.
 4176: 	&Apache::loncommon::end_data_table_header_row();
 4177:  
 4178:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4179:     my $ptr = 1;
 4180:     foreach my $student (sort 
 4181: 			 {
 4182: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4183: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4184: 			     }
 4185: 			     return $a cmp $b;
 4186: 			 } (keys(%$fullname))) {
 4187: 	my ($uname,$udom) = split(/:/,$student);
 4188: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4189:                                   : '</td>');
 4190: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4191: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4192: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4193: 	$studentTable.=
 4194: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4195:                          : '');
 4196: 	$ptr++;
 4197:     }
 4198:     if ($ptr%2 == 0) {
 4199: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4200: 	    &Apache::loncommon::end_data_table_row();
 4201:     }
 4202:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4203:     $studentTable.='<input type="button" '.
 4204: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4205: 
 4206:     $studentTable.=&show_grading_menu_form($symb);
 4207:     $request->print($studentTable);
 4208: 
 4209:     return '';
 4210: }
 4211: 
 4212: sub getSymbMap {
 4213:     my $navmap = Apache::lonnavmaps::navmap->new();
 4214: 
 4215:     my %symbx = ();
 4216:     my @titles = ();
 4217:     my $minder = 0;
 4218: 
 4219:     # Gather every sequence that has problems.
 4220:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4221: 					       1,0,1);
 4222:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4223: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4224: 	    my $title = $minder.'.'.
 4225: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4226: 	    push(@titles, $title); # minder in case two titles are identical
 4227: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4228: 	    $minder++;
 4229: 	}
 4230:     }
 4231:     return \@titles,\%symbx;
 4232: }
 4233: 
 4234: #
 4235: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4236: sub displayPage {
 4237:     my ($request) = shift;
 4238: 
 4239:     my ($symb) = &get_symb($request);
 4240:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4241:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4242:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4243:     my $pageTitle = $env{'form.page'};
 4244:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4245:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4246:     my $usec=$classlist->{$env{'form.student'}}[5];
 4247: 
 4248:     #need to make sure we have the correct data for later EXT calls, 
 4249:     #thus invalidate the cache
 4250:     &Apache::lonnet::devalidatecourseresdata(
 4251:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4252:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4253:     &Apache::lonnet::clear_EXT_cache_status();
 4254: 
 4255:     if (!&canview($usec)) {
 4256: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4257: 	$request->print(&show_grading_menu_form($symb));
 4258: 	return;
 4259:     }
 4260:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4261:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4262: 	'</h3>'."\n";
 4263:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4264:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4265: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4266:     } else {
 4267: 	delete($env{'form.CODE'});
 4268:     }
 4269:     &sub_page_js($request);
 4270:     $request->print($result);
 4271: 
 4272:     my $navmap = Apache::lonnavmaps::navmap->new();
 4273:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4274:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4275:     if (!$map) {
 4276: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4277: 	$request->print(&show_grading_menu_form($symb));
 4278: 	return; 
 4279:     }
 4280:     my $iterator = $navmap->getIterator($map->map_start(),
 4281: 					$map->map_finish());
 4282: 
 4283:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4284: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4285: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4286: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4287: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4288: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4289: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4290: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4291: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4292: 
 4293:     if (defined($env{'form.CODE'})) {
 4294: 	$studentTable.=
 4295: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4296:     }
 4297:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4298: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4299: 
 4300:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4301: 	&Apache::loncommon::start_data_table().
 4302: 	&Apache::loncommon::start_data_table_header_row().
 4303: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4304: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4305: 	&Apache::loncommon::end_data_table_header_row();
 4306: 
 4307:     &Apache::lonxml::clear_problem_counter();
 4308:     my ($depth,$question,$prob) = (1,1,1);
 4309:     $iterator->next(); # skip the first BEGIN_MAP
 4310:     my $curRes = $iterator->next(); # for "current resource"
 4311:     while ($depth > 0) {
 4312:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4313:         if($curRes == $iterator->END_MAP) { $depth--; }
 4314: 
 4315:         if (ref($curRes) && $curRes->is_problem()) {
 4316: 	    my $parts = $curRes->parts();
 4317:             my $title = $curRes->compTitle();
 4318: 	    my $symbx = $curRes->symb();
 4319: 	    $studentTable.=
 4320: 		&Apache::loncommon::start_data_table_row().
 4321: 		'<td align="center" valign="top" >'.$prob.
 4322: 		(scalar(@{$parts}) == 1 ? '' 
 4323: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4324: 							scalar(@{$parts}))
 4325: 		 ).
 4326: 		 '</td>';
 4327: 	    $studentTable.='<td valign="top">';
 4328: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4329: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4330: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4331: 					     undef,'both',\%form);
 4332: 	    } else {
 4333: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4334: 		$companswer =~ s|<form(.*?)>||g;
 4335: 		$companswer =~ s|</form>||g;
 4336: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4337: #		    $companswer =~ s/$1/ /ms;
 4338: #		    $request->print('match='.$1."<br />\n");
 4339: #		}
 4340: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4341: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
 4342: 	    }
 4343: 
 4344: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4345: 
 4346: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4347: 		if ($record{'version'} eq '') {
 4348: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4349: 		} else {
 4350: 		    my %responseType = ();
 4351: 		    foreach my $partid (@{$parts}) {
 4352: 			my @responseIds =$curRes->responseIds($partid);
 4353: 			my @responseType =$curRes->responseType($partid);
 4354: 			my %responseIds;
 4355: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4356: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4357: 			}
 4358: 			$responseType{$partid} = \%responseIds;
 4359: 		    }
 4360: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4361: 
 4362: 		}
 4363: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4364: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4365: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4366: 									$env{'request.course.id'},
 4367: 									'','.submission');
 4368:  
 4369: 	    }
 4370: 	    if (&canmodify($usec)) {
 4371: 		foreach my $partid (@{$parts}) {
 4372: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4373: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4374: 		    $question++;
 4375: 		}
 4376: 		$prob++;
 4377: 	    }
 4378: 	    $studentTable.='</td></tr>';
 4379: 
 4380: 	}
 4381:         $curRes = $iterator->next();
 4382:     }
 4383: 
 4384:     $studentTable.='</table>'."\n".
 4385: 	'<input type="button" value="'.&mt('Save').'" '.
 4386: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4387: 	'</form>'."\n";
 4388:     $studentTable.=&show_grading_menu_form($symb);
 4389:     $request->print($studentTable);
 4390: 
 4391:     return '';
 4392: }
 4393: 
 4394: sub displaySubByDates {
 4395:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4396:     my $isCODE=0;
 4397:     my $isTask = ($symb =~/\.task$/);
 4398:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4399:     my $studentTable=&Apache::loncommon::start_data_table().
 4400: 	&Apache::loncommon::start_data_table_header_row().
 4401: 	'<th>'.&mt('Date/Time').'</th>'.
 4402: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4403: 	'<th>'.&mt('Submission').'</th>'.
 4404: 	'<th>'.&mt('Status').'</th>'.
 4405: 	&Apache::loncommon::end_data_table_header_row();
 4406:     my ($version);
 4407:     my %mark;
 4408:     my %orders;
 4409:     $mark{'correct_by_student'} = $checkIcon;
 4410:     if (!exists($$record{'1:timestamp'})) {
 4411: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
 4412:     }
 4413: 
 4414:     my $interaction;
 4415:     my $no_increment = 1;
 4416:     for ($version=1;$version<=$$record{'version'};$version++) {
 4417: 	my $timestamp = 
 4418: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4419: 	if (exists($$record{$version.':resource.0.version'})) {
 4420: 	    $interaction = $$record{$version.':resource.0.version'};
 4421: 	}
 4422: 
 4423: 	my $where = ($isTask ? "$version:resource.$interaction"
 4424: 		             : "$version:resource");
 4425: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4426: 	    '<td>'.$timestamp.'</td>';
 4427: 	if ($isCODE) {
 4428: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4429: 	}
 4430: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4431: 	my @displaySub = ();
 4432: 	foreach my $partid (@{$parts}) {
 4433: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4434: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4435: 	    
 4436: 
 4437: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4438: 	    my $display_part=&get_display_part($partid,$symb);
 4439: 	    foreach my $matchKey (@matchKey) {
 4440: 		if (exists($$record{$version.':'.$matchKey}) &&
 4441: 		    $$record{$version.':'.$matchKey} ne '') {
 4442: 
 4443: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4444: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4445: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4446: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4447: 			$responseId.')</span>&nbsp;<b>';
 4448: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4449: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4450: 		    } else {
 4451: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4452: 					    $$record{"$where.$partid.tries"});
 4453: 		    }
 4454: 		    my $responseType=($isTask ? 'Task'
 4455:                                               : $responseType->{$partid}->{$responseId});
 4456: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4457: 		    if (!exists($orders{$partid}->{$responseId})) {
 4458: 			$orders{$partid}->{$responseId}=
 4459: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4460:                                        $no_increment);
 4461: 		    }
 4462: 		    $displaySub[0].='</b>&nbsp; '.
 4463: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4464: 		}
 4465: 	    }
 4466: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4467: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4468: 				    $$record{"$where.$partid.checkedin"},
 4469: 				    $$record{"$where.$partid.checkedin.slot"}).
 4470: 					'<br />';
 4471: 	    }
 4472: 	    if (exists $$record{"$where.$partid.award"}) {
 4473: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4474: 		    lc($$record{"$where.$partid.award"}).' '.
 4475: 		    $mark{$$record{"$where.$partid.solved"}}.
 4476: 		    '<br />';
 4477: 	    }
 4478: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4479: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4480: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4481: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4482: 		$displaySub[2].=
 4483: 		    $$record{"$version:resource.$partid.regrader"}.
 4484: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4485: 	    }
 4486: 	}
 4487: 	# needed because old essay regrader has not parts info
 4488: 	if (exists $$record{"$version:resource.regrader"}) {
 4489: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4490: 	}
 4491: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4492: 	if ($displaySub[2]) {
 4493: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4494: 	}
 4495: 	$studentTable.='&nbsp;</td>'.
 4496: 	    &Apache::loncommon::end_data_table_row();
 4497:     }
 4498:     $studentTable.=&Apache::loncommon::end_data_table();
 4499:     return $studentTable;
 4500: }
 4501: 
 4502: sub updateGradeByPage {
 4503:     my ($request) = shift;
 4504: 
 4505:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4506:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4507:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4508:     my $pageTitle = $env{'form.page'};
 4509:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4510:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4511:     my $usec=$classlist->{$env{'form.student'}}[5];
 4512:     if (!&canmodify($usec)) {
 4513: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4514: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4515: 	return;
 4516:     }
 4517:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4518:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4519: 	'</h3>'."\n";
 4520: 
 4521:     $request->print($result);
 4522: 
 4523:     my $navmap = Apache::lonnavmaps::navmap->new();
 4524:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4525:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4526:     if (!$map) {
 4527: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4528: 	my ($symb)=&get_symb($request);
 4529: 	$request->print(&show_grading_menu_form($symb));
 4530: 	return; 
 4531:     }
 4532:     my $iterator = $navmap->getIterator($map->map_start(),
 4533: 					$map->map_finish());
 4534: 
 4535:     my $studentTable=
 4536: 	&Apache::loncommon::start_data_table().
 4537: 	&Apache::loncommon::start_data_table_header_row().
 4538: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4539: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4540: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4541: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4542: 	&Apache::loncommon::end_data_table_header_row();
 4543: 
 4544:     $iterator->next(); # skip the first BEGIN_MAP
 4545:     my $curRes = $iterator->next(); # for "current resource"
 4546:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4547:     while ($depth > 0) {
 4548:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4549:         if($curRes == $iterator->END_MAP) { $depth--; }
 4550: 
 4551:         if (ref($curRes) && $curRes->is_problem()) {
 4552: 	    my $parts = $curRes->parts();
 4553:             my $title = $curRes->compTitle();
 4554: 	    my $symbx = $curRes->symb();
 4555: 	    $studentTable.=
 4556: 		&Apache::loncommon::start_data_table_row().
 4557: 		'<td align="center" valign="top" >'.$prob.
 4558: 		(scalar(@{$parts}) == 1 ? '' 
 4559:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4560: 		.')').'</td>';
 4561: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4562: 
 4563: 	    my %newrecord=();
 4564: 	    my @displayPts=();
 4565:             my %aggregate = ();
 4566:             my $aggregateflag = 0;
 4567: 	    foreach my $partid (@{$parts}) {
 4568: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4569: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4570: 
 4571: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4572: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4573: 		my $partial = $newpts/$wgt;
 4574: 		my $score;
 4575: 		if ($partial > 0) {
 4576: 		    $score = 'correct_by_override';
 4577: 		} elsif ($newpts ne '') { #empty is taken as 0
 4578: 		    $score = 'incorrect_by_override';
 4579: 		}
 4580: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4581: 		if ($dropMenu eq 'excused') {
 4582: 		    $partial = '';
 4583: 		    $score = 'excused';
 4584: 		} elsif ($dropMenu eq 'reset status'
 4585: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4586: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4587: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4588: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4589: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4590: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4591: 		    $changeflag++;
 4592: 		    $newpts = '';
 4593:                     
 4594:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4595:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4596:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4597:                     if ($aggtries > 0) {
 4598:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4599:                         $aggregateflag = 1;
 4600:                     }
 4601: 		}
 4602: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4603: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4604: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4605: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4606: 		    '&nbsp;<br />';
 4607: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4608: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4609: 		    '&nbsp;<br />';
 4610: 		$question++;
 4611: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4612: 
 4613: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4614: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4615: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4616: 		    if (scalar(keys(%newrecord)) > 0);
 4617: 
 4618: 		$changeflag++;
 4619: 	    }
 4620: 	    if (scalar(keys(%newrecord)) > 0) {
 4621: 		my %record = 
 4622: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4623: 					     $udom,$uname);
 4624: 
 4625: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4626: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4627: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4628: 		    $newrecord{'resource.CODE'} = '';
 4629: 		}
 4630: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4631: 					$udom,$uname);
 4632: 		%record = &Apache::lonnet::restore($symbx,
 4633: 						   $env{'request.course.id'},
 4634: 						   $udom,$uname);
 4635: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4636: 					     $cdom,$cnum,$udom,$uname);
 4637: 	    }
 4638: 	    
 4639:             if ($aggregateflag) {
 4640:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4641:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4642:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4643:             }
 4644: 
 4645: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4646: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4647: 		&Apache::loncommon::end_data_table_row();
 4648: 
 4649: 	    $prob++;
 4650: 	}
 4651:         $curRes = $iterator->next();
 4652:     }
 4653: 
 4654:     $studentTable.=&Apache::loncommon::end_data_table();
 4655:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4656:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4657: 		  &mt('The scores were changed for [quant,_1,problem].',
 4658: 		  $changeflag));
 4659:     $request->print($grademsg.$studentTable);
 4660: 
 4661:     return '';
 4662: }
 4663: 
 4664: #-------- end of section for handling grading by page/sequence ---------
 4665: #
 4666: #-------------------------------------------------------------------
 4667: 
 4668: #--------------------Scantron Grading-----------------------------------
 4669: #
 4670: #------ start of section for handling grading by page/sequence ---------
 4671: 
 4672: =pod
 4673: 
 4674: =head1 Bubble sheet grading routines
 4675: 
 4676:   For this documentation:
 4677: 
 4678:    'scanline' refers to the full line of characters
 4679:    from the file that we are parsing that represents one entire sheet
 4680: 
 4681:    'bubble line' refers to the data
 4682:    representing the line of bubbles that are on the physical bubble sheet
 4683: 
 4684: 
 4685: The overall process is that a scanned in bubble sheet data is uploaded
 4686: into a course. When a user wants to grade, they select a
 4687: sequence/folder of resources, a file of bubble sheet info, and pick
 4688: one of the predefined configurations for what each scanline looks
 4689: like.
 4690: 
 4691: Next each scanline is checked for any errors of either 'missing
 4692: bubbles' (it's an error because it may have been mis-scanned
 4693: because too light bubbling), 'double bubble' (each bubble line should
 4694: have no more that one letter picked), invalid or duplicated CODE,
 4695: invalid student ID
 4696: 
 4697: If the CODE option is used that determines the randomization of the
 4698: homework problems, either way the student ID is looked up into a
 4699: username:domain.
 4700: 
 4701: During the validation phase the instructor can choose to skip scanlines. 
 4702: 
 4703: After the validation phase, there are now 3 bubble sheet files
 4704: 
 4705:   scantron_original_filename (unmodified original file)
 4706:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4707:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4708: 
 4709: Also there is a separate hash nohist_scantrondata that contains extra
 4710: correction information that isn't representable in the bubble sheet
 4711: file (see &scantron_getfile() for more information)
 4712: 
 4713: After all scanlines are either valid, marked as valid or skipped, then
 4714: foreach line foreach problem in the picked sequence, an ssi request is
 4715: made that simulates a user submitting their selected letter(s) against
 4716: the homework problem.
 4717: 
 4718: =over 4
 4719: 
 4720: 
 4721: 
 4722: =item defaultFormData
 4723: 
 4724:   Returns html hidden inputs used to hold context/default values.
 4725: 
 4726:  Arguments:
 4727:   $symb - $symb of the current resource 
 4728: 
 4729: =cut
 4730: 
 4731: sub defaultFormData {
 4732:     my ($symb)=@_;
 4733:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4734:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4735:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4736: }
 4737: 
 4738: 
 4739: =pod 
 4740: 
 4741: =item getSequenceDropDown
 4742: 
 4743:    Return html dropdown of possible sequences to grade
 4744:  
 4745:  Arguments:
 4746:    $symb - $symb of the current resource 
 4747: 
 4748: =cut
 4749: 
 4750: sub getSequenceDropDown {
 4751:     my ($symb)=@_;
 4752:     my $result='<select name="selectpage">'."\n";
 4753:     my ($titles,$symbx) = &getSymbMap();
 4754:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4755:     my $ctr=0;
 4756:     foreach (@$titles) {
 4757: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4758: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4759: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4760: 	    '>'.$showtitle.'</option>'."\n";
 4761: 	$ctr++;
 4762:     }
 4763:     $result.= '</select>';
 4764:     return $result;
 4765: }
 4766: 
 4767: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4768:                                    # index is "symb.part_id"
 4769: 
 4770: my %first_bubble_line;             # First bubble line no. for each bubble.
 4771: 
 4772: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4773:                                    # matchresponse or rankresponse, where 
 4774:                                    # an individual response can have multiple 
 4775:                                    # lines
 4776: 
 4777: my %responsetype_per_response;     # responsetype for each response
 4778: 
 4779: # Save and restore the bubble lines array to the form env.
 4780: 
 4781: 
 4782: sub save_bubble_lines {
 4783:     foreach my $line (keys(%bubble_lines_per_response)) {
 4784: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4785: 	$env{"form.scantron.first_bubble_line.$line"} =
 4786: 	    $first_bubble_line{$line};
 4787:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4788:             $subdivided_bubble_lines{$line};
 4789:         $env{"form.scantron.responsetype.$line"} =
 4790:             $responsetype_per_response{$line};
 4791:     }
 4792: }
 4793: 
 4794: 
 4795: sub restore_bubble_lines {
 4796:     my $line = 0;
 4797:     %bubble_lines_per_response = ();
 4798:     while ($env{"form.scantron.bubblelines.$line"}) {
 4799: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4800: 	$bubble_lines_per_response{$line} = $value;
 4801: 	$first_bubble_line{$line}  =
 4802: 	    $env{"form.scantron.first_bubble_line.$line"};
 4803:         $subdivided_bubble_lines{$line} =
 4804:             $env{"form.scantron.sub_bubblelines.$line"};
 4805:         $responsetype_per_response{$line} =
 4806:             $env{"form.scantron.responsetype.$line"};
 4807: 	$line++;
 4808:     }
 4809: 
 4810: }
 4811: 
 4812: #  Given the parsed scanline, get the response for 
 4813: #  'answer' number n:
 4814: 
 4815: sub get_response_bubbles {
 4816:     my ($parsed_line, $response)  = @_;
 4817: 
 4818: 
 4819:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4820:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4821:     
 4822:     my $selected = "";
 4823: 
 4824:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4825: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4826: 	$bubble_line++;
 4827:     }
 4828:     return $selected;
 4829: }
 4830: 
 4831: =pod 
 4832: 
 4833: =item scantron_filenames
 4834: 
 4835:    Returns a list of the scantron files in the current course 
 4836: 
 4837: =cut
 4838: 
 4839: sub scantron_filenames {
 4840:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4841:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4842:     my $getpropath = 1;
 4843:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4844:                                        $getpropath);
 4845:     my @possiblenames;
 4846:     foreach my $filename (sort(@files)) {
 4847: 	($filename)=split(/&/,$filename);
 4848: 	if ($filename!~/^scantron_orig_/) { next ; }
 4849: 	$filename=~s/^scantron_orig_//;
 4850: 	push(@possiblenames,$filename);
 4851:     }
 4852:     return @possiblenames;
 4853: }
 4854: 
 4855: =pod 
 4856: 
 4857: =item scantron_uploads
 4858: 
 4859:    Returns  html drop-down list of scantron files in current course.
 4860: 
 4861:  Arguments:
 4862:    $file2grade - filename to set as selected in the dropdown
 4863: 
 4864: =cut
 4865: 
 4866: sub scantron_uploads {
 4867:     my ($file2grade) = @_;
 4868:     my $result=	'<select name="scantron_selectfile">';
 4869:     $result.="<option></option>";
 4870:     foreach my $filename (sort(&scantron_filenames())) {
 4871: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4872:     }
 4873:     $result.="</select>";
 4874:     return $result;
 4875: }
 4876: 
 4877: =pod 
 4878: 
 4879: =item scantron_scantab
 4880: 
 4881:   Returns html drop down of the scantron formats in the scantronformat.tab
 4882:   file.
 4883: 
 4884: =cut
 4885: 
 4886: sub scantron_scantab {
 4887:     my $result='<select name="scantron_format">'."\n";
 4888:     $result.='<option></option>'."\n";
 4889:     my @lines = &get_scantronformat_file();
 4890:     if (@lines > 0) {
 4891:         foreach my $line (@lines) {
 4892:             next if (($line =~ /^\#/) || ($line eq ''));
 4893: 	    my ($name,$descrip)=split(/:/,$line);
 4894: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4895:         }
 4896:     }
 4897:     $result.='</select>'."\n";
 4898:     return $result;
 4899: }
 4900: 
 4901: =pod
 4902: 
 4903: =item get_scantronformat_file
 4904: 
 4905:   Returns an array containing lines from the scantron format file for
 4906:   the domain of the course.
 4907: 
 4908:   If a url for a custom.tab file is listed in domain's configuration.db, 
 4909:   lines are from this file.
 4910: 
 4911:   Otherwise, if a default.tab has been published in RES space by the 
 4912:   domainconfig user, lines are from this file.
 4913: 
 4914:   Otherwise, fall back to getting lines from the legacy file on the
 4915:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 4916: 
 4917: =cut
 4918: 
 4919: sub get_scantronformat_file {
 4920:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4921:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 4922:     my $gottab = 0;
 4923:     my @lines;
 4924:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4925:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4926:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4927:             if ($formatfile ne '-1') {
 4928:                 @lines = split("\n",$formatfile,-1);
 4929:                 $gottab = 1;
 4930:             }
 4931:         }
 4932:     }
 4933:     if (!$gottab) {
 4934:         my $confname = $cdom.'-domainconfig';
 4935:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4936:         my $formatfile =  &Apache::lonnet::getfile($default);
 4937:         if ($formatfile ne '-1') {
 4938:             @lines = split("\n",$formatfile,-1);
 4939:             $gottab = 1;
 4940:         }
 4941:     }
 4942:     if (!$gottab) {
 4943:         my @domains = &Apache::lonnet::current_machine_domains();
 4944:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4945:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4946:             @lines = <$fh>;
 4947:             close($fh);
 4948:         } else {
 4949:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 4950:             @lines = <$fh>;
 4951:             close($fh);
 4952:         }
 4953:     }
 4954:     return @lines;
 4955: }
 4956: 
 4957: =pod 
 4958: 
 4959: =item scantron_CODElist
 4960: 
 4961:   Returns html drop down of the saved CODE lists from current course,
 4962:   generated from earlier printings.
 4963: 
 4964: =cut
 4965: 
 4966: sub scantron_CODElist {
 4967:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4968:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4969:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4970:     my $namechoice='<option></option>';
 4971:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4972: 	if ($name =~ /^error: 2 /) { next; }
 4973: 	if ($name =~ /^type\0/) { next; }
 4974: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4975:     }
 4976:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4977:     return $namechoice;
 4978: }
 4979: 
 4980: =pod 
 4981: 
 4982: =item scantron_CODEunique
 4983: 
 4984:   Returns the html for "Each CODE to be used once" radio.
 4985: 
 4986: =cut
 4987: 
 4988: sub scantron_CODEunique {
 4989:     my $result='<span class="LC_nobreak">
 4990:                  <label><input type="radio" name="scantron_CODEunique"
 4991:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4992:                 </span>
 4993:                 <span class="LC_nobreak">
 4994:                  <label><input type="radio" name="scantron_CODEunique"
 4995:                         value="no" />'.&mt('No').' </label>
 4996:                 </span>';
 4997:     return $result;
 4998: }
 4999: 
 5000: =pod 
 5001: 
 5002: =item scantron_selectphase
 5003: 
 5004:   Generates the initial screen to start the bubble sheet process.
 5005:   Allows for - starting a grading run.
 5006:              - downloading existing scan data (original, corrected
 5007:                                                 or skipped info)
 5008: 
 5009:              - uploading new scan data
 5010: 
 5011:  Arguments:
 5012:   $r          - The Apache request object
 5013:   $file2grade - name of the file that contain the scanned data to score
 5014: 
 5015: =cut
 5016: 
 5017: sub scantron_selectphase {
 5018:     my ($r,$file2grade) = @_;
 5019:     my ($symb)=&get_symb($r);
 5020:     if (!$symb) {return '';}
 5021:     my $sequence_selector=&getSequenceDropDown($symb);
 5022:     my $default_form_data=&defaultFormData($symb);
 5023:     my $grading_menu_button=&show_grading_menu_form($symb);
 5024:     my $file_selector=&scantron_uploads($file2grade);
 5025:     my $format_selector=&scantron_scantab();
 5026:     my $CODE_selector=&scantron_CODElist();
 5027:     my $CODE_unique=&scantron_CODEunique();
 5028:     my $result;
 5029: 
 5030:     $ssi_error = 0;
 5031: 
 5032:     # Chunk of form to prompt for a file to grade and how:
 5033: 
 5034:     $result.= '
 5035:     <br />
 5036:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5037:     <input type="hidden" name="command" value="scantron_warning" />
 5038:     '.$default_form_data.'
 5039:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5040:        '.&Apache::loncommon::start_data_table_header_row().'
 5041:             <th colspan="2">
 5042:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5043:             </th>
 5044:        '.&Apache::loncommon::end_data_table_header_row().'
 5045:        '.&Apache::loncommon::start_data_table_row().'
 5046:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5047:        '.&Apache::loncommon::end_data_table_row().'
 5048:        '.&Apache::loncommon::start_data_table_row().'
 5049:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5050:        '.&Apache::loncommon::end_data_table_row().'
 5051:        '.&Apache::loncommon::start_data_table_row().'
 5052:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5053:        '.&Apache::loncommon::end_data_table_row().'
 5054:        '.&Apache::loncommon::start_data_table_row().'
 5055:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5056:        '.&Apache::loncommon::end_data_table_row().'
 5057:        '.&Apache::loncommon::start_data_table_row().'
 5058:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5059:        '.&Apache::loncommon::end_data_table_row().'
 5060:        '.&Apache::loncommon::start_data_table_row().'
 5061: 	    <td> '.&mt('Options:').' </td>
 5062:             <td>
 5063: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5064:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5065:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5066: 	    </td>
 5067:        '.&Apache::loncommon::end_data_table_row().'
 5068:        '.&Apache::loncommon::start_data_table_row().'
 5069:             <td colspan="2">
 5070:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5071:             </td>
 5072:        '.&Apache::loncommon::end_data_table_row().'
 5073:     '.&Apache::loncommon::end_data_table().'
 5074:     </form>
 5075: ';
 5076:    
 5077:     $r->print($result);
 5078: 
 5079:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5080:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5081: 
 5082: 	# Chunk of form to prompt for a scantron file upload.
 5083: 
 5084:         $r->print('
 5085:     <br />
 5086:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5087:        '.&Apache::loncommon::start_data_table_header_row().'
 5088:             <th>
 5089:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5090:             </th>
 5091:        '.&Apache::loncommon::end_data_table_header_row().'
 5092:        '.&Apache::loncommon::start_data_table_row().'
 5093:             <td>
 5094: ');
 5095:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5096:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5097:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5098:     $r->print('
 5099:               <script type="text/javascript" language="javascript">
 5100:     function checkUpload(formname) {
 5101: 	if (formname.upfile.value == "") {
 5102: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5103: 	    return false;
 5104: 	}
 5105: 	formname.submit();
 5106:     }
 5107:               </script>
 5108: 
 5109:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5110:                 '.$default_form_data.'
 5111:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5112:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5113:                 <input name="command" value="scantronupload_save" type="hidden" />
 5114:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5115:                 <br />
 5116:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5117:               </form>
 5118: ');
 5119: 
 5120:         $r->print('
 5121:             </td>
 5122:        '.&Apache::loncommon::end_data_table_row().'
 5123:        '.&Apache::loncommon::end_data_table().'
 5124: ');
 5125:     }
 5126: 
 5127:     # Chunk of the form that prompts to view a scoring office file,
 5128:     # corrected file, skipped records in a file.
 5129: 
 5130:     $r->print('
 5131:    <br />
 5132:    <form action="/adm/grades" name="scantron_download">
 5133:      '.$default_form_data.'
 5134:      <input type="hidden" name="command" value="scantron_download" />
 5135:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5136:        '.&Apache::loncommon::start_data_table_header_row().'
 5137:               <th>
 5138:                 &nbsp;'.&mt('Download a scoring office file').'
 5139:               </th>
 5140:        '.&Apache::loncommon::end_data_table_header_row().'
 5141:        '.&Apache::loncommon::start_data_table_row().'
 5142:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5143:                 <br />
 5144:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5145:        '.&Apache::loncommon::end_data_table_row().'
 5146:      '.&Apache::loncommon::end_data_table().'
 5147:    </form>
 5148:    <br />
 5149: ');
 5150: 
 5151:     &Apache::lonpickcode::code_list($r,2);
 5152: 
 5153:     $r->print('<br /><form method="post" name="checkscantron">'.
 5154:              $default_form_data."\n".
 5155:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5156:              &Apache::loncommon::start_data_table_header_row()."\n".
 5157:              '<th colspan="2">
 5158:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5159:              '</th>'."\n".
 5160:               &Apache::loncommon::end_data_table_header_row()."\n".
 5161:               &Apache::loncommon::start_data_table_row()."\n".
 5162:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5163:               '<td> '.$sequence_selector.' </td>'.
 5164:               &Apache::loncommon::end_data_table_row()."\n".
 5165:               &Apache::loncommon::start_data_table_row()."\n".
 5166:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5167:               '<td> '.$file_selector.' </td>'."\n".
 5168:               &Apache::loncommon::end_data_table_row()."\n".
 5169:               &Apache::loncommon::start_data_table_row()."\n".
 5170:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5171:               '<td> '.$format_selector.' </td>'."\n".
 5172:               &Apache::loncommon::end_data_table_row()."\n".
 5173:               &Apache::loncommon::start_data_table_row()."\n".
 5174:               '<td colspan="2">'."\n".
 5175:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5176:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5177:               '</td>'."\n".
 5178:               &Apache::loncommon::end_data_table_row()."\n".
 5179:               &Apache::loncommon::end_data_table()."\n".
 5180:               '</form><br />');
 5181:     $r->print($grading_menu_button);
 5182:     return;
 5183: }
 5184: 
 5185: =pod
 5186: 
 5187: =item get_scantron_config
 5188: 
 5189:    Parse and return the scantron configuration line selected as a
 5190:    hash of configuration file fields.
 5191: 
 5192:  Arguments:
 5193:     which - the name of the configuration to parse from the file.
 5194: 
 5195: 
 5196:  Returns:
 5197:             If the named configuration is not in the file, an empty
 5198:             hash is returned.
 5199:     a hash with the fields
 5200:       name         - internal name for the this configuration setup
 5201:       description  - text to display to operator that describes this config
 5202:       CODElocation - if 0 or the string 'none'
 5203:                           - no CODE exists for this config
 5204:                      if -1 || the string 'letter'
 5205:                           - a CODE exists for this config and is
 5206:                             a string of letters
 5207:                      Unsupported value (but planned for future support)
 5208:                           if a positive integer
 5209:                                - The CODE exists as the first n items from
 5210:                                  the question section of the form
 5211:                           if the string 'number'
 5212:                                - The CODE exists for this config and is
 5213:                                  a string of numbers
 5214:       CODEstart   - (only matter if a CODE exists) column in the line where
 5215:                      the CODE starts
 5216:       CODElength  - length of the CODE
 5217:       IDstart     - column where the student ID number starts
 5218:       IDlength    - length of the student ID info
 5219:       Qstart      - column where the information from the bubbled
 5220:                     'questions' start
 5221:       Qlength     - number of columns comprising a single bubble line from
 5222:                     the sheet. (usually either 1 or 10)
 5223:       Qon         - either a single character representing the character used
 5224:                     to signal a bubble was chosen in the positional setup, or
 5225:                     the string 'letter' if the letter of the chosen bubble is
 5226:                     in the final, or 'number' if a number representing the
 5227:                     chosen bubble is in the file (1->A 0->J)
 5228:       Qoff        - the character used to represent that a bubble was
 5229:                     left blank
 5230:       PaperID     - if the scanning process generates a unique number for each
 5231:                     sheet scanned the column that this ID number starts in
 5232:       PaperIDlength - number of columns that comprise the unique ID number
 5233:                       for the sheet of paper
 5234:       FirstName   - column that the first name starts in
 5235:       FirstNameLength - number of columns that the first name spans
 5236:  
 5237:       LastName    - column that the last name starts in
 5238:       LastNameLength - number of columns that the last name spans
 5239: 
 5240: =cut
 5241: 
 5242: sub get_scantron_config {
 5243:     my ($which) = @_;
 5244:     my @lines = &get_scantronformat_file();
 5245:     my %config;
 5246:     #FIXME probably should move to XML it has already gotten a bit much now
 5247:     foreach my $line (@lines) {
 5248: 	my ($name,$descrip)=split(/:/,$line);
 5249: 	if ($name ne $which ) { next; }
 5250: 	chomp($line);
 5251: 	my @config=split(/:/,$line);
 5252: 	$config{'name'}=$config[0];
 5253: 	$config{'description'}=$config[1];
 5254: 	$config{'CODElocation'}=$config[2];
 5255: 	$config{'CODEstart'}=$config[3];
 5256: 	$config{'CODElength'}=$config[4];
 5257: 	$config{'IDstart'}=$config[5];
 5258: 	$config{'IDlength'}=$config[6];
 5259: 	$config{'Qstart'}=$config[7];
 5260:  	$config{'Qlength'}=$config[8];
 5261: 	$config{'Qoff'}=$config[9];
 5262: 	$config{'Qon'}=$config[10];
 5263: 	$config{'PaperID'}=$config[11];
 5264: 	$config{'PaperIDlength'}=$config[12];
 5265: 	$config{'FirstName'}=$config[13];
 5266: 	$config{'FirstNamelength'}=$config[14];
 5267: 	$config{'LastName'}=$config[15];
 5268: 	$config{'LastNamelength'}=$config[16];
 5269: 	last;
 5270:     }
 5271:     return %config;
 5272: }
 5273: 
 5274: =pod 
 5275: 
 5276: =item username_to_idmap
 5277: 
 5278:     creates a hash keyed by student id with values of the corresponding
 5279:     student username:domain.
 5280: 
 5281:   Arguments:
 5282: 
 5283:     $classlist - reference to the class list hash. This is a hash
 5284:                  keyed by student name:domain  whose elements are references
 5285:                  to arrays containing various chunks of information
 5286:                  about the student. (See loncoursedata for more info).
 5287: 
 5288:   Returns
 5289:     %idmap - the constructed hash
 5290: 
 5291: =cut
 5292: 
 5293: sub username_to_idmap {
 5294:     my ($classlist)= @_;
 5295:     my %idmap;
 5296:     foreach my $student (keys(%$classlist)) {
 5297: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5298: 	    $student;
 5299:     }
 5300:     return %idmap;
 5301: }
 5302: 
 5303: =pod
 5304: 
 5305: =item scantron_fixup_scanline
 5306: 
 5307:    Process a requested correction to a scanline.
 5308: 
 5309:   Arguments:
 5310:     $scantron_config   - hash from &get_scantron_config()
 5311:     $scan_data         - hash of correction information 
 5312:                           (see &scantron_getfile())
 5313:     $line              - existing scanline
 5314:     $whichline         - line number of the passed in scanline
 5315:     $field             - type of change to process 
 5316:                          (either 
 5317:                           'ID'     -> correct the student ID number
 5318:                           'CODE'   -> correct the CODE
 5319:                           'answer' -> fixup the submitted answers)
 5320:     
 5321:    $args               - hash of additional info,
 5322:                           - 'ID' 
 5323:                                'newid' -> studentID to use in replacement
 5324:                                           of existing one
 5325:                           - 'CODE' 
 5326:                                'CODE_ignore_dup' - set to true if duplicates
 5327:                                                    should be ignored.
 5328: 	                       'CODE' - is new code or 'use_unfound'
 5329:                                         if the existing unfound code should
 5330:                                         be used as is
 5331:                           - 'answer'
 5332:                                'response' - new answer or 'none' if blank
 5333:                                'question' - the bubble line to change
 5334:                                'questionnum' - the question identifier,
 5335:                                                may include subquestion. 
 5336: 
 5337:   Returns:
 5338:     $line - the modified scanline
 5339: 
 5340:   Side effects: 
 5341:     $scan_data - may be updated
 5342: 
 5343: =cut
 5344: 
 5345: 
 5346: sub scantron_fixup_scanline {
 5347:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5348:     if ($field eq 'ID') {
 5349: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5350: 	    return ($line,1,'New value too large');
 5351: 	}
 5352: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5353: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5354: 				     $args->{'newid'});
 5355: 	}
 5356: 	substr($line,$$scantron_config{'IDstart'}-1,
 5357: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5358: 	if ($args->{'newid'}=~/^\s*$/) {
 5359: 	    &scan_data($scan_data,"$whichline.user",
 5360: 		       $args->{'username'}.':'.$args->{'domain'});
 5361: 	}
 5362:     } elsif ($field eq 'CODE') {
 5363: 	if ($args->{'CODE_ignore_dup'}) {
 5364: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5365: 	}
 5366: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5367: 	if ($args->{'CODE'} ne 'use_unfound') {
 5368: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5369: 		return ($line,1,'New CODE value too large');
 5370: 	    }
 5371: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5372: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5373: 	    }
 5374: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5375: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5376: 	}
 5377:     } elsif ($field eq 'answer') {
 5378: 	my $length=$scantron_config->{'Qlength'};
 5379: 	my $off=$scantron_config->{'Qoff'};
 5380: 	my $on=$scantron_config->{'Qon'};
 5381: 	my $answer=${off}x$length;
 5382: 	if ($args->{'response'} eq 'none') {
 5383: 	    &scan_data($scan_data,
 5384: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5385: 	} else {
 5386: 	    if ($on eq 'letter') {
 5387: 		my @alphabet=('A'..'Z');
 5388: 		$answer=$alphabet[$args->{'response'}];
 5389: 	    } elsif ($on eq 'number') {
 5390: 		$answer=$args->{'response'}+1;
 5391: 		if ($answer == 10) { $answer = '0'; }
 5392: 	    } else {
 5393: 		substr($answer,$args->{'response'},1)=$on;
 5394: 	    }
 5395: 	    &scan_data($scan_data,
 5396: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5397: 	}
 5398: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5399: 	substr($line,$where-1,$length)=$answer;
 5400:     }
 5401:     return $line;
 5402: }
 5403: 
 5404: =pod
 5405: 
 5406: =item scan_data
 5407: 
 5408:     Edit or look up  an item in the scan_data hash.
 5409: 
 5410:   Arguments:
 5411:     $scan_data  - The hash (see scantron_getfile)
 5412:     $key        - shorthand of the key to edit (actual key is
 5413:                   scantronfilename_key).
 5414:     $data        - New value of the hash entry.
 5415:     $delete      - If true, the entry is removed from the hash.
 5416: 
 5417:   Returns:
 5418:     The new value of the hash table field (undefined if deleted).
 5419: 
 5420: =cut
 5421: 
 5422: 
 5423: sub scan_data {
 5424:     my ($scan_data,$key,$value,$delete)=@_;
 5425:     my $filename=$env{'form.scantron_selectfile'};
 5426:     if (defined($value)) {
 5427: 	$scan_data->{$filename.'_'.$key} = $value;
 5428:     }
 5429:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5430:     return $scan_data->{$filename.'_'.$key};
 5431: }
 5432: 
 5433: # ----- These first few routines are general use routines.----
 5434: 
 5435: # Return the number of occurences of a pattern in a string.
 5436: 
 5437: sub occurence_count {
 5438:     my ($string, $pattern) = @_;
 5439: 
 5440:     my @matches = ($string =~ /$pattern/g);
 5441: 
 5442:     return scalar(@matches);
 5443: }
 5444: 
 5445: 
 5446: # Take a string known to have digits and convert all the
 5447: # digits into letters in the range J,A..I.
 5448: 
 5449: sub digits_to_letters {
 5450:     my ($input) = @_;
 5451: 
 5452:     my @alphabet = ('J', 'A'..'I');
 5453: 
 5454:     my @input    = split(//, $input);
 5455:     my $output ='';
 5456:     for (my $i = 0; $i < scalar(@input); $i++) {
 5457: 	if ($input[$i] =~ /\d/) {
 5458: 	    $output .= $alphabet[$input[$i]];
 5459: 	} else {
 5460: 	    $output .= $input[$i];
 5461: 	}
 5462:     }
 5463:     return $output;
 5464: }
 5465: 
 5466: =pod 
 5467: 
 5468: =item scantron_parse_scanline
 5469: 
 5470:   Decodes a scanline from the selected scantron file
 5471: 
 5472:  Arguments:
 5473:     line             - The text of the scantron file line to process
 5474:     whichline        - Line number
 5475:     scantron_config  - Hash describing the format of the scantron lines.
 5476:     scan_data        - Hash of extra information about the scanline
 5477:                        (see scantron_getfile for more information)
 5478:     just_header      - True if should not process question answers but only
 5479:                        the stuff to the left of the answers.
 5480:  Returns:
 5481:    Hash containing the result of parsing the scanline
 5482: 
 5483:    Keys are all proceeded by the string 'scantron.'
 5484: 
 5485:        CODE    - the CODE in use for this scanline
 5486:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5487:                  by the operator
 5488:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5489:                             CODEs were selected, but the usage has been
 5490:                             forced by the operator
 5491:        ID  - student ID
 5492:        PaperID - if used, the ID number printed on the sheet when the 
 5493:                  paper was scanned
 5494:        FirstName - first name from the sheet
 5495:        LastName  - last name from the sheet
 5496: 
 5497:      if just_header was not true these key may also exist
 5498: 
 5499:        missingerror - a list of bubble ranges that are considered to be answers
 5500:                       to a single question that don't have any bubbles filled in.
 5501:                       Of the form questionnumber:firstbubblenumber:count.
 5502:        doubleerror  - a list of bubble ranges that are considered to be answers
 5503:                       to a single question that have more than one bubble filled in.
 5504:                       Of the form questionnumber::firstbubblenumber:count
 5505:    
 5506:                 In the above, count is the number of bubble responses in the
 5507:                 input line needed to represent the possible answers to the question.
 5508:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5509:                 per line would have count = 2.
 5510: 
 5511:        maxquest     - the number of the last bubble line that was parsed
 5512: 
 5513:        (<number> starts at 1)
 5514:        <number>.answer - zero or more letters representing the selected
 5515:                          letters from the scanline for the bubble line 
 5516:                          <number>.
 5517:                          if blank there was either no bubble or there where
 5518:                          multiple bubbles, (consult the keys missingerror and
 5519:                          doubleerror if this is an error condition)
 5520: 
 5521: =cut
 5522: 
 5523: sub scantron_parse_scanline {
 5524:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5525: 
 5526:     my %record;
 5527:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
 5528:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
 5529:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5530:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5531: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5532: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5533: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5534: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5535: 	    $record{'scantron.CODE'}=substr($data,
 5536: 					    $$scantron_config{'CODEstart'}-1,
 5537: 					    $$scantron_config{'CODElength'});
 5538: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5539: 		$record{'scantron.useCODE'}=1;
 5540: 	    }
 5541: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5542: 		$record{'scantron.CODE_ignore_dup'}=1;
 5543: 	    }
 5544: 	} else {
 5545: 	    #FIXME interpret first N questions
 5546: 	}
 5547:     }
 5548:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5549: 				  $$scantron_config{'IDlength'});
 5550:     $record{'scantron.PaperID'}=
 5551: 	substr($data,$$scantron_config{'PaperID'}-1,
 5552: 	       $$scantron_config{'PaperIDlength'});
 5553:     $record{'scantron.FirstName'}=
 5554: 	substr($data,$$scantron_config{'FirstName'}-1,
 5555: 	       $$scantron_config{'FirstNamelength'});
 5556:     $record{'scantron.LastName'}=
 5557: 	substr($data,$$scantron_config{'LastName'}-1,
 5558: 	       $$scantron_config{'LastNamelength'});
 5559:     if ($just_header) { return \%record; }
 5560: 
 5561:     my @alphabet=('A'..'Z');
 5562:     my $questnum=0;
 5563:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5564: 
 5565:     chomp($questions);		# Get rid of any trailing \n.
 5566:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5567:     while (length($questions)) {
 5568: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5570:                              || 1;
 5571:         $questnum++;
 5572:         my $quest_id = $questnum;
 5573:         my $currentquest = substr($questions,0,$answer_length);
 5574:         $questions       = substr($questions,$answer_length);
 5575:         if (length($currentquest) < $answer_length) { next; }
 5576: 
 5577:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5578:             my $subquestnum = 1;
 5579:             my $subquestions = $currentquest;
 5580:             my @subanswers_needed = 
 5581:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5582:             foreach my $subans (@subanswers_needed) {
 5583:                 my $subans_length =
 5584:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5585:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5586:                 $subquestions   = substr($subquestions,$subans_length);
 5587:                 $quest_id = "$questnum.$subquestnum";
 5588:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5589:                     ($$scantron_config{'Qon'} eq 'number')) {
 5590:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5591:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5592:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5593:                 } else {
 5594:                     $ansnum = &scantron_validator_positional($ansnum,
 5595:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5596:                 }
 5597:                 $subquestnum ++;
 5598:             }
 5599:         } else {
 5600:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5601:                 ($$scantron_config{'Qon'} eq 'number')) {
 5602:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5603:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5604:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5605:             } else {
 5606:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5607:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5608:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5609:             }
 5610:         }
 5611:     }
 5612:     $record{'scantron.maxquest'}=$questnum;
 5613:     return \%record;
 5614: }
 5615: 
 5616: sub scantron_validator_lettnum {
 5617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5618:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5619: 
 5620:     # Qon 'letter' implies for each slot in currquest we have:
 5621:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5622:     #    about anything else (esp. a value of Qoff) for missing
 5623:     #    bubbles.
 5624:     #
 5625:     # Qon 'number' implies each slot gives a digit that indexes the
 5626:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5627:     #    and * or ? for double bubbles on a single line.
 5628:     #
 5629: 
 5630:     my $matchon;
 5631:     if ($$scantron_config{'Qon'} eq 'letter') {
 5632:         $matchon = '[A-Z]';
 5633:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5634:         $matchon = '\d';
 5635:     }
 5636:     my $occurrences = 0;
 5637:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5638:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5639:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5640:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5641:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5642:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5643:         my @singlelines = split('',$currquest);
 5644:         foreach my $entry (@singlelines) {
 5645:             $occurrences = &occurence_count($entry,$matchon);
 5646:             if ($occurrences > 1) {
 5647:                 last;
 5648:             }
 5649:         } 
 5650:     } else {
 5651:         $occurrences = &occurence_count($currquest,$matchon); 
 5652:     }
 5653:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5654:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5655:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5656:             my $bubble = substr($currquest,$ans,1);
 5657:             if ($bubble =~ /$matchon/ ) {
 5658:                 if ($$scantron_config{'Qon'} eq 'number') {
 5659:                     if ($bubble == 0) {
 5660:                         $bubble = 10; 
 5661:                     }
 5662:                     $record->{"scantron.$ansnum.answer"} = 
 5663:                         $alphabet->[$bubble-1];
 5664:                 } else {
 5665:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5666:                 }
 5667:             } else {
 5668:                 $record->{"scantron.$ansnum.answer"}='';
 5669:             }
 5670:             $ansnum++;
 5671:         }
 5672:     } elsif (!defined($currquest)
 5673:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5674:             || (&occurence_count($currquest,$matchon) == 0)) {
 5675:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5676:             $record->{"scantron.$ansnum.answer"}='';
 5677:             $ansnum++;
 5678:         }
 5679:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5680:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5681:         }
 5682:     } else {
 5683:         if ($$scantron_config{'Qon'} eq 'number') {
 5684:             $currquest = &digits_to_letters($currquest);            
 5685:         }
 5686:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5687:             my $bubble = substr($currquest,$ans,1);
 5688:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5689:             $ansnum++;
 5690:         }
 5691:     }
 5692:     return $ansnum;
 5693: }
 5694: 
 5695: sub scantron_validator_positional {
 5696:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5697:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5698: 
 5699:     # Otherwise there's a positional notation;
 5700:     # each bubble line requires Qlength items, and there are filled in
 5701:     # bubbles for each case where there 'Qon' characters.
 5702:     #
 5703: 
 5704:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5705: 
 5706:     # If the split only gives us one element.. the full length of the
 5707:     # answer string, no bubbles are filled in:
 5708: 
 5709:     if ($answers_needed eq '') {
 5710:         return;
 5711:     }
 5712: 
 5713:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5714:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5715:             $record->{"scantron.$ansnum.answer"}='';
 5716:             $ansnum++;
 5717:         }
 5718:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5719:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5720:         }
 5721:     } elsif (scalar(@array) == 2) {
 5722:         my $location = length($array[0]);
 5723:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5724:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5725:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5726:             if ($ans eq $line_num) {
 5727:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5728:             } else {
 5729:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5730:             }
 5731:             $ansnum++;
 5732:          }
 5733:     } else {
 5734:         #  If there's more than one instance of a bubble character
 5735:         #  That's a double bubble; with positional notation we can
 5736:         #  record all the bubbles filled in as well as the
 5737:         #  fact this response consists of multiple bubbles.
 5738:         #
 5739:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5740:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5741:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5742:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5743:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5744:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5745:             my $doubleerror = 0;
 5746:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5747:                    (!$doubleerror)) {
 5748:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5749:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5750:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5751:                if (length(@currarray) > 2) {
 5752:                    $doubleerror = 1;
 5753:                } 
 5754:             }
 5755:             if ($doubleerror) {
 5756:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5757:             }
 5758:         } else {
 5759:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5760:         }
 5761:         my $item = $ansnum;
 5762:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5763:             $record->{"scantron.$item.answer"} = '';
 5764:             $item ++;
 5765:         }
 5766: 
 5767:         my @ans=@array;
 5768:         my $i=0;
 5769:         my $increment = 0;
 5770:         while ($#ans) {
 5771:             $i+=length($ans[0]) + $increment;
 5772:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5773:             my $bubble = $i%$$scantron_config{'Qlength'};
 5774:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5775:             shift(@ans);
 5776:             $increment = 1;
 5777:         }
 5778:         $ansnum += $answers_needed;
 5779:     }
 5780:     return $ansnum;
 5781: }
 5782: 
 5783: =pod
 5784: 
 5785: =item scantron_add_delay
 5786: 
 5787:    Adds an error message that occurred during the grading phase to a
 5788:    queue of messages to be shown after grading pass is complete
 5789: 
 5790:  Arguments:
 5791:    $delayqueue  - arrary ref of hash ref of error messages
 5792:    $scanline    - the scanline that caused the error
 5793:    $errormesage - the error message
 5794:    $errorcode   - a numeric code for the error
 5795: 
 5796:  Side Effects:
 5797:    updates the $delayqueue to have a new hash ref of the error
 5798: 
 5799: =cut
 5800: 
 5801: sub scantron_add_delay {
 5802:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5803:     push(@$delayqueue,
 5804: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5805: 	  'ecode' => $errorcode }
 5806: 	 );
 5807: }
 5808: 
 5809: =pod
 5810: 
 5811: =item scantron_find_student
 5812: 
 5813:    Finds the username for the current scanline
 5814: 
 5815:   Arguments:
 5816:    $scantron_record - hash result from scantron_parse_scanline
 5817:    $scan_data       - hash of correction information 
 5818:                       (see &scantron_getfile() form more information)
 5819:    $idmap           - hash from &username_to_idmap()
 5820:    $line            - number of current scanline
 5821:  
 5822:   Returns:
 5823:    Either 'username:domain' or undef if unknown
 5824: 
 5825: =cut
 5826: 
 5827: sub scantron_find_student {
 5828:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5829:     my $scanID=$$scantron_record{'scantron.ID'};
 5830:     if ($scanID =~ /^\s*$/) {
 5831:  	return &scan_data($scan_data,"$line.user");
 5832:     }
 5833:     foreach my $id (keys(%$idmap)) {
 5834:  	if (lc($id) eq lc($scanID)) {
 5835:  	    return $$idmap{$id};
 5836:  	}
 5837:     }
 5838:     return undef;
 5839: }
 5840: 
 5841: =pod
 5842: 
 5843: =item scantron_filter
 5844: 
 5845:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5846:    hidden resources was selected
 5847: 
 5848: =cut
 5849: 
 5850: sub scantron_filter {
 5851:     my ($curres)=@_;
 5852: 
 5853:     if (ref($curres) && $curres->is_problem()) {
 5854: 	# if the user has asked to not have either hidden
 5855: 	# or 'randomout' controlled resources to be graded
 5856: 	# don't include them
 5857: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5858: 	    && $curres->randomout) {
 5859: 	    return 0;
 5860: 	}
 5861: 	return 1;
 5862:     }
 5863:     return 0;
 5864: }
 5865: 
 5866: =pod
 5867: 
 5868: =item scantron_process_corrections
 5869: 
 5870:    Gets correction information out of submitted form data and corrects
 5871:    the scanline
 5872: 
 5873: =cut
 5874: 
 5875: sub scantron_process_corrections {
 5876:     my ($r) = @_;
 5877:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5878:     my ($scanlines,$scan_data)=&scantron_getfile();
 5879:     my $classlist=&Apache::loncoursedata::get_classlist();
 5880:     my $which=$env{'form.scantron_line'};
 5881:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5882:     my ($skip,$err,$errmsg);
 5883:     if ($env{'form.scantron_skip_record'}) {
 5884: 	$skip=1;
 5885:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5886: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5887: 	    $env{'form.scantron_domain'};
 5888: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5889: 	($line,$err,$errmsg)=
 5890: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5891: 				     'ID',{'newid'=>$newid,
 5892: 				    'username'=>$env{'form.scantron_username'},
 5893: 				    'domain'=>$env{'form.scantron_domain'}});
 5894:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5895: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5896: 	my $newCODE;
 5897: 	my %args;
 5898: 	if      ($resolution eq 'use_unfound') {
 5899: 	    $newCODE='use_unfound';
 5900: 	} elsif ($resolution eq 'use_found') {
 5901: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5902: 	} elsif ($resolution eq 'use_typed') {
 5903: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5904: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5905: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5906: 	}
 5907: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5908: 	    $args{'CODE_ignore_dup'}=1;
 5909: 	}
 5910: 	$args{'CODE'}=$newCODE;
 5911: 	($line,$err,$errmsg)=
 5912: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5913: 				     'CODE',\%args);
 5914:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5915: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5916: 	    ($line,$err,$errmsg)=
 5917: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5918: 					 $which,'answer',
 5919: 					 { 'question'=>$question,
 5920: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 5921:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 5922: 	    if ($err) { last; }
 5923: 	}
 5924:     }
 5925:     if ($err) {
 5926: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5927:     } else {
 5928: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5929: 	&scantron_putfile($scanlines,$scan_data);
 5930:     }
 5931: }
 5932: 
 5933: =pod
 5934: 
 5935: =item reset_skipping_status
 5936: 
 5937:    Forgets the current set of remember skipped scanlines (and thus
 5938:    reverts back to considering all lines in the
 5939:    scantron_skipped_<filename> file)
 5940: 
 5941: =cut
 5942: 
 5943: sub reset_skipping_status {
 5944:     my ($scanlines,$scan_data)=&scantron_getfile();
 5945:     &scan_data($scan_data,'remember_skipping',undef,1);
 5946:     &scantron_putfile(undef,$scan_data);
 5947: }
 5948: 
 5949: =pod
 5950: 
 5951: =item start_skipping
 5952: 
 5953:    Marks a scanline to be skipped. 
 5954: 
 5955: =cut
 5956: 
 5957: sub start_skipping {
 5958:     my ($scan_data,$i)=@_;
 5959:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5960:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5961: 	$remembered{$i}=2;
 5962:     } else {
 5963: 	$remembered{$i}=1;
 5964:     }
 5965:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5966: }
 5967: 
 5968: =pod
 5969: 
 5970: =item should_be_skipped
 5971: 
 5972:    Checks whether a scanline should be skipped.
 5973: 
 5974: =cut
 5975: 
 5976: sub should_be_skipped {
 5977:     my ($scanlines,$scan_data,$i)=@_;
 5978:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5979: 	# not redoing old skips
 5980: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5981: 	return 0;
 5982:     }
 5983:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5984: 
 5985:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5986: 	return 0;
 5987:     }
 5988:     return 1;
 5989: }
 5990: 
 5991: =pod
 5992: 
 5993: =item remember_current_skipped
 5994: 
 5995:    Discovers what scanlines are in the scantron_skipped_<filename>
 5996:    file and remembers them into scan_data for later use.
 5997: 
 5998: =cut
 5999: 
 6000: sub remember_current_skipped {
 6001:     my ($scanlines,$scan_data)=&scantron_getfile();
 6002:     my %to_remember;
 6003:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6004: 	if ($scanlines->{'skipped'}[$i]) {
 6005: 	    $to_remember{$i}=1;
 6006: 	}
 6007:     }
 6008: 
 6009:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6010:     &scantron_putfile(undef,$scan_data);
 6011: }
 6012: 
 6013: =pod
 6014: 
 6015: =item check_for_error
 6016: 
 6017:     Checks if there was an error when attempting to remove a specific
 6018:     scantron_.. bubble sheet data file. Prints out an error if
 6019:     something went wrong.
 6020: 
 6021: =cut
 6022: 
 6023: sub check_for_error {
 6024:     my ($r,$result)=@_;
 6025:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6026: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6027:     }
 6028: }
 6029: 
 6030: =pod
 6031: 
 6032: =item scantron_warning_screen
 6033: 
 6034:    Interstitial screen to make sure the operator has selected the
 6035:    correct options before we start the validation phase.
 6036: 
 6037: =cut
 6038: 
 6039: sub scantron_warning_screen {
 6040:     my ($button_text)=@_;
 6041:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6043:     my $CODElist;
 6044:     if ($scantron_config{'CODElocation'} &&
 6045: 	$scantron_config{'CODEstart'} &&
 6046: 	$scantron_config{'CODElength'}) {
 6047: 	$CODElist=$env{'form.scantron_CODElist'};
 6048: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6049: 	$CODElist=
 6050: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6051: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6052:     }
 6053:     return ('
 6054: <p>
 6055: <span class="LC_warning">
 6056: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6057: </p>
 6058: <table>
 6059: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6060: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6061: '.$CODElist.'
 6062: </table>
 6063: <br />
 6064: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6065: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6066: 
 6067: <br />
 6068: ');
 6069: }
 6070: 
 6071: =pod
 6072: 
 6073: =item scantron_do_warning
 6074: 
 6075:    Check if the operator has picked something for all required
 6076:    fields. Error out if something is missing.
 6077: 
 6078: =cut
 6079: 
 6080: sub scantron_do_warning {
 6081:     my ($r)=@_;
 6082:     my ($symb)=&get_symb($r);
 6083:     if (!$symb) {return '';}
 6084:     my $default_form_data=&defaultFormData($symb);
 6085:     $r->print(&scantron_form_start().$default_form_data);
 6086:     if ( $env{'form.selectpage'} eq '' ||
 6087: 	 $env{'form.scantron_selectfile'} eq '' ||
 6088: 	 $env{'form.scantron_format'} eq '' ) {
 6089: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6090: 	if ( $env{'form.selectpage'} eq '') {
 6091: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6092: 	} 
 6093: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6094: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6095: 	} 
 6096: 	if ( $env{'form.scantron_format'} eq '') {
 6097: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6098: 	} 
 6099:     } else {
 6100: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6101: 	$r->print('
 6102: '.$warning.'
 6103: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6104: <input type="hidden" name="command" value="scantron_validate" />
 6105: ');
 6106:     }
 6107:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6108:     return '';
 6109: }
 6110: 
 6111: =pod
 6112: 
 6113: =item scantron_form_start
 6114: 
 6115:     html hidden input for remembering all selected grading options
 6116: 
 6117: =cut
 6118: 
 6119: sub scantron_form_start {
 6120:     my ($max_bubble)=@_;
 6121:     my $result= <<SCANTRONFORM;
 6122: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6123:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6124:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6125:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6126:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6127:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6128:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6129:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6130:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6131:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6132: SCANTRONFORM
 6133: 
 6134:   my $line = 0;
 6135:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6136:        my $chunk =
 6137: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6138:        $chunk .=
 6139: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6140:        $chunk .= 
 6141:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6142:        $chunk .=
 6143:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6144:        $result .= $chunk;
 6145:        $line++;
 6146:    }
 6147:     return $result;
 6148: }
 6149: 
 6150: =pod
 6151: 
 6152: =item scantron_validate_file
 6153: 
 6154:     Dispatch routine for doing validation of a bubble sheet data file.
 6155: 
 6156:     Also processes any necessary information resets that need to
 6157:     occur before validation begins (ignore previous corrections,
 6158:     restarting the skipped records processing)
 6159: 
 6160: =cut
 6161: 
 6162: sub scantron_validate_file {
 6163:     my ($r) = @_;
 6164:     my ($symb)=&get_symb($r);
 6165:     if (!$symb) {return '';}
 6166:     my $default_form_data=&defaultFormData($symb);
 6167:     
 6168:     # do the detection of only doing skipped records first befroe we delete
 6169:     # them when doing the corrections reset
 6170:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6171: 	&reset_skipping_status();
 6172:     }
 6173:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6174: 	&remember_current_skipped();
 6175: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6176:     }
 6177: 
 6178:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6179: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6180: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6181: 	&check_for_error($r,&scantron_remove_scan_data());
 6182: 	$env{'form.scantron_options_ignore'}='done';
 6183:     }
 6184: 
 6185:     if ($env{'form.scantron_corrections'}) {
 6186: 	&scantron_process_corrections($r);
 6187:     }
 6188:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6189:     #get the student pick code ready
 6190:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6191:     my $max_bubble=&scantron_get_maxbubble();
 6192:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6193:     $r->print($result);
 6194:     
 6195:     my @validate_phases=( 'sequence',
 6196: 			  'ID',
 6197: 			  'CODE',
 6198: 			  'doublebubble',
 6199: 			  'missingbubbles');
 6200:     if (!$env{'form.validatepass'}) {
 6201: 	$env{'form.validatepass'} = 0;
 6202:     }
 6203:     my $currentphase=$env{'form.validatepass'};
 6204: 
 6205: 
 6206:     my $stop=0;
 6207:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6208: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6209: 	$r->rflush();
 6210: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6211: 	{
 6212: 	    no strict 'refs';
 6213: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6214: 	}
 6215:     }
 6216:     if (!$stop) {
 6217:         my $warning=&scantron_warning_screen('Start Grading');
 6218:         $r->print(&mt('Validation process complete.').'<br />'.
 6219:                   $warning.
 6220:                   &mt('Perform verification for each student after storage of submissions?').
 6221:                   '&nbsp;<span class="LC_nobreak"><label>'.
 6222:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
 6223:                   ('&nbsp;'x3).'<label>'.
 6224:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
 6225:                   '</label></span><br />'.
 6226:                   &mt('Grading will take longer if you use verification.').'<br />'.                  &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
 6227:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
 6228:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
 6229:     } else {
 6230:         $r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6231:         $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6232:     }
 6233:     if ($stop) {
 6234: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6235: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr;" />');
 6236: 	    $r->print(' '.&mt('this error').' <br />');
 6237: 
 6238: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6239: 	} else {
 6240:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6241: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
 6242:             } else {
 6243:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
 6244:             }
 6245: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6246: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6247: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6248: 	}
 6249:     }
 6250:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6251:     return '';
 6252: }
 6253: 
 6254: 
 6255: =pod
 6256: 
 6257: =item scantron_remove_file
 6258: 
 6259:    Removes the requested bubble sheet data file, makes sure that
 6260:    scantron_original_<filename> is never removed
 6261: 
 6262: 
 6263: =cut
 6264: 
 6265: sub scantron_remove_file {
 6266:     my ($which)=@_;
 6267:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6268:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6269:     my $file='scantron_';
 6270:     if ($which eq 'corrected' || $which eq 'skipped') {
 6271: 	$file.=$which.'_';
 6272:     } else {
 6273: 	return 'refused';
 6274:     }
 6275:     $file.=$env{'form.scantron_selectfile'};
 6276:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6277: }
 6278: 
 6279: 
 6280: =pod
 6281: 
 6282: =item scantron_remove_scan_data
 6283: 
 6284:    Removes all scan_data correction for the requested bubble sheet
 6285:    data file.  (In the case that both the are doing skipped records we need
 6286:    to remember the old skipped lines for the time being so that element
 6287:    persists for a while.)
 6288: 
 6289: =cut
 6290: 
 6291: sub scantron_remove_scan_data {
 6292:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6293:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6294:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6295:     my @todelete;
 6296:     my $filename=$env{'form.scantron_selectfile'};
 6297:     foreach my $key (@keys) {
 6298: 	if ($key=~/^\Q$filename\E_/) {
 6299: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6300: 		$key=~/remember_skipping/) {
 6301: 		next;
 6302: 	    }
 6303: 	    push(@todelete,$key);
 6304: 	}
 6305:     }
 6306:     my $result;
 6307:     if (@todelete) {
 6308: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6309: 				       \@todelete,$cdom,$cname);
 6310:     } else {
 6311: 	$result = 'ok';
 6312:     }
 6313:     return $result;
 6314: }
 6315: 
 6316: 
 6317: =pod
 6318: 
 6319: =item scantron_getfile
 6320: 
 6321:     Fetches the requested bubble sheet data file (all 3 versions), and
 6322:     the scan_data hash
 6323:   
 6324:   Arguments:
 6325:     None
 6326: 
 6327:   Returns:
 6328:     2 hash references
 6329: 
 6330:      - first one has 
 6331:          orig      -
 6332:          corrected -
 6333:          skipped   -  each of which points to an array ref of the specified
 6334:                       file broken up into individual lines
 6335:          count     - number of scanlines
 6336:  
 6337:      - second is the scan_data hash possible keys are
 6338:        ($number refers to scanline numbered $number and thus the key affects
 6339:         only that scanline
 6340:         $bubline refers to the specific bubble line element and the aspects
 6341:         refers to that specific bubble line element)
 6342: 
 6343:        $number.user - username:domain to use
 6344:        $number.CODE_ignore_dup 
 6345:                     - ignore the duplicate CODE error 
 6346:        $number.useCODE
 6347:                     - use the CODE in the scanline as is
 6348:        $number.no_bubble.$bubline
 6349:                     - it is valid that there is no bubbled in bubble
 6350:                       at $number $bubline
 6351:        remember_skipping
 6352:                     - a frozen hash containing keys of $number and values
 6353:                       of either 
 6354:                         1 - we are on a 'do skipped records pass' and plan
 6355:                             on processing this line
 6356:                         2 - we are on a 'do skipped records pass' and this
 6357:                             scanline has been marked to skip yet again
 6358: 
 6359: =cut
 6360: 
 6361: sub scantron_getfile {
 6362:     #FIXME really would prefer a scantron directory
 6363:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6365:     my $lines;
 6366:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6367: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6368:     my %scanlines;
 6369:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6370:     my $temp=$scanlines{'orig'};
 6371:     $scanlines{'count'}=$#$temp;
 6372: 
 6373:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6374: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6375:     if ($lines eq '-1') {
 6376: 	$scanlines{'corrected'}=[];
 6377:     } else {
 6378: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6379:     }
 6380:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6381: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6382:     if ($lines eq '-1') {
 6383: 	$scanlines{'skipped'}=[];
 6384:     } else {
 6385: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6386:     }
 6387:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6388:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6389:     my %scan_data = @tmp;
 6390:     return (\%scanlines,\%scan_data);
 6391: }
 6392: 
 6393: =pod
 6394: 
 6395: =item lonnet_putfile
 6396: 
 6397:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6398: 
 6399:  Arguments:
 6400:    $contents - data to store
 6401:    $filename - filename to store $contents into
 6402: 
 6403:  Returns:
 6404:    result value from &Apache::lonnet::finishuserfileupload
 6405: 
 6406: =cut
 6407: 
 6408: sub lonnet_putfile {
 6409:     my ($contents,$filename)=@_;
 6410:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6411:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6412:     $env{'form.sillywaytopassafilearound'}=$contents;
 6413:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6414: 
 6415: }
 6416: 
 6417: =pod
 6418: 
 6419: =item scantron_putfile
 6420: 
 6421:     Stores the current version of the bubble sheet data files, and the
 6422:     scan_data hash. (Does not modify the original version only the
 6423:     corrected and skipped versions.
 6424: 
 6425:  Arguments:
 6426:     $scanlines - hash ref that looks like the first return value from
 6427:                  &scantron_getfile()
 6428:     $scan_data - hash ref that looks like the second return value from
 6429:                  &scantron_getfile()
 6430: 
 6431: =cut
 6432: 
 6433: sub scantron_putfile {
 6434:     my ($scanlines,$scan_data) = @_;
 6435:     #FIXME really would prefer a scantron directory
 6436:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6438:     if ($scanlines) {
 6439: 	my $prefix='scantron_';
 6440: # no need to update orig, shouldn't change
 6441: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6442: #		    $env{'form.scantron_selectfile'});
 6443: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6444: 			$prefix.'corrected_'.
 6445: 			$env{'form.scantron_selectfile'});
 6446: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6447: 			$prefix.'skipped_'.
 6448: 			$env{'form.scantron_selectfile'});
 6449:     }
 6450:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6451: }
 6452: 
 6453: =pod
 6454: 
 6455: =item scantron_get_line
 6456: 
 6457:    Returns the correct version of the scanline
 6458: 
 6459:  Arguments:
 6460:     $scanlines - hash ref that looks like the first return value from
 6461:                  &scantron_getfile()
 6462:     $scan_data - hash ref that looks like the second return value from
 6463:                  &scantron_getfile()
 6464:     $i         - number of the requested line (starts at 0)
 6465: 
 6466:  Returns:
 6467:    A scanline, (either the original or the corrected one if it
 6468:    exists), or undef if the requested scanline should be
 6469:    skipped. (Either because it's an skipped scanline, or it's an
 6470:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6471:    pass.
 6472: 
 6473: =cut
 6474: 
 6475: sub scantron_get_line {
 6476:     my ($scanlines,$scan_data,$i)=@_;
 6477:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6478:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6479:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6480:     return $scanlines->{'orig'}[$i]; 
 6481: }
 6482: 
 6483: =pod
 6484: 
 6485: =item scantron_todo_count
 6486: 
 6487:     Counts the number of scanlines that need processing.
 6488: 
 6489:  Arguments:
 6490:     $scanlines - hash ref that looks like the first return value from
 6491:                  &scantron_getfile()
 6492:     $scan_data - hash ref that looks like the second return value from
 6493:                  &scantron_getfile()
 6494: 
 6495:  Returns:
 6496:     $count - number of scanlines to process
 6497: 
 6498: =cut
 6499: 
 6500: sub get_todo_count {
 6501:     my ($scanlines,$scan_data)=@_;
 6502:     my $count=0;
 6503:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6504: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6505: 	if ($line=~/^[\s\cz]*$/) { next; }
 6506: 	$count++;
 6507:     }
 6508:     return $count;
 6509: }
 6510: 
 6511: =pod
 6512: 
 6513: =item scantron_put_line
 6514: 
 6515:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6516:     data file.
 6517: 
 6518:  Arguments:
 6519:     $scanlines - hash ref that looks like the first return value from
 6520:                  &scantron_getfile()
 6521:     $scan_data - hash ref that looks like the second return value from
 6522:                  &scantron_getfile()
 6523:     $i         - line number to update
 6524:     $newline   - contents of the updated scanline
 6525:     $skip      - if true make the line for skipping and update the
 6526:                  'skipped' file
 6527: 
 6528: =cut
 6529: 
 6530: sub scantron_put_line {
 6531:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6532:     if ($skip) {
 6533: 	$scanlines->{'skipped'}[$i]=$newline;
 6534: 	&start_skipping($scan_data,$i);
 6535: 	return;
 6536:     }
 6537:     $scanlines->{'corrected'}[$i]=$newline;
 6538: }
 6539: 
 6540: =pod
 6541: 
 6542: =item scantron_clear_skip
 6543: 
 6544:    Remove a line from the 'skipped' file
 6545: 
 6546:  Arguments:
 6547:     $scanlines - hash ref that looks like the first return value from
 6548:                  &scantron_getfile()
 6549:     $scan_data - hash ref that looks like the second return value from
 6550:                  &scantron_getfile()
 6551:     $i         - line number to update
 6552: 
 6553: =cut
 6554: 
 6555: sub scantron_clear_skip {
 6556:     my ($scanlines,$scan_data,$i)=@_;
 6557:     if (exists($scanlines->{'skipped'}[$i])) {
 6558: 	undef($scanlines->{'skipped'}[$i]);
 6559: 	return 1;
 6560:     }
 6561:     return 0;
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item scantron_filter_not_exam
 6567: 
 6568:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6569:    filter out resources that are not marked as 'exam' mode
 6570: 
 6571: =cut
 6572: 
 6573: sub scantron_filter_not_exam {
 6574:     my ($curres)=@_;
 6575:     
 6576:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6577: 	# if the user has asked to not have either hidden
 6578: 	# or 'randomout' controlled resources to be graded
 6579: 	# don't include them
 6580: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6581: 	    && $curres->randomout) {
 6582: 	    return 0;
 6583: 	}
 6584: 	return 1;
 6585:     }
 6586:     return 0;
 6587: }
 6588: 
 6589: =pod
 6590: 
 6591: =item scantron_validate_sequence
 6592: 
 6593:     Validates the selected sequence, checking for resource that are
 6594:     not set to exam mode.
 6595: 
 6596: =cut
 6597: 
 6598: sub scantron_validate_sequence {
 6599:     my ($r,$currentphase) = @_;
 6600: 
 6601:     my $navmap=Apache::lonnavmaps::navmap->new();
 6602:     my (undef,undef,$sequence)=
 6603: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6604: 
 6605:     my $map=$navmap->getResourceByUrl($sequence);
 6606: 
 6607:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6608:                                     value="ignore" />');
 6609:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6610: 	my @resources=
 6611: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6612: 	if (@resources) {
 6613: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6614: 	    return (1,$currentphase);
 6615: 	}
 6616:     }
 6617: 
 6618:     return (0,$currentphase+1);
 6619: }
 6620: 
 6621: =pod
 6622: 
 6623: =item scantron_validate_ID
 6624: 
 6625:    Validates all scanlines in the selected file to not have any
 6626:    invalid or underspecified student IDs
 6627: 
 6628: =cut
 6629: 
 6630: sub scantron_validate_ID {
 6631:     my ($r,$currentphase) = @_;
 6632:     
 6633:     #get student info
 6634:     my $classlist=&Apache::loncoursedata::get_classlist();
 6635:     my %idmap=&username_to_idmap($classlist);
 6636: 
 6637:     #get scantron line setup
 6638:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6639:     my ($scanlines,$scan_data)=&scantron_getfile();
 6640:     
 6641:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6642: 
 6643:     my %found=('ids'=>{},'usernames'=>{});
 6644:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6645: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6646: 	if ($line=~/^[\s\cz]*$/) { next; }
 6647: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6648: 						 $scan_data);
 6649: 	my $id=$$scan_record{'scantron.ID'};
 6650: 	my $found;
 6651: 	foreach my $checkid (keys(%idmap)) {
 6652: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6653: 	}
 6654: 	if ($found) {
 6655: 	    my $username=$idmap{$found};
 6656: 	    if ($found{'ids'}{$found}) {
 6657: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6658: 					 $line,'duplicateID',$found);
 6659: 		return(1,$currentphase);
 6660: 	    } elsif ($found{'usernames'}{$username}) {
 6661: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6662: 					 $line,'duplicateID',$username);
 6663: 		return(1,$currentphase);
 6664: 	    }
 6665: 	    #FIXME store away line we previously saw the ID on to use above
 6666: 	    $found{'ids'}{$found}++;
 6667: 	    $found{'usernames'}{$username}++;
 6668: 	} else {
 6669: 	    if ($id =~ /^\s*$/) {
 6670: 		my $username=&scan_data($scan_data,"$i.user");
 6671: 		if (defined($username) && $found{'usernames'}{$username}) {
 6672: 		    &scantron_get_correction($r,$i,$scan_record,
 6673: 					     \%scantron_config,
 6674: 					     $line,'duplicateID',$username);
 6675: 		    return(1,$currentphase);
 6676: 		} elsif (!defined($username)) {
 6677: 		    &scantron_get_correction($r,$i,$scan_record,
 6678: 					     \%scantron_config,
 6679: 					     $line,'incorrectID');
 6680: 		    return(1,$currentphase);
 6681: 		}
 6682: 		$found{'usernames'}{$username}++;
 6683: 	    } else {
 6684: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6685: 					 $line,'incorrectID');
 6686: 		return(1,$currentphase);
 6687: 	    }
 6688: 	}
 6689:     }
 6690: 
 6691:     return (0,$currentphase+1);
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_get_correction
 6697: 
 6698:    Builds the interface screen to interact with the operator to fix a
 6699:    specific error condition in a specific scanline
 6700: 
 6701:  Arguments:
 6702:     $r           - Apache request object
 6703:     $i           - number of the current scanline
 6704:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6705:     $scan_config - hash ref as returned from &get_scantron_config()
 6706:     $line        - full contents of the current scanline
 6707:     $error       - error condition, valid values are
 6708:                    'incorrectCODE', 'duplicateCODE',
 6709:                    'doublebubble', 'missingbubble',
 6710:                    'duplicateID', 'incorrectID'
 6711:     $arg         - extra information needed
 6712:        For errors:
 6713:          - duplicateID   - paper number that this studentID was seen before on
 6714:          - duplicateCODE - array ref of the paper numbers this CODE was
 6715:                            seen on before
 6716:          - incorrectCODE - current incorrect CODE 
 6717:          - doublebubble  - array ref of the bubble lines that have double
 6718:                            bubble errors
 6719:          - missingbubble - array ref of the bubble lines that have missing
 6720:                            bubble errors
 6721: 
 6722: =cut
 6723: 
 6724: sub scantron_get_correction {
 6725:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6726: #FIXME in the case of a duplicated ID the previous line, probably need
 6727: #to show both the current line and the previous one and allow skipping
 6728: #the previous one or the current one
 6729: 
 6730:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6731: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6732: 			    " for PaperID <tt>[_1]</tt>",
 6733: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6734:     } else {
 6735: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6736: 			    " in scanline [_1] <pre>[_2]</pre>",
 6737: 			    $i,$line)."</p> \n");
 6738:     }
 6739:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6740: 			  "The name on the paper is [_2],[_3]",
 6741: 			  $$scan_record{'scantron.ID'},
 6742: 			  $$scan_record{'scantron.LastName'},
 6743: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6744: 
 6745:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6746:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6747:                            # Array populated for doublebubble or
 6748:     my @lines_to_correct;  # missingbubble errors to build javascript
 6749:                            # to validate radio button checking   
 6750: 
 6751:     if ($error =~ /ID$/) {
 6752: 	if ($error eq 'incorrectID') {
 6753: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6754: 		      "</p>\n");
 6755: 	} elsif ($error eq 'duplicateID') {
 6756: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6757: 	}
 6758: 	$r->print($message);
 6759: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6760: 	$r->print("\n<ul><li> ");
 6761: 	#FIXME it would be nice if this sent back the user ID and
 6762: 	#could do partial userID matches
 6763: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6764: 				       'scantron_username','scantron_domain'));
 6765: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6766: 	$r->print("\n@".
 6767: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6768: 
 6769: 	$r->print('</li>');
 6770:     } elsif ($error =~ /CODE$/) {
 6771: 	if ($error eq 'incorrectCODE') {
 6772: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6773: 	} elsif ($error eq 'duplicateCODE') {
 6774: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
 6775: 	}
 6776: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6777: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6778: 	$r->print($message);
 6779: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6780: 	$r->print("\n<br /> ");
 6781: 	my $i=0;
 6782: 	if ($error eq 'incorrectCODE' 
 6783: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6784: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6785: 	    if ($closest > 0) {
 6786: 		foreach my $testcode (@{$closest}) {
 6787: 		    my $checked='';
 6788: 		    if (!$i) { $checked=' checked="checked" '; }
 6789: 		    $r->print("
 6790:    <label>
 6791:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6792:        ".&mt("Use the similar CODE [_1] instead.",
 6793: 	    "<b><tt>".$testcode."</tt></b>")."
 6794:     </label>
 6795:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6796: 		    $r->print("\n<br />");
 6797: 		    $i++;
 6798: 		}
 6799: 	    }
 6800: 	}
 6801: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6802: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6803: 	    $r->print("
 6804:     <label>
 6805:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6806:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6807: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6808:     </label>");
 6809: 	    $r->print("\n<br />");
 6810: 	}
 6811: 
 6812: 	$r->print(<<ENDSCRIPT);
 6813: <script type="text/javascript">
 6814: function change_radio(field) {
 6815:     var slct=document.scantronupload.scantron_CODE_resolution;
 6816:     var i;
 6817:     for (i=0;i<slct.length;i++) {
 6818:         if (slct[i].value==field) { slct[i].checked=true; }
 6819:     }
 6820: }
 6821: </script>
 6822: ENDSCRIPT
 6823: 	my $href="/adm/pickcode?".
 6824: 	   "form=".&escape("scantronupload").
 6825: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6826: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6827: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6828: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6829: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6830: 	    $r->print("
 6831:     <label>
 6832:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6833:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6834: 	     "<a target='_blank' href='$href'>","</a>")."
 6835:     </label> 
 6836:     ".&mt('Selected CODE is [_1]','<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
 6837: 	    $r->print("\n<br />");
 6838: 	}
 6839: 	$r->print("
 6840:     <label>
 6841:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6842:        ".&mt("Use [_1] as the CODE.",
 6843: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6844: 	$r->print("\n<br /><br />");
 6845:     } elsif ($error eq 'doublebubble') {
 6846: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6847: 
 6848: 	# The form field scantron_questions is acutally a list of line numbers.
 6849: 	# represented by this form so:
 6850: 
 6851: 	my $line_list = &questions_to_line_list($arg);
 6852: 
 6853: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6854: 		  $line_list.'" />');
 6855: 	$r->print($message);
 6856: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6857: 	foreach my $question (@{$arg}) {
 6858: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6859:                                                    $scan_record, $error);
 6860:             push(@lines_to_correct,@linenums);
 6861: 	}
 6862:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6863:     } elsif ($error eq 'missingbubble') {
 6864: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6865: 	$r->print($message);
 6866: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6867: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6868: 
 6869: 	# The form field scantron_questions is actually a list of line numbers not
 6870: 	# a list of question numbers. Therefore:
 6871: 	#
 6872: 	
 6873: 	my $line_list = &questions_to_line_list($arg);
 6874: 
 6875: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6876: 		  $line_list.'" />');
 6877: 	foreach my $question (@{$arg}) {
 6878: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6879:                                                    $scan_record, $error);
 6880:             push(@lines_to_correct,@linenums);
 6881: 	}
 6882:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6883:     } else {
 6884: 	$r->print("\n<ul>");
 6885:     }
 6886:     $r->print("\n</li></ul>");
 6887: }
 6888: 
 6889: sub verify_bubbles_checked {
 6890:     my (@ansnums) = @_;
 6891:     my $ansnumstr = join('","',@ansnums);
 6892:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6893:     my $output = (<<ENDSCRIPT);
 6894: <script type="text/javascript">
 6895: function verify_bubble_radio(form) {
 6896:     var ansnumArray = new Array ("$ansnumstr");
 6897:     var need_bubble_count = 0;
 6898:     for (var i=0; i<ansnumArray.length; i++) {
 6899:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6900:             var bubble_picked = 0; 
 6901:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6902:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6903:                     bubble_picked = 1;
 6904:                 }
 6905:             }
 6906:             if (bubble_picked == 0) {
 6907:                 need_bubble_count ++;
 6908:             }
 6909:         }
 6910:     }
 6911:     if (need_bubble_count) {
 6912:         alert("$warning");
 6913:         return;
 6914:     }
 6915:     form.submit(); 
 6916: }
 6917: </script>
 6918: ENDSCRIPT
 6919:     return $output;
 6920: }
 6921: 
 6922: =pod
 6923: 
 6924: =item  questions_to_line_list
 6925: 
 6926: Converts a list of questions into a string of comma separated
 6927: line numbers in the answer sheet used by the questions.  This is
 6928: used to fill in the scantron_questions form field.
 6929: 
 6930:   Arguments:
 6931:      questions    - Reference to an array of questions.
 6932: 
 6933: =cut
 6934: 
 6935: 
 6936: sub questions_to_line_list {
 6937:     my ($questions) = @_;
 6938:     my @lines;
 6939: 
 6940:     foreach my $item (@{$questions}) {
 6941:         my $question = $item;
 6942:         my ($first,$count,$last);
 6943:         if ($item =~ /^(\d+)\.(\d+)$/) {
 6944:             $question = $1;
 6945:             my $subquestion = $2;
 6946:             $first = $first_bubble_line{$question-1} + 1;
 6947:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 6948:             my $subcount = 1;
 6949:             while ($subcount<$subquestion) {
 6950:                 $first += $subans[$subcount-1];
 6951:                 $subcount ++;
 6952:             }
 6953:             $count = $subans[$subquestion-1];
 6954:         } else {
 6955: 	    $first   = $first_bubble_line{$question-1} + 1;
 6956: 	    $count   = $bubble_lines_per_response{$question-1};
 6957:         }
 6958:         $last = $first+$count-1;
 6959:         push(@lines, ($first..$last));
 6960:     }
 6961:     return join(',', @lines);
 6962: }
 6963: 
 6964: =pod 
 6965: 
 6966: =item prompt_for_corrections
 6967: 
 6968: Prompts for a potentially multiline correction to the
 6969: user's bubbling (factors out common code from scantron_get_correction
 6970: for multi and missing bubble cases).
 6971: 
 6972:  Arguments:
 6973:    $r           - Apache request object.
 6974:    $question    - The question number to prompt for.
 6975:    $scan_config - The scantron file configuration hash.
 6976:    $scan_record - Reference to the hash that has the the parsed scanlines.
 6977:    $error       - Type of error
 6978: 
 6979:  Implicit inputs:
 6980:    %bubble_lines_per_response   - Starting line numbers for each question.
 6981:                                   Numbered from 0 (but question numbers are from
 6982:                                   1.
 6983:    %first_bubble_line           - Starting bubble line for each question.
 6984:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 6985:                                   type problems render as separate sub-questions, 
 6986:                                   in exam mode. This hash contains a 
 6987:                                   comma-separated list of the lines per 
 6988:                                   sub-question.
 6989:    %responsetype_per_response   - essayresponse, formularesponse,
 6990:                                   stringresponse, imageresponse, reactionresponse,
 6991:                                   and organicresponse type problem parts can have
 6992:                                   multiple lines per response if the weight
 6993:                                   assigned exceeds 10.  In this case, only
 6994:                                   one bubble per line is permitted, but more 
 6995:                                   than one line might contain bubbles, e.g.
 6996:                                   bubbling of: line 1 - J, line 2 - J, 
 6997:                                   line 3 - B would assign 22 points.  
 6998: 
 6999: =cut
 7000: 
 7001: sub prompt_for_corrections {
 7002:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7003:     my ($current_line,$lines);
 7004:     my @linenums;
 7005:     my $questionnum = $question;
 7006:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7007:         $question = $1;
 7008:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7009:         my $subquestion = $2;
 7010:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7011:         my $subcount = 1;
 7012:         while ($subcount<$subquestion) {
 7013:             $current_line += $subans[$subcount-1];
 7014:             $subcount ++;
 7015:         }
 7016:         $lines = $subans[$subquestion-1];
 7017:     } else {
 7018:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7019:         $lines        = $bubble_lines_per_response{$question-1};
 7020:     }
 7021:     if ($lines > 1) {
 7022:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7023:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7024:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7025:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7026:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7027:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7028:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7029:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
 7030:         } else {
 7031:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7032:         }
 7033:     }
 7034:     for (my $i =0; $i < $lines; $i++) {
 7035:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7036: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7037: 	        		  $questionnum,$error,split('', $selected));
 7038:         push(@linenums,$current_line);
 7039: 	$current_line++;
 7040:     }
 7041:     if ($lines > 1) {
 7042: 	$r->print("<hr /><br />");
 7043:     }
 7044:     return @linenums;
 7045: }
 7046: 
 7047: =pod
 7048: 
 7049: =item scantron_bubble_selector
 7050:   
 7051:    Generates the html radiobuttons to correct a single bubble line
 7052:    possibly showing the existing the selected bubbles if known
 7053: 
 7054:  Arguments:
 7055:     $r           - Apache request object
 7056:     $scan_config - hash from &get_scantron_config()
 7057:     $line        - Number of the line being displayed.
 7058:     $questionnum - Question number (may include subquestion)
 7059:     $error       - Type of error.
 7060:     @selected    - Array of bubbles picked on this line.
 7061: 
 7062: =cut
 7063: 
 7064: sub scantron_bubble_selector {
 7065:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7066:     my $max=$$scan_config{'Qlength'};
 7067: 
 7068:     my $scmode=$$scan_config{'Qon'};
 7069:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7070: 
 7071:     my @alphabet=('A'..'Z');
 7072:     $r->print(&Apache::loncommon::start_data_table().
 7073:               &Apache::loncommon::start_data_table_row());
 7074:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7075:     for (my $i=0;$i<$max+1;$i++) {
 7076: 	$r->print("\n".'<td align="center">');
 7077: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7078: 	else { $r->print('&nbsp;'); }
 7079: 	$r->print('</td>');
 7080:     }
 7081:     $r->print(&Apache::loncommon::end_data_table_row().
 7082:               &Apache::loncommon::start_data_table_row());
 7083:     for (my $i=0;$i<$max;$i++) {
 7084: 	$r->print("\n".
 7085: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7086: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7087:     }
 7088:     my $nobub_checked = ' ';
 7089:     if ($error eq 'missingbubble') {
 7090:         $nobub_checked = ' checked = "checked" ';
 7091:     }
 7092:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7093: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7094:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7095:               $line.'" value="'.$questionnum.'" /></td>');
 7096:     $r->print(&Apache::loncommon::end_data_table_row().
 7097:               &Apache::loncommon::end_data_table());
 7098: }
 7099: 
 7100: =pod
 7101: 
 7102: =item num_matches
 7103: 
 7104:    Counts the number of characters that are the same between the two arguments.
 7105: 
 7106:  Arguments:
 7107:    $orig - CODE from the scanline
 7108:    $code - CODE to match against
 7109: 
 7110:  Returns:
 7111:    $count - integer count of the number of same characters between the
 7112:             two arguments
 7113: 
 7114: =cut
 7115: 
 7116: sub num_matches {
 7117:     my ($orig,$code) = @_;
 7118:     my @code=split(//,$code);
 7119:     my @orig=split(//,$orig);
 7120:     my $same=0;
 7121:     for (my $i=0;$i<scalar(@code);$i++) {
 7122: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7123:     }
 7124:     return $same;
 7125: }
 7126: 
 7127: =pod
 7128: 
 7129: =item scantron_get_closely_matching_CODEs
 7130: 
 7131:    Cycles through all CODEs and finds the set that has the greatest
 7132:    number of same characters as the provided CODE
 7133: 
 7134:  Arguments:
 7135:    $allcodes - hash ref returned by &get_codes()
 7136:    $CODE     - CODE from the current scanline
 7137: 
 7138:  Returns:
 7139:    2 element list
 7140:     - first elements is number of how closely matching the best fit is 
 7141:       (5 means best set has 5 matching characters)
 7142:     - second element is an arrary ref containing the set of valid CODEs
 7143:       that best fit the passed in CODE
 7144: 
 7145: =cut
 7146: 
 7147: sub scantron_get_closely_matching_CODEs {
 7148:     my ($allcodes,$CODE)=@_;
 7149:     my @CODEs;
 7150:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7151: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7152:     }
 7153: 
 7154:     return ($#CODEs,$CODEs[-1]);
 7155: }
 7156: 
 7157: =pod
 7158: 
 7159: =item get_codes
 7160: 
 7161:    Builds a hash which has keys of all of the valid CODEs from the selected
 7162:    set of remembered CODEs.
 7163: 
 7164:  Arguments:
 7165:   $old_name - name of the set of remembered CODEs
 7166:   $cdom     - domain of the course
 7167:   $cnum     - internal course name
 7168: 
 7169:  Returns:
 7170:   %allcodes - keys are the valid CODEs, values are all 1
 7171: 
 7172: =cut
 7173: 
 7174: sub get_codes {
 7175:     my ($old_name, $cdom, $cnum) = @_;
 7176:     if (!$old_name) {
 7177: 	$old_name=$env{'form.scantron_CODElist'};
 7178:     }
 7179:     if (!$cdom) {
 7180: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7181:     }
 7182:     if (!$cnum) {
 7183: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7184:     }
 7185:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7186: 				    $cdom,$cnum);
 7187:     my %allcodes;
 7188:     if ($result{"type\0$old_name"} eq 'number') {
 7189: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7190:     } else {
 7191: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7192:     }
 7193:     return %allcodes;
 7194: }
 7195: 
 7196: =pod
 7197: 
 7198: =item scantron_validate_CODE
 7199: 
 7200:    Validates all scanlines in the selected file to not have any
 7201:    invalid or underspecified CODEs and that none of the codes are
 7202:    duplicated if this was requested.
 7203: 
 7204: =cut
 7205: 
 7206: sub scantron_validate_CODE {
 7207:     my ($r,$currentphase) = @_;
 7208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7209:     if ($scantron_config{'CODElocation'} &&
 7210: 	$scantron_config{'CODEstart'} &&
 7211: 	$scantron_config{'CODElength'}) {
 7212: 	if (!defined($env{'form.scantron_CODElist'})) {
 7213: 	    &FIXME_blow_up()
 7214: 	}
 7215:     } else {
 7216: 	return (0,$currentphase+1);
 7217:     }
 7218:     
 7219:     my %usedCODEs;
 7220: 
 7221:     my %allcodes=&get_codes();
 7222: 
 7223:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7224: 
 7225:     my ($scanlines,$scan_data)=&scantron_getfile();
 7226:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7227: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7228: 	if ($line=~/^[\s\cz]*$/) { next; }
 7229: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7230: 						 $scan_data);
 7231: 	my $CODE=$$scan_record{'scantron.CODE'};
 7232: 	my $error=0;
 7233: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7234: 	    &scantron_get_correction($r,$i,$scan_record,
 7235: 				     \%scantron_config,
 7236: 				     $line,'incorrectCODE',\%allcodes);
 7237: 	    return(1,$currentphase);
 7238: 	}
 7239: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7240: 	    && !$$scan_record{'scantron.useCODE'}) {
 7241: 	    &scantron_get_correction($r,$i,$scan_record,
 7242: 				     \%scantron_config,
 7243: 				     $line,'incorrectCODE',\%allcodes);
 7244: 	    return(1,$currentphase);
 7245: 	}
 7246: 	if (exists($usedCODEs{$CODE}) 
 7247: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7248: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7249: 	    &scantron_get_correction($r,$i,$scan_record,
 7250: 				     \%scantron_config,
 7251: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7252: 	    return(1,$currentphase);
 7253: 	}
 7254: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7255:     }
 7256:     return (0,$currentphase+1);
 7257: }
 7258: 
 7259: =pod
 7260: 
 7261: =item scantron_validate_doublebubble
 7262: 
 7263:    Validates all scanlines in the selected file to not have any
 7264:    bubble lines with multiple bubbles marked.
 7265: 
 7266: =cut
 7267: 
 7268: sub scantron_validate_doublebubble {
 7269:     my ($r,$currentphase) = @_;
 7270:     #get student info
 7271:     my $classlist=&Apache::loncoursedata::get_classlist();
 7272:     my %idmap=&username_to_idmap($classlist);
 7273: 
 7274:     #get scantron line setup
 7275:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7276:     my ($scanlines,$scan_data)=&scantron_getfile();
 7277:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7278: 
 7279:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7280: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7281: 	if ($line=~/^[\s\cz]*$/) { next; }
 7282: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7283: 						 $scan_data);
 7284: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7285: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7286: 				 'doublebubble',
 7287: 				 $$scan_record{'scantron.doubleerror'});
 7288:     	return (1,$currentphase);
 7289:     }
 7290:     return (0,$currentphase+1);
 7291: }
 7292: 
 7293: =pod
 7294: 
 7295: =item scantron_get_maxbubble
 7296: 
 7297:    Returns the maximum number of bubble lines that are expected to
 7298:    occur. Does this by walking the selected sequence rendering the
 7299:    resource and then checking &Apache::lonxml::get_problem_counter()
 7300:    for what the current value of the problem counter is.
 7301: 
 7302:    Caches the results to $env{'form.scantron_maxbubble'},
 7303:    $env{'form.scantron.bubble_lines.n'}, 
 7304:    $env{'form.scantron.first_bubble_line.n'} and
 7305:    $env{"form.scantron.sub_bubblelines.n"}
 7306:    which are the total number of bubble, lines, the number of bubble
 7307:    lines for response n and number of the first bubble line for response n,
 7308:    and a comma separated list of numbers of bubble lines for sub-questions
 7309:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
 7310: 
 7311: =cut
 7312: 
 7313: sub scantron_get_maxbubble {
 7314:     if (defined($env{'form.scantron_maxbubble'}) &&
 7315: 	$env{'form.scantron_maxbubble'}) {
 7316: 	&restore_bubble_lines();
 7317: 	return $env{'form.scantron_maxbubble'};
 7318:     }
 7319: 
 7320:     my (undef, undef, $sequence) =
 7321: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7322: 
 7323:     my $navmap=Apache::lonnavmaps::navmap->new();
 7324:     my $map=$navmap->getResourceByUrl($sequence);
 7325:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7326: 
 7327:     &Apache::lonxml::clear_problem_counter();
 7328: 
 7329:     my $uname       = $env{'form.student'};
 7330:     my $udom        = $env{'form.userdom'};
 7331:     my $cid         = $env{'request.course.id'};
 7332:     my $total_lines = 0;
 7333:     %bubble_lines_per_response = ();
 7334:     %first_bubble_line         = ();
 7335:     %subdivided_bubble_lines   = ();
 7336:     %responsetype_per_response = ();
 7337:   
 7338:     my $response_number = 0;
 7339:     my $bubble_line     = 0;
 7340:     foreach my $resource (@resources) {
 7341:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
 7342:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
 7343:             foreach my $part_id (@{$parts}) {
 7344: 
 7345:                 my $lines;
 7346: 
 7347: 	        # TODO - make this a persistent hash not an array.
 7348: 
 7349:                 # optionresponse, matchresponse and rankresponse type items 
 7350:                 # render as separate sub-questions in exam mode.
 7351:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
 7352:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
 7353:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
 7354:                     my ($numbub,$numshown);
 7355:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
 7356:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
 7357:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
 7358:                         }
 7359:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
 7360:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
 7361:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
 7362:                         }
 7363:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
 7364:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
 7365:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
 7366:                         }
 7367:                     }
 7368:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
 7369:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
 7370:                     }
 7371:                     my $bubbles_per_line = 10;
 7372:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7373:                     if (($numbub % $bubbles_per_line) != 0) {
 7374:                         $inner_bubble_lines++;
 7375:                     }
 7376:                     for (my $i=0; $i<$numshown; $i++) {
 7377:                         $subdivided_bubble_lines{$response_number} .= 
 7378:                             $inner_bubble_lines.',';
 7379:                     }
 7380:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7381:                     $lines = $numshown * $inner_bubble_lines;
 7382:                 } else {
 7383:                     $lines = $analysis->{"$part_id.bubble_lines"};
 7384:                 } 
 7385: 
 7386:                 $first_bubble_line{$response_number} = $bubble_line;
 7387: 	        $bubble_lines_per_response{$response_number} = $lines;
 7388:                 $responsetype_per_response{$response_number} = 
 7389:                     $analysis->{$part_id.'.type'};
 7390: 	        $response_number++;
 7391: 
 7392: 	        $bubble_line +=  $lines;
 7393: 	        $total_lines +=  $lines;
 7394: 	    }
 7395:         }
 7396:     }
 7397:     &Apache::lonnet::delenv('scantron.');
 7398: 
 7399:     &save_bubble_lines();
 7400:     $env{'form.scantron_maxbubble'} =
 7401: 	$total_lines;
 7402:     return $env{'form.scantron_maxbubble'};
 7403: }
 7404: 
 7405: sub scantron_partids_tograde {
 7406:     my ($resource,$cid,$uname,$udom) = @_;
 7407:     my (%analysis,@parts);
 7408: 
 7409:     if (ref($resource)) {
 7410:         my $symb = $resource->symb();
 7411:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7412:                                         ('symb' => $symb,
 7413:                                          'grade_target' => 'analyze',
 7414:                                          'grade_courseid' => $cid,
 7415:                                          'grade_domain' => $udom,
 7416:                                          'grade_username' => $uname));
 7417:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
 7418:         %analysis = &Apache::lonnet::str2hash($an);
 7419: 
 7420:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7421:             foreach my $part (@{$analysis{'parts'}}) {
 7422:                 my ($id,$respid) = split(/\./,$part);
 7423:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7424:                     push(@parts,$part);
 7425:                 }
 7426:             }
 7427:         }
 7428:     }
 7429:     return (\%analysis,\@parts);
 7430: }
 7431: 
 7432: =pod
 7433: 
 7434: =item scantron_validate_missingbubbles
 7435: 
 7436:    Validates all scanlines in the selected file to not have any
 7437:     answers that don't have bubbles that have not been verified
 7438:     to be bubble free.
 7439: 
 7440: =cut
 7441: 
 7442: sub scantron_validate_missingbubbles {
 7443:     my ($r,$currentphase) = @_;
 7444:     #get student info
 7445:     my $classlist=&Apache::loncoursedata::get_classlist();
 7446:     my %idmap=&username_to_idmap($classlist);
 7447: 
 7448:     #get scantron line setup
 7449:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7450:     my ($scanlines,$scan_data)=&scantron_getfile();
 7451:     my $max_bubble=&scantron_get_maxbubble();
 7452:     if (!$max_bubble) { $max_bubble=2**31; }
 7453:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7454: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7455: 	if ($line=~/^[\s\cz]*$/) { next; }
 7456: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7457: 						 $scan_data);
 7458: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7459: 	my @to_correct;
 7460: 	
 7461: 	# Probably here's where the error is...
 7462: 
 7463: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7464:             my $lastbubble;
 7465:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7466:                my $question = $1;
 7467:                my $subquestion = $2;
 7468:                if (!defined($first_bubble_line{$question -1})) { next; }
 7469:                my $first = $first_bubble_line{$question-1};
 7470:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7471:                my $subcount = 1;
 7472:                while ($subcount<$subquestion) {
 7473:                    $first += $subans[$subcount-1];
 7474:                    $subcount ++;
 7475:                }
 7476:                my $count = $subans[$subquestion-1];
 7477:                $lastbubble = $first + $count;
 7478:             } else {
 7479:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7480:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7481:             }
 7482:             if ($lastbubble > $max_bubble) { next; }
 7483: 	    push(@to_correct,$missing);
 7484: 	}
 7485: 	if (@to_correct) {
 7486: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7487: 				     $line,'missingbubble',\@to_correct);
 7488: 	    return (1,$currentphase);
 7489: 	}
 7490: 
 7491:     }
 7492:     return (0,$currentphase+1);
 7493: }
 7494: 
 7495: =pod
 7496: 
 7497: =item scantron_process_students
 7498: 
 7499:    Routine that does the actual grading of the bubble sheet information.
 7500: 
 7501:    The parsed scanline hash is added to %env 
 7502: 
 7503:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 7504:    foreach resource , with the form data of
 7505: 
 7506: 	'submitted'     =>'scantron' 
 7507: 	'grade_target'  =>'grade',
 7508: 	'grade_username'=> username of student
 7509: 	'grade_domain'  => domain of student
 7510: 	'grade_courseid'=> of course
 7511: 	'grade_symb'    => symb of resource to grade
 7512: 
 7513:     This triggers a grading pass. The problem grading code takes care
 7514:     of converting the bubbled letter information (now in %env) into a
 7515:     valid submission.
 7516: 
 7517: =cut
 7518: 
 7519: sub scantron_process_students {
 7520:     my ($r) = @_;
 7521: 
 7522:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7523:     my ($symb)=&get_symb($r);
 7524:     if (!$symb) {
 7525: 	return '';
 7526:     }
 7527:     my $default_form_data=&defaultFormData($symb);
 7528: 
 7529:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7530:     my ($scanlines,$scan_data)=&scantron_getfile();
 7531:     my $classlist=&Apache::loncoursedata::get_classlist();
 7532:     my %idmap=&username_to_idmap($classlist);
 7533:     my $navmap=Apache::lonnavmaps::navmap->new();
 7534:     my $map=$navmap->getResourceByUrl($sequence);
 7535:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7536: 
 7537:     my ($uname,$udom,%partids_by_symb);
 7538:     foreach my $resource (@resources) {
 7539:         my $ressymb = $resource->symb();
 7540:         my ($analysis,$parts) =
 7541:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7542:         $partids_by_symb{$ressymb} = $parts;
 7543:     }
 7544: #    $r->print("geto ".scalar(@resources)."<br />");
 7545:     my $result= <<SCANTRONFORM;
 7546: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7547:   <input type="hidden" name="command" value="scantron_configphase" />
 7548:   $default_form_data
 7549: SCANTRONFORM
 7550:     $r->print($result);
 7551: 
 7552:     my @delayqueue;
 7553:     my (%completedstudents,,%scandata);
 7554:     
 7555:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7556:     my $count=&get_todo_count($scanlines,$scan_data);
 7557:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7558:  				    'Scantron Progress',$count,
 7559: 				    'inline',undef,'scantronupload');
 7560:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7561: 					  'Processing first student');
 7562:     $r->print('<br />');
 7563:     my $start=&Time::HiRes::time();
 7564:     my $i=-1;
 7565:     my $started;
 7566: 
 7567:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7568:     
 7569: 
 7570:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7571:     # the user and return.
 7572: 
 7573:     if ($ssi_error) {
 7574: 	$r->print("</form>");
 7575: 	&ssi_print_error($r);
 7576: 	$r->print(&show_grading_menu_form($symb));
 7577:         &Apache::lonnet::remove_lock($lock);
 7578: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7579:     }
 7580: 
 7581:     my %lettdig = &letter_to_digits();
 7582:     my $numletts = scalar(keys(%lettdig));
 7583: 
 7584:     while ($i<$scanlines->{'count'}) {
 7585:  	($uname,$udom)=('','');
 7586:  	$i++;
 7587:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7588:  	if ($line=~/^[\s\cz]*$/) { next; }
 7589: 	if ($started) {
 7590: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7591: 						     'last student');
 7592: 	}
 7593: 	$started=1;
 7594:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7595:  						 $scan_data);
 7596:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7597:  					      \%idmap,$i)) {
 7598:   	    &scantron_add_delay(\@delayqueue,$line,
 7599:  				'Unable to find a student that matches',1);
 7600:  	    next;
 7601:   	}
 7602:  	if (exists $completedstudents{$uname}) {
 7603:  	    &scantron_add_delay(\@delayqueue,$line,
 7604:  				'Student '.$uname.' has multiple sheets',2);
 7605:  	    next;
 7606:  	}
 7607:   	($uname,$udom)=split(/:/,$uname);
 7608: 
 7609: 	&Apache::lonxml::clear_problem_counter();
 7610:   	&Apache::lonnet::appenv($scan_record);
 7611: 
 7612: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7613: 	    &scantron_putfile($scanlines,$scan_data);
 7614: 	}
 7615: 
 7616:         my $scancode;
 7617:         if ((exists($scan_record->{'scantron.CODE'})) &&
 7618:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
 7619:             $scancode = $scan_record->{'scantron.CODE'};
 7620:         } else {
 7621:             $scancode = '';
 7622:         }
 7623: 
 7624:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7625:                                    @resources) eq 'ssi_error') {
 7626:             $ssi_error = 0; # So end of handler error message does not trigger.
 7627:             $r->print("</form>");
 7628:             &ssi_print_error($r);
 7629:             $r->print(&show_grading_menu_form($symb));
 7630:             &Apache::lonnet::remove_lock($lock);
 7631:             return '';      # Why return ''?  Beats me.
 7632:         }
 7633: 
 7634: 	$completedstudents{$uname}={'line'=>$line};
 7635:         if ($env{'form.verifyrecord'}) {
 7636:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7637:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7638:             chomp($studentdata);
 7639:             $studentdata =~ s/\r$//;
 7640:             my $studentrecord = '';
 7641:             my $counter = -1;
 7642:             foreach my $resource (@resources) {
 7643:                 ($counter,my $recording) =
 7644:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7645:                                              $counter,$studentdata,\%partids_by_symb,
 7646:                                              \%scantron_config,\%lettdig,$numletts);
 7647:                 $studentrecord .= $recording;
 7648:             }
 7649:             if ($studentrecord ne $studentdata) {
 7650:                 &Apache::lonxml::clear_problem_counter();
 7651:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
 7652:                                            @resources) eq 'ssi_error') {
 7653:                     $ssi_error = 0; # So end of handler error message does not trigger.
 7654:                     $r->print("</form>");
 7655:                     &ssi_print_error($r);
 7656:                     $r->print(&show_grading_menu_form($symb));
 7657:                     &Apache::lonnet::remove_lock($lock);
 7658:                     delete($completedstudents{$uname});
 7659:                     return '';
 7660:                 }
 7661:                 $counter = -1;
 7662:                 $studentrecord = '';
 7663:                 foreach my $resource (@resources) {
 7664:                     ($counter,my $recording) =
 7665:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
 7666:                                                  $counter,$studentdata,\%partids_by_symb,
 7667:                                                  \%scantron_config,\%lettdig,$numletts);
 7668:                     $studentrecord .= $recording;
 7669:                 }
 7670:                 if ($studentrecord ne $studentdata) {
 7671:                     $r->print('<p><span class="LC_error">');
 7672:                     if ($scancode eq '') {
 7673:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
 7674:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
 7675:                     } else {
 7676:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
 7677:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
 7678:                     }
 7679:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
 7680:                               &Apache::loncommon::start_data_table_header_row()."\n".
 7681:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
 7682:                               &Apache::loncommon::end_data_table_header_row()."\n".
 7683:                               &Apache::loncommon::start_data_table_row().
 7684:                               '<td>'.&mt('Bubble Sheet').'</td>'.
 7685:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
 7686:                               &Apache::loncommon::end_data_table_row().
 7687:                               &Apache::loncommon::start_data_table_row().
 7688:                               '<td>Stored submissions</td>'.
 7689:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
 7690:                               &Apache::loncommon::end_data_table_row().
 7691:                               &Apache::loncommon::end_data_table().'</p>');
 7692:                 } else {
 7693:                     $r->print('<br /><span class="LC_warning">'.
 7694:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
 7695:                              &mt("As a consequence, this user's submission history records two tries.").
 7696:                                  '</span><br />');
 7697:                 }
 7698:             }
 7699:         }
 7700: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7701:     } continue {
 7702: 	&Apache::lonxml::clear_problem_counter();
 7703: 	&Apache::lonnet::delenv('scantron.');
 7704:     }
 7705:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7706:     &Apache::lonnet::remove_lock($lock);
 7707: #    my $lasttime = &Time::HiRes::time()-$start;
 7708: #    $r->print("<p>took $lasttime</p>");
 7709: 
 7710:     $r->print("</form>");
 7711:     $r->print(&show_grading_menu_form($symb));
 7712:     return '';
 7713: }
 7714: 
 7715: sub grade_student_bubbles {
 7716:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
 7717:     foreach my $resource (@resources) {
 7718:         my %form = ('submitted'     => 'scantron',
 7719:                     'grade_target'  => 'grade',
 7720:                     'grade_username'=> $uname,
 7721:                     'grade_domain'  => $udom,
 7722:                     'grade_courseid'=> $env{'request.course.id'},
 7723:                     'grade_symb'    => $resource->symb(),
 7724:                     'CODE'          => $scancode);
 7725:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
 7726:         return 'ssi_error' if ($ssi_error);
 7727:         last if (&Apache::loncommon::connection_aborted($r));
 7728:     }
 7729:     return;
 7730: }
 7731: 
 7732: =pod
 7733: 
 7734: =item scantron_upload_scantron_data
 7735: 
 7736:     Creates the screen for adding a new bubble sheet data file to a course.
 7737: 
 7738: =cut
 7739: 
 7740: sub scantron_upload_scantron_data {
 7741:     my ($r)=@_;
 7742:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7743:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7744: 							  'domainid',
 7745: 							  'coursename');
 7746:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7747: 						   'domainid');
 7748:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7749:     $r->print('
 7750: <script type="text/javascript" language="javascript">
 7751:     function checkUpload(formname) {
 7752: 	if (formname.upfile.value == "") {
 7753: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 7754: 	    return false;
 7755: 	}
 7756: 	formname.submit();
 7757:     }
 7758: </script>
 7759: 
 7760: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7761: '.$default_form_data.'
 7762: <table>
 7763: <tr><td>'.$select_link.'                             </td></tr>
 7764: <tr><td>'.&mt('Course ID:').'     </td>
 7765:     <td><input name="courseid"   type="text" />      </td></tr>
 7766: <tr><td>'.&mt('Course Name:').'   </td>
 7767:     <td><input name="coursename" type="text" />      </td></tr>
 7768: <tr><td>'.&mt('Domain:').'        </td>
 7769:     <td>'.$domsel.'                                  </td></tr>
 7770: <tr><td>'.&mt('File to upload:').'</td>
 7771:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7772: </table>
 7773: <input name="command" value="scantronupload_save" type="hidden" />
 7774: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7775: </form>
 7776: ');
 7777:     return '';
 7778: }
 7779: 
 7780: =pod
 7781: 
 7782: =item scantron_upload_scantron_data_save
 7783: 
 7784:    Adds a provided bubble information data file to the course if user
 7785:    has the correct privileges to do so.  
 7786: 
 7787: =cut
 7788: 
 7789: sub scantron_upload_scantron_data_save {
 7790:     my($r)=@_;
 7791:     my ($symb)=&get_symb($r,1);
 7792:     my $doanotherupload=
 7793: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7794: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7795: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7796: 	'</form>'."\n";
 7797:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7798: 	!&Apache::lonnet::allowed('usc',
 7799: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7800: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7801: 	if ($symb) {
 7802: 	    $r->print(&show_grading_menu_form($symb));
 7803: 	} else {
 7804: 	    $r->print($doanotherupload);
 7805: 	}
 7806: 	return '';
 7807:     }
 7808:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7809:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7810:     my $fname=$env{'form.upfile.filename'};
 7811:     #FIXME
 7812:     #copied from lonnet::userfileupload()
 7813:     #make that function able to target a specified course
 7814:     # Replace Windows backslashes by forward slashes
 7815:     $fname=~s/\\/\//g;
 7816:     # Get rid of everything but the actual filename
 7817:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7818:     # Replace spaces by underscores
 7819:     $fname=~s/\s+/\_/g;
 7820:     # Replace all other weird characters by nothing
 7821:     $fname=~s/[^\w\.\-]//g;
 7822:     # See if there is anything left
 7823:     unless ($fname) { return 'error: no uploaded file'; }
 7824:     my $uploadedfile=$fname;
 7825:     $fname='scantron_orig_'.$fname;
 7826:     if (length($env{'form.upfile'}) < 2) {
 7827: 	$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>"));
 7828:     } else {
 7829: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7830: 	if ($result =~ m|^/uploaded/|) {
 7831: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7832: 			  (length($env{'form.upfile'})-1),
 7833: 			  '<span class="LC_filename">'.$result."</span>"));
 7834: 	} else {
 7835: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7836: 			  $result,
 7837: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7838: 
 7839: 	}
 7840:     }
 7841:     if ($symb) {
 7842: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7843:     } else {
 7844: 	$r->print($doanotherupload);
 7845:     }
 7846:     return '';
 7847: }
 7848: 
 7849: =pod
 7850: 
 7851: =item valid_file
 7852: 
 7853:    Validates that the requested bubble data file exists in the course.
 7854: 
 7855: =cut
 7856: 
 7857: sub valid_file {
 7858:     my ($requested_file)=@_;
 7859:     foreach my $filename (sort(&scantron_filenames())) {
 7860: 	if ($requested_file eq $filename) { return 1; }
 7861:     }
 7862:     return 0;
 7863: }
 7864: 
 7865: =pod
 7866: 
 7867: =item scantron_download_scantron_data
 7868: 
 7869:    Shows a list of the three internal files (original, corrected,
 7870:    skipped) for a specific bubble sheet data file that exists in the
 7871:    course.
 7872: 
 7873: =cut
 7874: 
 7875: sub scantron_download_scantron_data {
 7876:     my ($r)=@_;
 7877:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7878:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7879:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7880:     my $file=$env{'form.scantron_selectfile'};
 7881:     if (! &valid_file($file)) {
 7882: 	$r->print('
 7883: 	<p>
 7884: 	    '.&mt('The requested file name was invalid.').'
 7885:         </p>
 7886: ');
 7887: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7888: 	return;
 7889:     }
 7890:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7891:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7892:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7893:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7894:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7895:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7896:     $r->print('
 7897:     <p>
 7898: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7899: 	      '<a href="'.$orig.'">','</a>').'
 7900:     </p>
 7901:     <p>
 7902: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7903: 	      '<a href="'.$corrected.'">','</a>').'
 7904:     </p>
 7905:     <p>
 7906: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7907: 	      '<a href="'.$skipped.'">','</a>').'
 7908:     </p>
 7909: ');
 7910:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7911:     return '';
 7912: }
 7913: 
 7914: sub checkscantron_results {
 7915:     my ($r) = @_;
 7916:     my ($symb)=&get_symb($r);
 7917:     if (!$symb) {return '';}
 7918:     my $grading_menu_button=&show_grading_menu_form($symb);
 7919:     my $cid = $env{'request.course.id'};
 7920:     my %lettdig = &letter_to_digits();
 7921:     my $numletts = scalar(keys(%lettdig));
 7922:     my $cnum = $env{'course.'.$cid.'.num'};
 7923:     my $cdom = $env{'course.'.$cid.'.domain'};
 7924:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7925:     my %record;
 7926:     my %scantron_config =
 7927:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7928:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7929:     my $classlist=&Apache::loncoursedata::get_classlist();
 7930:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7931:     my $navmap=Apache::lonnavmaps::navmap->new();
 7932:     my $map=$navmap->getResourceByUrl($sequence);
 7933:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7934:     my ($uname,$udom,%partids_by_symb);
 7935:     foreach my $resource (@resources) {
 7936:         my $ressymb = $resource->symb();
 7937:         my ($analysis,$parts) =
 7938:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
 7939:         $partids_by_symb{$ressymb} = $parts;
 7940:     }
 7941:     my (%scandata,%lastname,%bylast);
 7942:     $r->print('
 7943: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7944: 
 7945:     my @delayqueue;
 7946:     my %completedstudents;
 7947: 
 7948:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7949:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7950:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7951:                                     'inline',undef,'checkscantron');
 7952:     my ($username,$domain,$started);
 7953: 
 7954:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7955: 
 7956:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7957:                                           'Processing first student');
 7958:     my $start=&Time::HiRes::time();
 7959:     my $i=-1;
 7960: 
 7961:     while ($i<$scanlines->{'count'}) {
 7962:         ($username,$domain,$uname)=('','','');
 7963:         $i++;
 7964:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7965:         if ($line=~/^[\s\cz]*$/) { next; }
 7966:         if ($started) {
 7967:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7968:                                                      'last student');
 7969:         }
 7970:         $started=1;
 7971:         my $scan_record=
 7972:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7973:                                                      $scan_data);
 7974:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7975:                                                               \%idmap,$i)) {
 7976:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7977:                                 'Unable to find a student that matches',1);
 7978:             next;
 7979:         }
 7980:         if (exists $completedstudents{$uname}) {
 7981:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7982:                                 'Student '.$uname.' has multiple sheets',2);
 7983:             next;
 7984:         }
 7985:         my $pid = $scan_record->{'scantron.ID'};
 7986:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7987:         push(@{$bylast{$lastname{$pid}}},$pid);
 7988:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7989:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7990:         chomp($scandata{$pid});
 7991:         $scandata{$pid} =~ s/\r$//;
 7992:         ($username,$domain)=split(/:/,$uname);
 7993:         my $counter = -1;
 7994:         foreach my $resource (@resources) {
 7995:             ($counter,my $recording) =
 7996:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
 7997:                                          $scandata{$pid},\%partids_by_symb,
 7998:                                          \%scantron_config,\%lettdig,$numletts);
 7999:             $record{$pid} .= $recording;
 8000:         }
 8001:     }
 8002:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8003:     $r->print('<br />');
 8004:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8005:     $passed = 0;
 8006:     $failed = 0;
 8007:     $numstudents = 0;
 8008:     foreach my $last (sort(keys(%bylast))) {
 8009:         if (ref($bylast{$last}) eq 'ARRAY') {
 8010:             foreach my $pid (sort(@{$bylast{$last}})) {
 8011:                 my $showscandata = $scandata{$pid};
 8012:                 my $showrecord = $record{$pid};
 8013:                 $showscandata =~ s/\s/&nbsp;/g;
 8014:                 $showrecord =~ s/\s/&nbsp;/g;
 8015:                 if ($scandata{$pid} eq $record{$pid}) {
 8016:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8017:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8018: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8019: '</tr>'."\n".
 8020: '<tr class="'.$css_class.'">'."\n".
 8021: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8022:                     $passed ++;
 8023:                 } else {
 8024:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8025:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8026: '</tr>'."\n".
 8027: '<tr class="'.$css_class.'">'."\n".
 8028: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8029: '</tr>'."\n";
 8030:                     $failed ++;
 8031:                 }
 8032:                 $numstudents ++;
 8033:             }
 8034:         }
 8035:     }
 8036:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
 8037:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
 8038:     if ($passed) {
 8039:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8040:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8041:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8042:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8043:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8044:                  $okstudents."\n".
 8045:                  &Apache::loncommon::end_data_table().'<br />');
 8046:     }
 8047:     if ($failed) {
 8048:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8049:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8050:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8051:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8052:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8053:                  $badstudents."\n".
 8054:                  &Apache::loncommon::end_data_table()).'<br />'.
 8055:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
 8056:     }
 8057:     $r->print('</form><br />'.$grading_menu_button);
 8058:     return;
 8059: }
 8060: 
 8061: sub verify_scantron_grading {
 8062:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
 8063:         $scantron_config,$lettdig,$numletts) = @_;
 8064:     my ($record,%expected,%startpos);
 8065:     return ($counter,$record) if (!ref($resource));
 8066:     return ($counter,$record) if (!$resource->is_problem());
 8067:     my $symb = $resource->symb();
 8068:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
 8069:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
 8070:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8071:         $counter ++;
 8072:         $expected{$part_id} = 0;
 8073:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 8074:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 8075:             foreach my $item (@sub_lines) {
 8076:                 $expected{$part_id} += $item;
 8077:             }
 8078:         } else {
 8079:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 8080:         }
 8081:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 8082:     }
 8083:     if ($symb) {
 8084:         my %recorded;
 8085:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
 8086:         if ($returnhash{'version'}) {
 8087:             my %lasthash=();
 8088:             my $version;
 8089:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 8090:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 8091:                     $lasthash{$key}=$returnhash{$version.':'.$key};
 8092:                 }
 8093:             }
 8094:             foreach my $key (keys(%lasthash)) {
 8095:                 if ($key =~ /\.scantron$/) {
 8096:                     my $value = &unescape($lasthash{$key});
 8097:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 8098:                     if ($value eq '') {
 8099:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8100:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
 8101:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8102:                             }
 8103:                         }
 8104:                     } else {
 8105:                         my @tocheck;
 8106:                         my @items = split(//,$value);
 8107:                         if (($scantron_config->{'Qon'} eq 'letter') ||
 8108:                             ($scantron_config->{'Qon'} eq 'number')) {
 8109:                             if (@items < $expected{$part_id}) {
 8110:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
 8111:                                 my @singles = split(//,$fragment);
 8112:                                 foreach my $pos (@singles) {
 8113:                                     if ($pos eq ' ') {
 8114:                                         push(@tocheck,$pos);
 8115:                                     } else {
 8116:                                         my $next = shift(@items);
 8117:                                         push(@tocheck,$next);
 8118:                                     }
 8119:                                 }
 8120:                             } else {
 8121:                                 @tocheck = @items;
 8122:                             }
 8123:                             foreach my $letter (@tocheck) {
 8124:                                 if ($scantron_config->{'Qon'} eq 'letter') {
 8125:                                     if ($letter !~ /^[A-J]$/) {
 8126:                                         $letter = $scantron_config->{'Qoff'};
 8127:                                     }
 8128:                                     $recorded{$part_id} .= $letter;
 8129:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
 8130:                                     my $digit;
 8131:                                     if ($letter !~ /^[A-J]$/) {
 8132:                                         $digit = $scantron_config->{'Qoff'};
 8133:                                     } else {
 8134:                                         $digit = $lettdig->{$letter};
 8135:                                     }
 8136:                                     $recorded{$part_id} .= $digit;
 8137:                                 }
 8138:                             }
 8139:                         } else {
 8140:                             @tocheck = @items;
 8141:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
 8142:                                 my $curr_sub = shift(@tocheck);
 8143:                                 my $digit;
 8144:                                 if ($curr_sub =~ /^[A-J]$/) {
 8145:                                     $digit = $lettdig->{$curr_sub}-1;
 8146:                                 }
 8147:                                 if ($curr_sub eq 'J') {
 8148:                                     $digit += scalar($numletts);
 8149:                                 }
 8150:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8151:                                     if ($j == $digit) {
 8152:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
 8153:                                     } else {
 8154:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8155:                                     }
 8156:                                 }
 8157:                             }
 8158:                         }
 8159:                     }
 8160:                 }
 8161:             }
 8162:         }
 8163:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
 8164:             if ($recorded{$part_id} eq '') {
 8165:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 8166:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
 8167:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
 8168:                     }
 8169:                 }
 8170:             }
 8171:             $record .= $recorded{$part_id};
 8172:         }
 8173:     }
 8174:     return ($counter,$record);
 8175: }
 8176: 
 8177: sub letter_to_digits {
 8178:     my %lettdig = (
 8179:                     A => 1,
 8180:                     B => 2,
 8181:                     C => 3,
 8182:                     D => 4,
 8183:                     E => 5,
 8184:                     F => 6,
 8185:                     G => 7,
 8186:                     H => 8,
 8187:                     I => 9,
 8188:                     J => 0,
 8189:                   );
 8190:     return %lettdig;
 8191: }
 8192: 
 8193: =pod
 8194: 
 8195: =back
 8196: 
 8197: =cut
 8198: 
 8199: #-------- end of section for handling grading scantron forms -------
 8200: #
 8201: #-------------------------------------------------------------------
 8202: 
 8203: #-------------------------- Menu interface -------------------------
 8204: #
 8205: #--- Show a Grading Menu button - Calls the next routine ---
 8206: sub show_grading_menu_form {
 8207:     my ($symb)=@_;
 8208:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8209: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8210: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8211: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8212: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8213: 	'</form>'."\n";
 8214:     return $result;
 8215: }
 8216: 
 8217: # -- Retrieve choices for grading form
 8218: sub savedState {
 8219:     my %savedState = ();
 8220:     if ($env{'form.saveState'}) {
 8221: 	foreach (split(/:/,$env{'form.saveState'})) {
 8222: 	    my ($key,$value) = split(/=/,$_,2);
 8223: 	    $savedState{$key} = $value;
 8224: 	}
 8225:     }
 8226:     return \%savedState;
 8227: }
 8228: 
 8229: sub grading_menu {
 8230:     my ($request) = @_;
 8231:     my ($symb)=&get_symb($request);
 8232:     if (!$symb) {return '';}
 8233:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8234:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8235: 
 8236:     $request->print($table);
 8237:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8238:                   'handgrade'=>$hdgrade,
 8239:                   'probTitle'=>$probTitle,
 8240:                   'command'=>'submit_options',
 8241:                   'saveState'=>"",
 8242:                   'gradingMenu'=>1,
 8243:                   'showgrading'=>"yes");
 8244:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8245:     my @menu = ({ url => $url,
 8246:                      name => &mt('Manual Grading/View Submissions'),
 8247:                      short_description => 
 8248:     &mt('Start the process of hand grading submissions.'),
 8249:                  });
 8250:     $fields{'command'} = 'csvform';
 8251:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8252:     push(@menu, { url => $url,
 8253:                    name => &mt('Upload Scores'),
 8254:                    short_description => 
 8255:             &mt('Specify a file containing the class scores for current resource.')});
 8256:     $fields{'command'} = 'processclicker';
 8257:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8258:     push(@menu, { url => $url,
 8259:                    name => &mt('Process Clicker'),
 8260:                    short_description => 
 8261:             &mt('Specify a file containing the clicker information for this resource.')});
 8262:     $fields{'command'} = 'scantron_selectphase';
 8263:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8264:     push(@menu, { url => $url,
 8265:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8266:                    short_description => 
 8267:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8268:     $fields{'command'} = 'verify';
 8269:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8270:     push(@menu, { url => "",
 8271:                    name => &mt('Verify Receipt'),
 8272:                    short_description => 
 8273:             &mt('')});
 8274:     #
 8275:     # Create the menu
 8276:     my $Str;
 8277:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8278:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8279:     $Str .= '<input type="hidden" name="command" value="" />'.
 8280:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8281: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8282: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8283: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8284: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8285: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8286: 
 8287:     foreach my $menudata (@menu) {
 8288:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8289:             $Str .='    <h3><a '.
 8290:                 $menudata->{'jscript'}.
 8291:                 ' href="'.
 8292:                 $menudata->{'url'}.'" >'.
 8293:                 $menudata->{'name'}."</a></h3>\n";
 8294:         } else {
 8295:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8296:                 $menudata->{'jscript'}.
 8297:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8298:                 ' /> '.
 8299: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8300:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8301:         }
 8302:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8303:             "\n";
 8304:     }
 8305:     $Str .="</form>\n";
 8306:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
 8307:     $request->print(<<GRADINGMENUJS);
 8308: <script type="text/javascript" language="javascript">
 8309:     function checkChoice(formname,val,cmdx) {
 8310: 	if (val <= 2) {
 8311: 	    var cmd = radioSelection(formname.radioChoice);
 8312: 	    var cmdsave = cmd;
 8313: 	} else {
 8314: 	    cmd = cmdx;
 8315: 	    cmdsave = 'submission';
 8316: 	}
 8317: 	formname.command.value = cmd;
 8318: 	if (val < 5) formname.submit();
 8319: 	if (val == 5) {
 8320: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8321: 	        return false;
 8322: 	    } else {
 8323: 	        formname.submit();
 8324: 	    }
 8325: 	}
 8326:     }
 8327: 
 8328:     function checkReceiptNo(formname,nospace) {
 8329: 	var receiptNo = formname.receipt.value;
 8330: 	var checkOpt = false;
 8331: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8332: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8333: 	if (checkOpt) {
 8334: 	    alert("$receiptalert$receiptalert");
 8335: 	    formname.receipt.value = "";
 8336: 	    formname.receipt.focus();
 8337: 	    return false;
 8338: 	}
 8339: 	return true;
 8340:     }
 8341: </script>
 8342: GRADINGMENUJS
 8343:     &commonJSfunctions($request);
 8344:     return $Str;    
 8345: }
 8346: 
 8347: 
 8348: #--- Displays the submissions first page -------
 8349: sub submit_options {
 8350:     my ($request) = @_;
 8351:     my ($symb)=&get_symb($request);
 8352:     if (!$symb) {return '';}
 8353:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8354: 
 8355:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
 8356:     $request->print(<<GRADINGMENUJS);
 8357: <script type="text/javascript" language="javascript">
 8358:     function checkChoice(formname,val,cmdx) {
 8359: 	if (val <= 2) {
 8360: 	    var cmd = radioSelection(formname.radioChoice);
 8361: 	    var cmdsave = cmd;
 8362: 	} else {
 8363: 	    cmd = cmdx;
 8364: 	    cmdsave = 'submission';
 8365: 	}
 8366: 	formname.command.value = cmd;
 8367: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8368: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8369: 	if (val < 5) formname.submit();
 8370: 	if (val == 5) {
 8371: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8372: 	    formname.submit();
 8373: 	}
 8374: 	if (val < 7) formname.submit();
 8375:     }
 8376: 
 8377:     function checkReceiptNo(formname,nospace) {
 8378: 	var receiptNo = formname.receipt.value;
 8379: 	var checkOpt = false;
 8380: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8381: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8382: 	if (checkOpt) {
 8383: 	    alert("$receiptalert");
 8384: 	    formname.receipt.value = "";
 8385: 	    formname.receipt.focus();
 8386: 	    return false;
 8387: 	}
 8388: 	return true;
 8389:     }
 8390: </script>
 8391: GRADINGMENUJS
 8392:     &commonJSfunctions($request);
 8393:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8394:     my $result;
 8395:     my (undef,$sections) = &getclasslist('all','0');
 8396:     my $savedState = &savedState();
 8397:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8398:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8399:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8400:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8401: 
 8402:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8403: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8404: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8405: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8406: 	'<input type="hidden" name="command"     value="" />'."\n".
 8407: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8408: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8409: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8410: 
 8411:     $result.='
 8412:     <div class="LC_grade_select_mode">
 8413:       <div class="LC_grade_select_mode_current">
 8414:         <h2>
 8415:           '.&mt('Grade Current Resource').'
 8416:         </h2>
 8417:         <div class="LC_grade_select_mode_body">
 8418:           <div class="LC_grades_resource_info">
 8419:            '.$table.'
 8420:           </div>
 8421:           <div class="LC_grade_select_mode_selector">
 8422:              <div class="LC_grade_select_mode_selector_header">
 8423:                 '.&mt('Sections').'
 8424:              </div>
 8425:              <div class="LC_grade_select_mode_selector_body">
 8426: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8427:     if (ref($sections)) {
 8428: 	foreach my $section (sort(@$sections)) {
 8429: 	    $result.='<option value="'.$section.'" '.
 8430: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8431: 	}
 8432:     }
 8433:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8434:     $result.='
 8435:              </div>
 8436:           </div>
 8437:           <div class="LC_grade_select_mode_selector">
 8438:              <div class="LC_grade_select_mode_selector_header">
 8439:                 '.&mt('Groups').'
 8440:              </div>
 8441:              <div class="LC_grade_select_mode_selector_body">
 8442:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8443:              </div>
 8444:           </div>
 8445:           <div class="LC_grade_select_mode_selector">
 8446:              <div class="LC_grade_select_mode_selector_header">
 8447:                 '.&mt('Access Status').'
 8448:              </div>
 8449:              <div class="LC_grade_select_mode_selector_body">
 8450:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8451:              </div>
 8452:           </div>
 8453:           <div class="LC_grade_select_mode_selector">
 8454:              <div class="LC_grade_select_mode_selector_header">
 8455:                 '.&mt('Submission Status').'
 8456:              </div>
 8457:              <div class="LC_grade_select_mode_selector_body">
 8458:                <select name="submitonly" size="5">
 8459: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8460: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8461: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8462: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8463:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8464:                </select>
 8465:              </div>
 8466:           </div>
 8467:           <div class="LC_grade_select_mode_type_body">
 8468:             <div class="LC_grade_select_mode_type">
 8469:               <label>
 8470:                 <input type="radio" name="radioChoice" value="submission" '.
 8471:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8472:              &mt('Select individual students to grade and view submissions.').'
 8473: 	      </label> 
 8474:             </div>
 8475:             <div class="LC_grade_select_mode_type">
 8476: 	      <label>
 8477:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8478:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8479:                     &mt('Grade all selected students in a grading table.').'
 8480:               </label>
 8481:             </div>
 8482:             <div class="LC_grade_select_mode_type">
 8483: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8484:             </div>
 8485:           </div>
 8486:         </div>
 8487:       </div>
 8488:       <div class="LC_grade_select_mode_page">
 8489:         <h2>
 8490:          '.&mt('Grade Complete Folder for One Student').'
 8491:         </h2>
 8492:         <div class="LC_grades_select_mode_body">
 8493:           <div class="LC_grade_select_mode_type_body">
 8494:             <div class="LC_grade_select_mode_type">
 8495:               <label>
 8496:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8497: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8498:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8499:               </label>
 8500:             </div>
 8501:             <div class="LC_grade_select_mode_type">
 8502: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
 8503:             </div>
 8504:           </div>
 8505:         </div>
 8506:       </div>
 8507:     </div>
 8508:   </form>';
 8509:     $result .= &show_grading_menu_form($symb);
 8510:     return $result;
 8511: }
 8512: 
 8513: sub reset_perm {
 8514:     undef(%perm);
 8515: }
 8516: 
 8517: sub init_perm {
 8518:     &reset_perm();
 8519:     foreach my $test_perm ('vgr','mgr','opa') {
 8520: 
 8521: 	my $scope = $env{'request.course.id'};
 8522: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8523: 
 8524: 	    $scope .= '/'.$env{'request.course.sec'};
 8525: 	    if ( $perm{$test_perm}=
 8526: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8527: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8528: 	    } else {
 8529: 		delete($perm{$test_perm});
 8530: 	    }
 8531: 	}
 8532:     }
 8533: }
 8534: 
 8535: sub gather_clicker_ids {
 8536:     my %clicker_ids;
 8537: 
 8538:     my $classlist = &Apache::loncoursedata::get_classlist();
 8539: 
 8540:     # Set up a couple variables.
 8541:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8542:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8543:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8544: 
 8545:     foreach my $student (keys(%$classlist)) {
 8546:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8547:         my $username = $classlist->{$student}->[$username_idx];
 8548:         my $domain   = $classlist->{$student}->[$domain_idx];
 8549:         my $clickers =
 8550: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8551:         foreach my $id (split(/\,/,$clickers)) {
 8552:             $id=~s/^[\#0]+//;
 8553:             $id=~s/[\-\:]//g;
 8554:             if (exists($clicker_ids{$id})) {
 8555: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8556:             } else {
 8557: 		$clicker_ids{$id}=$username.':'.$domain;
 8558:             }
 8559:         }
 8560:     }
 8561:     return %clicker_ids;
 8562: }
 8563: 
 8564: sub gather_adv_clicker_ids {
 8565:     my %clicker_ids;
 8566:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8567:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8568:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8569:     foreach my $element (sort(keys(%coursepersonnel))) {
 8570:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8571:             my ($puname,$pudom)=split(/\:/,$person);
 8572:             my $clickers =
 8573: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8574:             foreach my $id (split(/\,/,$clickers)) {
 8575: 		$id=~s/^[\#0]+//;
 8576:                 $id=~s/[\-\:]//g;
 8577: 		if (exists($clicker_ids{$id})) {
 8578: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8579: 		} else {
 8580: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8581: 		}
 8582:             }
 8583:         }
 8584:     }
 8585:     return %clicker_ids;
 8586: }
 8587: 
 8588: sub clicker_grading_parameters {
 8589:     return ('gradingmechanism' => 'scalar',
 8590:             'upfiletype' => 'scalar',
 8591:             'specificid' => 'scalar',
 8592:             'pcorrect' => 'scalar',
 8593:             'pincorrect' => 'scalar');
 8594: }
 8595: 
 8596: sub process_clicker {
 8597:     my ($r)=@_;
 8598:     my ($symb)=&get_symb($r);
 8599:     if (!$symb) {return '';}
 8600:     my $result=&checkforfile_js();
 8601:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8602:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8603:     $result.=$table;
 8604:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8605:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8606:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
 8607:         '.</b></td></tr>'."\n";
 8608:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8609: # Attempt to restore parameters from last session, set defaults if not present
 8610:     my %Saveable_Parameters=&clicker_grading_parameters();
 8611:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8612:                                                  \%Saveable_Parameters);
 8613:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8614:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8615:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8616:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8617: 
 8618:     my %checked;
 8619:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8620:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8621:           $checked{$gradingmechanism}="checked='checked'";
 8622:        }
 8623:     }
 8624: 
 8625:     my $upload=&mt("Upload File");
 8626:     my $type=&mt("Type");
 8627:     my $attendance=&mt("Award points just for participation");
 8628:     my $personnel=&mt("Correctness determined from response by course personnel");
 8629:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8630:     my $given=&mt("Correctness determined from given list of answers").' '.
 8631:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8632:     my $pcorrect=&mt("Percentage points for correct solution");
 8633:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8634:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8635: 						   ('iclicker' => 'i>clicker',
 8636:                                                     'interwrite' => 'interwrite PRS'));
 8637:     $symb = &Apache::lonenc::check_encrypt($symb);
 8638:     $result.=<<ENDUPFORM;
 8639: <script type="text/javascript">
 8640: function sanitycheck() {
 8641: // Accept only integer percentages
 8642:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8643:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8644: // Find out grading choice
 8645:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8646:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8647:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8648:       }
 8649:    }
 8650: // By default, new choice equals user selection
 8651:    newgradingchoice=gradingchoice;
 8652: // Not good to give more points for false answers than correct ones
 8653:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8654:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8655:    }
 8656: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8657:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8658:       document.forms.gradesupload.pcorrect.value=100;
 8659:       document.forms.gradesupload.pincorrect.value=100;
 8660:    }
 8661: // If the values are different, cannot be attendance only
 8662:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8663:        (gradingchoice=='attendance')) {
 8664:        newgradingchoice='personnel';
 8665:    }
 8666: // Change grading choice to new one
 8667:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8668:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8669:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8670:       } else {
 8671:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8672:       }
 8673:    }
 8674: // Remember the old state
 8675:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8676: }
 8677: </script>
 8678: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8679: <input type="hidden" name="symb" value="$symb" />
 8680: <input type="hidden" name="command" value="processclickerfile" />
 8681: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8682: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8683: <input type="file" name="upfile" size="50" />
 8684: <br /><label>$type: $selectform</label>
 8685: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8686: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8687: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8688: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8689: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8690: <br />&nbsp;&nbsp;&nbsp;
 8691: <input type="text" name="givenanswer" size="50" />
 8692: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8693: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8694: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8695: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8696: </form>
 8697: ENDUPFORM
 8698:     $result.='</td></tr></table>'."\n".
 8699:              '</td></tr></table><br /><br />'."\n";
 8700:     $result.=&show_grading_menu_form($symb);
 8701:     return $result;
 8702: }
 8703: 
 8704: sub process_clicker_file {
 8705:     my ($r)=@_;
 8706:     my ($symb)=&get_symb($r);
 8707:     if (!$symb) {return '';}
 8708: 
 8709:     my %Saveable_Parameters=&clicker_grading_parameters();
 8710:     &Apache::loncommon::store_course_settings('grades_clicker',
 8711:                                               \%Saveable_Parameters);
 8712: 
 8713:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8714:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8715: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8716: 	return $result.&show_grading_menu_form($symb);
 8717:     }
 8718:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8719:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8720:         return $result.&show_grading_menu_form($symb);
 8721:     }
 8722:     my $foundgiven=0;
 8723:     if ($env{'form.gradingmechanism'} eq 'given') {
 8724:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8725:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8726:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8727:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8728:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8729:         $foundgiven=$#answers+1;
 8730:     }
 8731:     my %clicker_ids=&gather_clicker_ids();
 8732:     my %correct_ids;
 8733:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8734: 	%correct_ids=&gather_adv_clicker_ids();
 8735:     }
 8736:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8737: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8738: 	   $correct_id=~tr/a-z/A-Z/;
 8739: 	   $correct_id=~s/\s//gs;
 8740: 	   $correct_id=~s/^[\#0]+//;
 8741:            $correct_id=~s/[\-\:]//g;
 8742:            if ($correct_id) {
 8743: 	      $correct_ids{$correct_id}='specified';
 8744:            }
 8745:         }
 8746:     }
 8747:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8748: 	$result.=&mt('Score based on attendance only');
 8749:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8750:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8751:     } else {
 8752: 	my $number=0;
 8753: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8754: 	foreach my $id (sort(keys(%correct_ids))) {
 8755: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8756: 	    if ($correct_ids{$id} eq 'specified') {
 8757: 		$result.=&mt('specified');
 8758: 	    } else {
 8759: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8760: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8761: 	    }
 8762: 	    $number++;
 8763: 	}
 8764:         $result.="</p>\n";
 8765: 	if ($number==0) {
 8766: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8767: 	    return $result.&show_grading_menu_form($symb);
 8768: 	}
 8769:     }
 8770:     if (length($env{'form.upfile'}) < 2) {
 8771:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8772: 		     '<span class="LC_error">',
 8773: 		     '</span>',
 8774: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8775:         return $result.&show_grading_menu_form($symb);
 8776:     }
 8777: 
 8778: # Were able to get all the info needed, now analyze the file
 8779: 
 8780:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8781:     $symb = &Apache::lonenc::check_encrypt($symb);
 8782:     my $heading=&mt('Scanning clicker file');
 8783:     $result.=(<<ENDHEADER);
 8784: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8785: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8786: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8787: <form method="post" action="/adm/grades" name="clickeranalysis">
 8788: <input type="hidden" name="symb" value="$symb" />
 8789: <input type="hidden" name="command" value="assignclickergrades" />
 8790: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8791: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8792: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8793: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8794: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8795: ENDHEADER
 8796:     if ($env{'form.gradingmechanism'} eq 'given') {
 8797:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8798:     } 
 8799:     my %responses;
 8800:     my @questiontitles;
 8801:     my $errormsg='';
 8802:     my $number=0;
 8803:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8804: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8805:     }
 8806:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8807:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8808:     }
 8809:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8810:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8811:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8812:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8813:              '<br />';
 8814:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8815:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8816:        return $result.&show_grading_menu_form($symb);
 8817:     } 
 8818: # Remember Question Titles
 8819: # FIXME: Possibly need delimiter other than ":"
 8820:     for (my $i=0;$i<$number;$i++) {
 8821:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8822:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8823:     }
 8824:     my $correct_count=0;
 8825:     my $student_count=0;
 8826:     my $unknown_count=0;
 8827: # Match answers with usernames
 8828: # FIXME: Possibly need delimiter other than ":"
 8829:     foreach my $id (keys(%responses)) {
 8830:        if ($correct_ids{$id}) {
 8831:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8832:           $correct_count++;
 8833:        } elsif ($clicker_ids{$id}) {
 8834:           if ($clicker_ids{$id}=~/\,/) {
 8835: # More than one user with the same clicker!
 8836:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8837:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8838:                            "<select name='multi".$id."'>";
 8839:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8840:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8841:              }
 8842:              $result.='</select>';
 8843:              $unknown_count++;
 8844:           } else {
 8845: # Good: found one and only one user with the right clicker
 8846:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8847:              $student_count++;
 8848:           }
 8849:        } else {
 8850:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8851:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8852:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8853:                    "\n".&mt("Domain").": ".
 8854:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8855:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8856:           $unknown_count++;
 8857:        }
 8858:     }
 8859:     $result.='<hr />'.
 8860:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8861:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8862:        if ($correct_count==0) {
 8863:           $errormsg.="Found no correct answers answers for grading!";
 8864:        } elsif ($correct_count>1) {
 8865:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8866:        }
 8867:     }
 8868:     if ($number<1) {
 8869:        $errormsg.="Found no questions.";
 8870:     }
 8871:     if ($errormsg) {
 8872:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8873:     } else {
 8874:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8875:     }
 8876:     $result.='</form></td></tr></table>'."\n".
 8877:              '</td></tr></table><br /><br />'."\n";
 8878:     return $result.&show_grading_menu_form($symb);
 8879: }
 8880: 
 8881: sub iclicker_eval {
 8882:     my ($questiontitles,$responses)=@_;
 8883:     my $number=0;
 8884:     my $errormsg='';
 8885:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8886:         my %components=&Apache::loncommon::record_sep($line);
 8887:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8888: 	if ($entries[0] eq 'Question') {
 8889: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8890: 		$$questiontitles[$number]=$entries[$i];
 8891: 		$number++;
 8892: 	    }
 8893: 	}
 8894: 	if ($entries[0]=~/^\#/) {
 8895: 	    my $id=$entries[0];
 8896: 	    my @idresponses;
 8897: 	    $id=~s/^[\#0]+//;
 8898: 	    for (my $i=0;$i<$number;$i++) {
 8899: 		my $idx=3+$i*6;
 8900: 		push(@idresponses,$entries[$idx]);
 8901: 	    }
 8902: 	    $$responses{$id}=join(',',@idresponses);
 8903: 	}
 8904:     }
 8905:     return ($errormsg,$number);
 8906: }
 8907: 
 8908: sub interwrite_eval {
 8909:     my ($questiontitles,$responses)=@_;
 8910:     my $number=0;
 8911:     my $errormsg='';
 8912:     my $skipline=1;
 8913:     my $questionnumber=0;
 8914:     my %idresponses=();
 8915:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8916:         my %components=&Apache::loncommon::record_sep($line);
 8917:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8918:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8919:         if ($entries[1] eq 'Response') { $skipline=1; }
 8920:         next if $skipline;
 8921:         if ($entries[0]!=$questionnumber) {
 8922:            $questionnumber=$entries[0];
 8923:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8924:            $number++;
 8925:         }
 8926:         my $id=$entries[4];
 8927:         $id=~s/^[\#0]+//;
 8928:         $id=~s/^v\d*\://i;
 8929:         $id=~s/[\-\:]//g;
 8930:         $idresponses{$id}[$number]=$entries[6];
 8931:     }
 8932:     foreach my $id (keys(%idresponses)) {
 8933:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8934:        $$responses{$id}=~s/^\s*\,//;
 8935:     }
 8936:     return ($errormsg,$number);
 8937: }
 8938: 
 8939: sub assign_clicker_grades {
 8940:     my ($r)=@_;
 8941:     my ($symb)=&get_symb($r);
 8942:     if (!$symb) {return '';}
 8943: # See which part we are saving to
 8944:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8945: # FIXME: This should probably look for the first handgradeable part
 8946:     my $part=$$partlist[0];
 8947: # Start screen output
 8948:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8949: 
 8950:     my $heading=&mt('Assigning grades based on clicker file');
 8951:     $result.=(<<ENDHEADER);
 8952: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8953: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8954: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8955: ENDHEADER
 8956: # Get correct result
 8957: # FIXME: Possibly need delimiter other than ":"
 8958:     my @correct=();
 8959:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8960:     my $number=$env{'form.number'};
 8961:     if ($gradingmechanism ne 'attendance') {
 8962:        foreach my $key (keys(%env)) {
 8963:           if ($key=~/^form\.correct\:/) {
 8964:              my @input=split(/\,/,$env{$key});
 8965:              for (my $i=0;$i<=$#input;$i++) {
 8966:                  if (($correct[$i]) && ($input[$i]) &&
 8967:                      ($correct[$i] ne $input[$i])) {
 8968:                     $result.='<br /><span class="LC_warning">'.
 8969:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8970:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8971:                  } elsif ($input[$i]) {
 8972:                     $correct[$i]=$input[$i];
 8973:                  }
 8974:              }
 8975:           }
 8976:        }
 8977:        for (my $i=0;$i<$number;$i++) {
 8978:           if (!$correct[$i]) {
 8979:              $result.='<br /><span class="LC_error">'.
 8980:                       &mt('No correct result given for question "[_1]"!',
 8981:                           $env{'form.question:'.$i}).'</span>';
 8982:           }
 8983:        }
 8984:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8985:     }
 8986: # Start grading
 8987:     my $pcorrect=$env{'form.pcorrect'};
 8988:     my $pincorrect=$env{'form.pincorrect'};
 8989:     my $storecount=0;
 8990:     foreach my $key (keys(%env)) {
 8991:        my $user='';
 8992:        if ($key=~/^form\.student\:(.*)$/) {
 8993:           $user=$1;
 8994:        }
 8995:        if ($key=~/^form\.unknown\:(.*)$/) {
 8996:           my $id=$1;
 8997:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8998:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8999:           } elsif ($env{'form.multi'.$id}) {
 9000:              $user=$env{'form.multi'.$id};
 9001:           }
 9002:        }
 9003:        if ($user) { 
 9004:           my @answer=split(/\,/,$env{$key});
 9005:           my $sum=0;
 9006:           my $realnumber=$number;
 9007:           for (my $i=0;$i<$number;$i++) {
 9008:              if ($answer[$i]) {
 9009:                 if ($gradingmechanism eq 'attendance') {
 9010:                    $sum+=$pcorrect;
 9011:                 } elsif ($answer[$i] eq '*') {
 9012:                    $sum+=$pcorrect;
 9013:                 } elsif ($answer[$i] eq '-') {
 9014:                    $realnumber--;
 9015:                 } else {
 9016:                    if ($answer[$i] eq $correct[$i]) {
 9017:                       $sum+=$pcorrect;
 9018:                    } else {
 9019:                       $sum+=$pincorrect;
 9020:                    }
 9021:                 }
 9022:              }
 9023:           }
 9024:           my $ave=$sum/(100*$realnumber);
 9025: # Store
 9026:           my ($username,$domain)=split(/\:/,$user);
 9027:           my %grades=();
 9028:           $grades{"resource.$part.solved"}='correct_by_override';
 9029:           $grades{"resource.$part.awarded"}=$ave;
 9030:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 9031:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 9032:                                                  $env{'request.course.id'},
 9033:                                                  $domain,$username);
 9034:           if ($returncode ne 'ok') {
 9035:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 9036:           } else {
 9037:              $storecount++;
 9038:           }
 9039:        }
 9040:     }
 9041: # We are done
 9042:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
 9043:              '</td></tr></table>'."\n".
 9044:              '</td></tr></table><br /><br />'."\n";
 9045:     return $result.&show_grading_menu_form($symb);
 9046: }
 9047: 
 9048: sub handler {
 9049:     my $request=$_[0];
 9050:     &reset_caches();
 9051:     if ($env{'browser.mathml'}) {
 9052: 	&Apache::loncommon::content_type($request,'text/xml');
 9053:     } else {
 9054: 	&Apache::loncommon::content_type($request,'text/html');
 9055:     }
 9056:     $request->send_http_header;
 9057:     return '' if $request->header_only;
 9058:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 9059:     my $symb=&get_symb($request,1);
 9060:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 9061:     my $command=$commands[0];
 9062: 
 9063:     if ($#commands > 0) {
 9064: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 9065:     }
 9066: 
 9067:     $ssi_error = 0;
 9068:     $request->print(&Apache::loncommon::start_page('Grading'));
 9069:     if ($symb eq '' && $command eq '') {
 9070: 	if ($env{'user.adv'}) {
 9071: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 9072: 		($env{'form.codethree'})) {
 9073: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9074: 		    $env{'form.codethree'};
 9075: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9076: 		    &Apache::lonnet::checkin($token);
 9077: 		if ($tsymb) {
 9078: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9079: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9080: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9081: 					  ('grade_username' => $tuname,
 9082: 					   'grade_domain' => $tudom,
 9083: 					   'grade_courseid' => $tcrsid,
 9084: 					   'grade_symb' => $tsymb)));
 9085: 		    } else {
 9086: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9087: 		    }
 9088: 		} else {
 9089: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9090: 		}
 9091: 	    } else {
 9092: 		$request->print(&Apache::lonxml::tokeninputfield());
 9093: 	    }
 9094: 	}
 9095:     } else {
 9096: 	&init_perm();
 9097: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9098: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9099: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9100: 	    &pickStudentPage($request);
 9101: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9102: 	    &displayPage($request);
 9103: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9104: 	    &updateGradeByPage($request);
 9105: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9106: 	    &processGroup($request);
 9107: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9108: 	    $request->print(&grading_menu($request));
 9109: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9110: 	    $request->print(&submit_options($request));
 9111: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9112: 	    $request->print(&viewgrades($request));
 9113: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9114: 	    $request->print(&processHandGrade($request));
 9115: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9116: 	    $request->print(&editgrades($request));
 9117: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9118: 	    $request->print(&verifyreceipt($request));
 9119:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9120:             $request->print(&process_clicker($request));
 9121:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9122:             $request->print(&process_clicker_file($request));
 9123:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9124:             $request->print(&assign_clicker_grades($request));
 9125: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9126: 	    $request->print(&upcsvScores_form($request));
 9127: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9128: 	    $request->print(&csvupload($request));
 9129: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9130: 	    $request->print(&csvuploadmap($request));
 9131: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9132: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9133: 		$request->print(&csvuploadoptions($request));
 9134: 	    } else {
 9135: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9136: 		    $env{'form.upfile_associate'} = 'reverse';
 9137: 		} else {
 9138: 		    $env{'form.upfile_associate'} = 'forward';
 9139: 		}
 9140: 		$request->print(&csvuploadmap($request));
 9141: 	    }
 9142: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9143: 	    $request->print(&csvuploadassign($request));
 9144: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9145: 	    $request->print(&scantron_selectphase($request));
 9146:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9147:  	    $request->print(&scantron_do_warning($request));
 9148: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9149: 	    $request->print(&scantron_validate_file($request));
 9150: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9151: 	    $request->print(&scantron_process_students($request));
 9152:  	} elsif ($command eq 'scantronupload' && 
 9153:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9154: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9155:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9156:  	} elsif ($command eq 'scantronupload_save' &&
 9157:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9158: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9159:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9160:  	} elsif ($command eq 'scantron_download' &&
 9161: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9162:  	    $request->print(&scantron_download_scantron_data($request));
 9163:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9164:             $request->print(&checkscantron_results($request));     
 9165: 	} elsif ($command) {
 9166: 	    $request->print("Access Denied ($command)");
 9167: 	}
 9168:     }
 9169:     if ($ssi_error) {
 9170: 	&ssi_print_error($request);
 9171:     }
 9172:     $request->print(&Apache::loncommon::end_page());
 9173:     &reset_caches();
 9174:     return '';
 9175: }
 9176: 
 9177: 1;
 9178: 
 9179: __END__;

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