File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.530: download - view: text, annotated - select for diffs
Tue Nov 18 19:14:28 2008 UTC (15 years, 5 months ago) by jms
Branches: MAIN
CVS tags: HEAD
Added/updated/converted POD. Many files had their POD redone to new standards.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.530 2008/11/18 19:14:28 jms 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: =head1 NAME
   30: 
   31: Apache::grades
   32: 
   33: =head1 SYNOPSIS
   34: 
   35: Handles the viewing of grades.
   36: 
   37: This is part of the LearningOnline Network with CAPA project
   38: described at http://www.lon-capa.org.
   39: 
   40: =head1 OVERVIEW
   41: 
   42: Do an ssi with retries:
   43: While I'd love to factor out this with the vesrion in lonprintout,
   44: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
   45: I'm not quite ready to invent (e.g. an ssi_with_retry object).
   46: 
   47: At least the logic that drives this has been pulled out into loncommon.
   48: 
   49: 
   50: 
   51: ssi_with_retries - Does the server side include of a resource.
   52:                      if the ssi call returns an error we'll retry it up to
   53:                      the number of times requested by the caller.
   54:                      If we still have a proble, no text is appended to the
   55:                      output and we set some global variables.
   56:                      to indicate to the caller an SSI error occurred.  
   57:                      All of this is supposed to deal with the issues described
   58:                      in LonCAPA BZ 5631 see:
   59:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
   60:                      by informing the user that this happened.
   61: 
   62: Parameters:
   63:   resource   - The resource to include.  This is passed directly, without
   64:                interpretation to lonnet::ssi.
   65:   form       - The form hash parameters that guide the interpretation of the resource
   66:                
   67:   retries    - Number of retries allowed before giving up completely.
   68: Returns:
   69:   On success, returns the rendered resource identified by the resource parameter.
   70: Side Effects:
   71:   The following global variables can be set:
   72:    ssi_error                - If an unrecoverable error occurred this becomes true.
   73:                               It is up to the caller to initialize this to false
   74:                               if desired.
   75:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
   76:                               of the resource that could not be rendered by the ssi
   77:                               call.
   78:    ssi_error_message   - The error string fetched from the ssi response
   79:                               in the event of an error.
   80: 
   81: 
   82: =head1 HANDLER SUBROUTINE
   83: 
   84: ssi_with_retries()
   85: 
   86: =head1 SUBROUTINES
   87: 
   88: =over
   89: 
   90: =item scantron_get_correction() : 
   91: 
   92:    Builds the interface screen to interact with the operator to fix a
   93:    specific error condition in a specific scanline
   94: 
   95:  Arguments:
   96:     $r           - Apache request object
   97:     $i           - number of the current scanline
   98:     $scan_record - hash ref as returned from &scantron_parse_scanline()
   99:     $scan_config - hash ref as returned from &get_scantron_config()
  100:     $line        - full contents of the current scanline
  101:     $error       - error condition, valid values are
  102:                    'incorrectCODE', 'duplicateCODE',
  103:                    'doublebubble', 'missingbubble',
  104:                    'duplicateID', 'incorrectID'
  105:     $arg         - extra information needed
  106:        For errors:
  107:          - duplicateID   - paper number that this studentID was seen before on
  108:          - duplicateCODE - array ref of the paper numbers this CODE was
  109:                            seen on before
  110:          - incorrectCODE - current incorrect CODE 
  111:          - doublebubble  - array ref of the bubble lines that have double
  112:                            bubble errors
  113:          - missingbubble - array ref of the bubble lines that have missing
  114:                            bubble errors
  115: 
  116: =item  scantron_get_maxbubble() : 
  117: 
  118:    Returns the maximum number of bubble lines that are expected to
  119:    occur. Does this by walking the selected sequence rendering the
  120:    resource and then checking &Apache::lonxml::get_problem_counter()
  121:    for what the current value of the problem counter is.
  122: 
  123:    Caches the results to $env{'form.scantron_maxbubble'},
  124:    $env{'form.scantron.bubble_lines.n'}, 
  125:    $env{'form.scantron.first_bubble_line.n'} and
  126:    $env{"form.scantron.sub_bubblelines.n"}
  127:    which are the total number of bubble, lines, the number of bubble
  128:    lines for response n and number of the first bubble line for response n,
  129:    and a comma separated list of numbers of bubble lines for sub-questions
  130:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
  131: 
  132: 
  133: =item  scantron_validate_missingbubbles() : 
  134: 
  135:    Validates all scanlines in the selected file to not have any
  136:     answers that don't have bubbles that have not been verified
  137:     to be bubble free.
  138: 
  139: =item  scantron_process_students() : 
  140: 
  141:    Routine that does the actual grading of the bubble sheet information.
  142: 
  143:    The parsed scanline hash is added to %env 
  144: 
  145:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
  146:    foreach resource , with the form data of
  147: 
  148: 	'submitted'     =>'scantron' 
  149: 	'grade_target'  =>'grade',
  150: 	'grade_username'=> username of student
  151: 	'grade_domain'  => domain of student
  152: 	'grade_courseid'=> of course
  153: 	'grade_symb'    => symb of resource to grade
  154: 
  155:     This triggers a grading pass. The problem grading code takes care
  156:     of converting the bubbled letter information (now in %env) into a
  157:     valid submission.
  158: 
  159: =item  scantron_upload_scantron_data() :
  160: 
  161:     Creates the screen for adding a new bubble sheet data file to a course.
  162: 
  163: =item  scantron_upload_scantron_data_save() : 
  164: 
  165:    Adds a provided bubble information data file to the course if user
  166:    has the correct privileges to do so. 
  167: 
  168: =item  valid_file() :
  169: 
  170:    Validates that the requested bubble data file exists in the course.
  171: 
  172: =item  scantron_download_scantron_data() : 
  173: 
  174:    Shows a list of the three internal files (original, corrected,
  175:    skipped) for a specific bubble sheet data file that exists in the
  176:    course.
  177: 
  178: =item  scantron_validate_ID() : 
  179: 
  180:    Validates all scanlines in the selected file to not have any
  181:    invalid or underspecified student IDs
  182: 
  183: =back
  184: 
  185: =cut
  186: 
  187: package Apache::grades;
  188: use strict;
  189: use Apache::style;
  190: use Apache::lonxml;
  191: use Apache::lonnet;
  192: use Apache::loncommon;
  193: use Apache::lonhtmlcommon;
  194: use Apache::lonnavmaps;
  195: use Apache::lonhomework;
  196: use Apache::lonpickcode;
  197: use Apache::loncoursedata;
  198: use Apache::lonmsg();
  199: use Apache::Constants qw(:common);
  200: use Apache::lonlocal;
  201: use Apache::lonenc;
  202: use String::Similarity;
  203: use LONCAPA;
  204: 
  205: use POSIX qw(floor);
  206: 
  207: 
  208: 
  209: my %perm=();
  210: 
  211: #  These variables are used to recover from ssi errors
  212: 
  213: my $ssi_retries = 5;
  214: my $ssi_error;
  215: my $ssi_error_resource;
  216: my $ssi_error_message;
  217: 
  218: 
  219: sub ssi_with_retries {
  220:     my ($resource, $retries, %form) = @_;
  221:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  222:     if ($response->is_error) {
  223: 	$ssi_error          = 1;
  224: 	$ssi_error_resource = $resource;
  225: 	$ssi_error_message  = $response->code . " " . $response->message;
  226:     }
  227: 
  228:     return $content;
  229: 
  230: }
  231: #
  232: #  Prodcuces an ssi retry failure error message to the user:
  233: #
  234: 
  235: sub ssi_print_error {
  236:     my ($r) = @_;
  237:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
  238:     $r->print('
  239: <br />
  240: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
  241: <p>
  242: '.&mt('Unable to retrieve a resource from a server:').'<br />
  243: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
  244: '.&mt('Error:').' '.$ssi_error_message.'
  245: </p>
  246: <p>'.
  247: &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 />'.
  248: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  249: '</p>');
  250:     return;
  251: }
  252: 
  253: #
  254: # --- Retrieve the parts from the metadata file.---
  255: sub getpartlist {
  256:     my ($symb) = @_;
  257: 
  258:     my $navmap   = Apache::lonnavmaps::navmap->new();
  259:     my $res      = $navmap->getBySymb($symb);
  260:     my $partlist = $res->parts();
  261:     my $url      = $res->src();
  262:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  263: 
  264:     my @stores;
  265:     foreach my $part (@{ $partlist }) {
  266: 	foreach my $key (@metakeys) {
  267: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  268: 	}
  269:     }
  270:     return @stores;
  271: }
  272: 
  273: # --- Get the symbolic name of a problem and the url
  274: sub get_symb {
  275:     my ($request,$silent) = @_;
  276:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  277:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  278:     if ($symb eq '') { 
  279: 	if (!$silent) {
  280: 	    $request->print("Unable to handle ambiguous references:$url:.");
  281: 	    return ();
  282: 	}
  283:     }
  284:     &Apache::lonenc::check_decrypt(\$symb);
  285:     return ($symb);
  286: }
  287: 
  288: #--- Format fullname, username:domain if different for display
  289: #--- Use anywhere where the student names are listed
  290: sub nameUserString {
  291:     my ($type,$fullname,$uname,$udom) = @_;
  292:     if ($type eq 'header') {
  293: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  294:     } else {
  295: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  296: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  297:     }
  298: }
  299: 
  300: #--- Get the partlist and the response type for a given problem. ---
  301: #--- Indicate if a response type is coded handgraded or not. ---
  302: sub response_type {
  303:     my ($symb) = shift;
  304: 
  305:     my $navmap = Apache::lonnavmaps::navmap->new();
  306:     my $res = $navmap->getBySymb($symb);
  307:     my $partlist = $res->parts();
  308:     my %vPart = 
  309: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  310:     my (%response_types,%handgrade);
  311:     foreach my $part (@{ $partlist }) {
  312: 	next if (%vPart && !exists($vPart{$part}));
  313: 
  314: 	my @types = $res->responseType($part);
  315: 	my @ids = $res->responseIds($part);
  316: 	for (my $i=0; $i < scalar(@ids); $i++) {
  317: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  318: 	    $handgrade{$part.'_'.$ids[$i]} = 
  319: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  320: 				     '.handgrade',$symb);
  321: 	}
  322:     }
  323:     return ($partlist,\%handgrade,\%response_types);
  324: }
  325: 
  326: sub flatten_responseType {
  327:     my ($responseType) = @_;
  328:     my @part_response_id =
  329: 	map { 
  330: 	    my $part = $_;
  331: 	    map {
  332: 		[$part,$_]
  333: 		} sort(keys(%{ $responseType->{$part} }));
  334: 	} sort(keys(%$responseType));
  335:     return @part_response_id;
  336: }
  337: 
  338: sub get_display_part {
  339:     my ($partID,$symb)=@_;
  340:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  341:     if (defined($display) and $display ne '') {
  342: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  343:     } else {
  344: 	$display=$partID;
  345:     }
  346:     return $display;
  347: }
  348: 
  349: #--- Show resource title
  350: #--- and parts and response type
  351: sub showResourceInfo {
  352:     my ($symb,$probTitle,$checkboxes) = @_;
  353:     my $col=3;
  354:     if ($checkboxes) { $col=4; }
  355:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  356:     $result .='<table border="0">';
  357:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  358:     my %resptype = ();
  359:     my $hdgrade='no';
  360:     my %partsseen;
  361:     foreach my $partID (sort(keys(%$responseType))) {
  362: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  363: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  364: 	    my $responsetype = $responseType->{$partID}->{$resID};
  365: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  366: 	    $result.='<tr>';
  367: 	    if ($checkboxes) {
  368: 		if (exists($partsseen{$partID})) {
  369: 		    $result.="<td>&nbsp;</td>";
  370: 		} else {
  371: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  372: 		}
  373: 		$partsseen{$partID}=1;
  374: 	    }
  375: 	    my $display_part=&get_display_part($partID,$symb);
  376: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
  377: 		$resID.'</span></td>'.
  378: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
  379: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  380: 	}
  381:     }
  382:     $result.='</table>'."\n";
  383:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  384: }
  385: 
  386: sub reset_caches {
  387:     &reset_analyze_cache();
  388:     &reset_perm();
  389: }
  390: 
  391: {
  392:     my %analyze_cache;
  393: 
  394:     sub reset_analyze_cache {
  395: 	undef(%analyze_cache);
  396:     }
  397: 
  398:     sub get_analyze {
  399: 	my ($symb,$uname,$udom,$no_increment)=@_;
  400: 	my $key = "$symb\0$uname\0$udom";
  401: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  402: 
  403: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  404: 	$url=&Apache::lonnet::clutter($url);
  405: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  406: 					   ('grade_target' => 'analyze',
  407: 					    'grade_domain' => $udom,
  408: 					    'grade_symb' => $symb,
  409: 					    'grade_courseid' => 
  410: 					    $env{'request.course.id'},
  411: 					    'grade_username' => $uname,
  412:                                             'grade_noincrement' => $no_increment));
  413: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  414: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  415: 	return $analyze_cache{$key} = \%analyze;
  416:     }
  417: 
  418:     sub get_order {
  419: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  420: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  421: 	return $analyze->{"$partid.$respid.shown"};
  422:     }
  423: 
  424:     sub get_radiobutton_correct_foil {
  425: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  426: 	my $analyze = &get_analyze($symb,$uname,$udom);
  427: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  428: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  429: 		return $foil;
  430: 	    }
  431: 	}
  432:     }
  433: }
  434: 
  435: #--- Clean response type for display
  436: #--- Currently filters option/rank/radiobutton/match/essay/Task
  437: #        response types only.
  438: sub cleanRecord {
  439:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  440: 	$uname,$udom) = @_;
  441:     my $grayFont = '<span class="LC_internal_info">';
  442:     if ($response =~ /^(option|rank)$/) {
  443: 	my %answer=&Apache::lonnet::str2hash($answer);
  444: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  445: 	my ($toprow,$bottomrow);
  446: 	foreach my $foil (@$order) {
  447: 	    if ($grading{$foil} == 1) {
  448: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  449: 	    } else {
  450: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  451: 	    }
  452: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  453: 	}
  454: 	return '<blockquote><table border="1">'.
  455: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  456: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  457: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  458:     } elsif ($response eq 'match') {
  459: 	my %answer=&Apache::lonnet::str2hash($answer);
  460: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  461: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  462: 	my ($toprow,$middlerow,$bottomrow);
  463: 	foreach my $foil (@$order) {
  464: 	    my $item=shift(@items);
  465: 	    if ($grading{$foil} == 1) {
  466: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  467: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  468: 	    } else {
  469: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  470: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  471: 	    }
  472: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  473: 	}
  474: 	return '<blockquote><table border="1">'.
  475: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  476: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  477: 	    $middlerow.'</tr>'.
  478: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  479: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  480:     } elsif ($response eq 'radiobutton') {
  481: 	my %answer=&Apache::lonnet::str2hash($answer);
  482: 	my ($toprow,$bottomrow);
  483: 	my $correct = 
  484: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  485: 	foreach my $foil (@$order) {
  486: 	    if (exists($answer{$foil})) {
  487: 		if ($foil eq $correct) {
  488: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  489: 		} else {
  490: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  491: 		}
  492: 	    } else {
  493: 		$toprow.='<td>'.&mt('false').'</td>';
  494: 	    }
  495: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  496: 	}
  497: 	return '<blockquote><table border="1">'.
  498: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  499: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  500: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  501:     } elsif ($response eq 'essay') {
  502: 	if (! exists ($env{'form.'.$symb})) {
  503: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  504: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  505: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  506: 
  507: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  508: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  509: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  510: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  511: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  512: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  513: 	}
  514: 	$answer =~ s-\n-<br />-g;
  515: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  516:     } elsif ( $response eq 'organic') {
  517: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  518: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  519: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  520: 	return $result;
  521:     } elsif ( $response eq 'Task') {
  522: 	if ( $answer eq 'SUBMITTED') {
  523: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  524: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  525: 	    return $result;
  526: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  527: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  528: 			       keys(%{$record}));
  529: 	    return join('<br />',($version,@matches));
  530: 			       
  531: 			       
  532: 	} else {
  533: 	    my $result =
  534: 		'<p>'
  535: 		.&mt('Overall result: [_1]',
  536: 		     $record->{$version."resource.$respid.$partid.status"})
  537: 		.'</p>';
  538: 	    
  539: 	    $result .= '<ul>';
  540: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  541: 			     keys(%{$record}));
  542: 	    foreach my $grade (sort(@grade)) {
  543: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  544: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  545: 				     $dim, $record->{$grade}).
  546: 			  '</li>';
  547: 	    }
  548: 	    $result.='</ul>';
  549: 	    return $result;
  550: 	}
  551:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  552: 	$answer = 
  553: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  554: 							      $answer);
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: #-- A couple of common js functions
  560: sub commonJSfunctions {
  561:     my $request = shift;
  562:     $request->print(<<COMMONJSFUNCTIONS);
  563: <script type="text/javascript" language="javascript">
  564:     function radioSelection(radioButton) {
  565: 	var selection=null;
  566: 	if (radioButton.length > 1) {
  567: 	    for (var i=0; i<radioButton.length; i++) {
  568: 		if (radioButton[i].checked) {
  569: 		    return radioButton[i].value;
  570: 		}
  571: 	    }
  572: 	} else {
  573: 	    if (radioButton.checked) return radioButton.value;
  574: 	}
  575: 	return selection;
  576:     }
  577: 
  578:     function pullDownSelection(selectOne) {
  579: 	var selection="";
  580: 	if (selectOne.length > 1) {
  581: 	    for (var i=0; i<selectOne.length; i++) {
  582: 		if (selectOne[i].selected) {
  583: 		    return selectOne[i].value;
  584: 		}
  585: 	    }
  586: 	} else {
  587:             // only one value it must be the selected one
  588: 	    return selectOne.value;
  589: 	}
  590:     }
  591: </script>
  592: COMMONJSFUNCTIONS
  593: }
  594: 
  595: #--- Dumps the class list with usernames,list of sections,
  596: #--- section, ids and fullnames for each user.
  597: sub getclasslist {
  598:     my ($getsec,$filterlist,$getgroup) = @_;
  599:     my @getsec;
  600:     my @getgroup;
  601:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  602:     if (!ref($getsec)) {
  603: 	if ($getsec ne '' && $getsec ne 'all') {
  604: 	    @getsec=($getsec);
  605: 	}
  606:     } else {
  607: 	@getsec=@{$getsec};
  608:     }
  609:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  610:     if (!ref($getgroup)) {
  611: 	if ($getgroup ne '' && $getgroup ne 'all') {
  612: 	    @getgroup=($getgroup);
  613: 	}
  614:     } else {
  615: 	@getgroup=@{$getgroup};
  616:     }
  617:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  618: 
  619:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  620:     # Bail out if we were unable to get the classlist
  621:     return if (! defined($classlist));
  622:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  623:     #
  624:     my %sections;
  625:     my %fullnames;
  626:     foreach my $student (keys(%$classlist)) {
  627:         my $end      = 
  628:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  629:         my $start    = 
  630:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  631:         my $id       = 
  632:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  633:         my $section  = 
  634:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  635:         my $fullname = 
  636:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  637:         my $status   = 
  638:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  639:         my $group   = 
  640:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  641: 	# filter students according to status selected
  642: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  643: 	    if (!($stu_status =~ $status)) {
  644: 		delete($classlist->{$student});
  645: 		next;
  646: 	    }
  647: 	}
  648: 	# filter students according to groups selected
  649: 	my @stu_groups = split(/,/,$group);
  650: 	if (@getgroup) {
  651: 	    my $exclude = 1;
  652: 	    foreach my $grp (@getgroup) {
  653: 	        foreach my $stu_group (@stu_groups) {
  654: 	            if ($stu_group eq $grp) {
  655: 	                $exclude = 0;
  656:     	            } 
  657: 	        }
  658:     	        if (($grp eq 'none') && !$group) {
  659:         	        $exclude = 0;
  660:         	}
  661: 	    }
  662: 	    if ($exclude) {
  663: 	        delete($classlist->{$student});
  664: 	    }
  665: 	}
  666: 	$section = ($section ne '' ? $section : 'none');
  667: 	if (&canview($section)) {
  668: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  669: 		$sections{$section}++;
  670: 		if ($classlist->{$student}) {
  671: 		    $fullnames{$student}=$fullname;
  672: 		}
  673: 	    } else {
  674: 		delete($classlist->{$student});
  675: 	    }
  676: 	} else {
  677: 	    delete($classlist->{$student});
  678: 	}
  679:     }
  680:     my %seen = ();
  681:     my @sections = sort(keys(%sections));
  682:     return ($classlist,\@sections,\%fullnames);
  683: }
  684: 
  685: sub canmodify {
  686:     my ($sec)=@_;
  687:     if ($perm{'mgr'}) {
  688: 	if (!defined($perm{'mgr_section'})) {
  689: 	    # can modify whole class
  690: 	    return 1;
  691: 	} else {
  692: 	    if ($sec eq $perm{'mgr_section'}) {
  693: 		#can modify the requested section
  694: 		return 1;
  695: 	    } else {
  696: 		# can't modify the request section
  697: 		return 0;
  698: 	    }
  699: 	}
  700:     }
  701:     #can't modify
  702:     return 0;
  703: }
  704: 
  705: sub canview {
  706:     my ($sec)=@_;
  707:     if ($perm{'vgr'}) {
  708: 	if (!defined($perm{'vgr_section'})) {
  709: 	    # can modify whole class
  710: 	    return 1;
  711: 	} else {
  712: 	    if ($sec eq $perm{'vgr_section'}) {
  713: 		#can modify the requested section
  714: 		return 1;
  715: 	    } else {
  716: 		# can't modify the request section
  717: 		return 0;
  718: 	    }
  719: 	}
  720:     }
  721:     #can't modify
  722:     return 0;
  723: }
  724: 
  725: #--- Retrieve the grade status of a student for all the parts
  726: sub student_gradeStatus {
  727:     my ($symb,$udom,$uname,$partlist) = @_;
  728:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  729:     my %partstatus = ();
  730:     foreach (@$partlist) {
  731: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  732: 	$status              = 'nothing' if ($status eq '');
  733: 	$partstatus{$_}      = $status;
  734: 	my $subkey           = "resource.$_.submitted_by";
  735: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  736:     }
  737:     return %partstatus;
  738: }
  739: 
  740: # hidden form and javascript that calls the form
  741: # Use by verifyscript and viewgrades
  742: # Shows a student's view of problem and submission
  743: sub jscriptNform {
  744:     my ($symb) = @_;
  745:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  746:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  747: 	'    function viewOneStudent(user,domain) {'."\n".
  748: 	'	document.onestudent.student.value = user;'."\n".
  749: 	'	document.onestudent.userdom.value = domain;'."\n".
  750: 	'	document.onestudent.submit();'."\n".
  751: 	'    }'."\n".
  752: 	'</script>'."\n";
  753:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  754: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  755: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  756: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  757: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  758: 	'<input type="hidden" name="command" value="submission" />'."\n".
  759: 	'<input type="hidden" name="student" value="" />'."\n".
  760: 	'<input type="hidden" name="userdom" value="" />'."\n".
  761: 	'</form>'."\n";
  762:     return $jscript;
  763: }
  764: 
  765: 
  766: 
  767: # Given the score (as a number [0-1] and the weight) what is the final
  768: # point value? This function will round to the nearest tenth, third,
  769: # or quarter if one of those is within the tolerance of .00001.
  770: sub compute_points {
  771:     my ($score, $weight) = @_;
  772:     
  773:     my $tolerance = .00001;
  774:     my $points = $score * $weight;
  775: 
  776:     # Check for nearness to 1/x.
  777:     my $check_for_nearness = sub {
  778:         my ($factor) = @_;
  779:         my $num = ($points * $factor) + $tolerance;
  780:         my $floored_num = floor($num);
  781:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  782:             return $floored_num / $factor;
  783:         }
  784:         return $points;
  785:     };
  786: 
  787:     $points = $check_for_nearness->(10);
  788:     $points = $check_for_nearness->(3);
  789:     $points = $check_for_nearness->(4);
  790:     
  791:     return $points;
  792: }
  793: 
  794: #------------------ End of general use routines --------------------
  795: 
  796: #
  797: # Find most similar essay
  798: #
  799: 
  800: sub most_similar {
  801:     my ($uname,$udom,$uessay,$old_essays)=@_;
  802: 
  803: # ignore spaces and punctuation
  804: 
  805:     $uessay=~s/\W+/ /gs;
  806: 
  807: # ignore empty submissions (occuring when only files are sent)
  808: 
  809:     unless ($uessay=~/\w+/) { return ''; }
  810: 
  811: # these will be returned. Do not care if not at least 50 percent similar
  812:     my $limit=0.6;
  813:     my $sname='';
  814:     my $sdom='';
  815:     my $scrsid='';
  816:     my $sessay='';
  817: # go through all essays ...
  818:     foreach my $tkey (keys(%$old_essays)) {
  819: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  820: # ... except the same student
  821:         next if (($tname eq $uname) && ($tdom eq $udom));
  822: 	my $tessay=$old_essays->{$tkey};
  823: 	$tessay=~s/\W+/ /gs;
  824: # String similarity gives up if not even limit
  825: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  826: # Found one
  827: 	if ($tsimilar>$limit) {
  828: 	    $limit=$tsimilar;
  829: 	    $sname=$tname;
  830: 	    $sdom=$tdom;
  831: 	    $scrsid=$tcrsid;
  832: 	    $sessay=$old_essays->{$tkey};
  833: 	}
  834:     }
  835:     if ($limit>0.6) {
  836:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  837:     } else {
  838:        return ('','','','',0);
  839:     }
  840: }
  841: 
  842: #-------------------------------------------------------------------
  843: 
  844: #------------------------------------ Receipt Verification Routines
  845: #
  846: #--- Check whether a receipt number is valid.---
  847: sub verifyreceipt {
  848:     my $request  = shift;
  849: 
  850:     my $courseid = $env{'request.course.id'};
  851:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  852: 	$env{'form.receipt'};
  853:     $receipt     =~ s/[^\-\d]//g;
  854:     my ($symb)   = &get_symb($request);
  855: 
  856:     my $title.=
  857: 	'<h3><span class="LC_info">'.
  858: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  859: 	'</span></h3>'."\n".
  860: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  861: 	'</h4>'."\n";
  862: 
  863:     my ($string,$contents,$matches) = ('','',0);
  864:     my (undef,undef,$fullname) = &getclasslist('all','0');
  865:     
  866:     my $receiptparts=0;
  867:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  868: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  869:     my $parts=['0'];
  870:     if ($receiptparts) { ($parts)=&response_type($symb); }
  871:     
  872:     my $header = 
  873: 	&Apache::loncommon::start_data_table().
  874: 	&Apache::loncommon::start_data_table_header_row().
  875: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  876: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  877: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  878:     if ($receiptparts) {
  879: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  880:     }
  881:     $header.=
  882: 	&Apache::loncommon::end_data_table_header_row();
  883: 
  884:     foreach (sort 
  885: 	     {
  886: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  887: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  888: 		 }
  889: 		 return $a cmp $b;
  890: 	     } (keys(%$fullname))) {
  891: 	my ($uname,$udom)=split(/\:/);
  892: 	foreach my $part (@$parts) {
  893: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  894: 		$contents.=
  895: 		    &Apache::loncommon::start_data_table_row().
  896: 		    '<td>&nbsp;'."\n".
  897: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  898: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  899: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  900: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  901: 		if ($receiptparts) {
  902: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  903: 		}
  904: 		$contents.= 
  905: 		    &Apache::loncommon::end_data_table_row()."\n";
  906: 		
  907: 		$matches++;
  908: 	    }
  909: 	}
  910:     }
  911:     if ($matches == 0) {
  912: 	$string = $title.&mt('No match found for the above receipt.');
  913:     } else {
  914: 	$string = &jscriptNform($symb).$title.
  915: 	    '<p>'.
  916: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  917: 	    '</p>'.
  918: 	    $header.
  919: 	    $contents.
  920: 	    &Apache::loncommon::end_data_table()."\n";
  921:     }
  922:     return $string.&show_grading_menu_form($symb);
  923: }
  924: 
  925: #--- This is called by a number of programs.
  926: #--- Called from the Grading Menu - View/Grade an individual student
  927: #--- Also called directly when one clicks on the subm button 
  928: #    on the problem page.
  929: sub listStudents {
  930:     my ($request) = shift;
  931: 
  932:     my ($symb) = &get_symb($request);
  933:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  934:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  935:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  936:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  937:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  938:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  939:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  940: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  941: 
  942:     my $result='<h3><span class="LC_info">&nbsp;'.
  943: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  944: 	.'</span></h3>';
  945: 
  946:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  947: 
  948:     my %lt = ( 'multiple' =>
  949: 	       "Please select a student or group of students before clicking on the Next button.",
  950: 	       'single'   =>
  951: 	       "Please select the student before clicking on the Next button.",
  952: 	       );
  953:     %lt = &Apache::lonlocal::texthash(%lt);
  954:     $request->print(<<LISTJAVASCRIPT);
  955: <script type="text/javascript" language="javascript">
  956:     function checkSelect(checkBox) {
  957: 	var ctr=0;
  958: 	var sense="";
  959: 	if (checkBox.length > 1) {
  960: 	    for (var i=0; i<checkBox.length; i++) {
  961: 		if (checkBox[i].checked) {
  962: 		    ctr++;
  963: 		}
  964: 	    }
  965: 	    sense = '$lt{'multiple'}';
  966: 	} else {
  967: 	    if (checkBox.checked) {
  968: 		ctr = 1;
  969: 	    }
  970: 	    sense = '$lt{'single'}';
  971: 	}
  972: 	if (ctr == 0) {
  973: 	    alert(sense);
  974: 	    return false;
  975: 	}
  976: 	document.gradesub.submit();
  977:     }
  978: 
  979:     function reLoadList(formname) {
  980: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  981: 	formname.command.value = 'submission';
  982: 	formname.submit();
  983:     }
  984: </script>
  985: LISTJAVASCRIPT
  986: 
  987:     &commonJSfunctions($request);
  988:     $request->print($result);
  989: 
  990:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  991:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  992:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  993: 	"\n".$table;
  994: 	
  995:     $gradeTable .= 
  996: 	'&nbsp;'.
  997: 	&mt('<b>View Problem Text: </b>[_1]',
  998: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
  999: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
 1000: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
 1001:     $gradeTable .= 
 1002: 	'&nbsp;'.
 1003: 	&mt('<b>View Answer: </b>[_1]',
 1004: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
 1005: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
 1006: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
 1007: 
 1008:     my $submission_options;
 1009:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
 1010: 	$submission_options.=
 1011: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
 1012:     }
 1013:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1014:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1015:     $env{'form.Status'} = $saveStatus;
 1016:     $submission_options.=
 1017: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
 1018: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
 1019: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
 1020: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
 1021:     $gradeTable .= 
 1022: 	'&nbsp;'.
 1023: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
 1024: 
 1025:     $gradeTable .= 
 1026:         '&nbsp;'.
 1027: 	&mt('<b>Grading Increments:</b> [_1]',
 1028: 	    '<select name="increment">'.
 1029: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
 1030: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
 1031: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
 1032: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
 1033: 	    '</select>');
 1034:     
 1035:     $gradeTable .= 
 1036:         &build_section_inputs().
 1037: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1038: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1039: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1040: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1041: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1042: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1043: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1044: 
 1045:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1046: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
 1047:     } else {
 1048: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
 1049: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
 1050:     }
 1051: 
 1052:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
 1053: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
 1054: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
 1055: 
 1056: # checkall buttons
 1057:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1058:     $gradeTable.='<input type="button" '."\n".
 1059: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1060: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
 1061:     $gradeTable.=&check_buttons();
 1062:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
 1063:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1064:     $gradeTable.= &Apache::loncommon::start_data_table().
 1065: 	&Apache::loncommon::start_data_table_header_row();
 1066:     my $loop = 0;
 1067:     while ($loop < 2) {
 1068: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1069: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1070: 	if ($env{'form.showgrading'} eq 'yes' 
 1071: 	    && $submitonly ne 'queued'
 1072: 	    && $submitonly ne 'all') {
 1073: 	    foreach my $part (sort(@$partlist)) {
 1074: 		my $display_part=
 1075: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1076: 		$gradeTable.=
 1077: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1078: 	    }
 1079: 	} elsif ($submitonly eq 'queued') {
 1080: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1081: 	}
 1082: 	$loop++;
 1083: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1084:     }
 1085:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1086: 
 1087:     my $ctr = 0;
 1088:     foreach my $student (sort 
 1089: 			 {
 1090: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1091: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1092: 			     }
 1093: 			     return $a cmp $b;
 1094: 			 }
 1095: 			 (keys(%$fullname))) {
 1096: 	my ($uname,$udom) = split(/:/,$student);
 1097: 
 1098: 	my %status = ();
 1099: 
 1100: 	if ($submitonly eq 'queued') {
 1101: 	    my %queue_status = 
 1102: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1103: 							$udom,$uname);
 1104: 	    next if (!defined($queue_status{'gradingqueue'}));
 1105: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1106: 	}
 1107: 
 1108: 	if ($env{'form.showgrading'} eq 'yes' 
 1109: 	    && $submitonly ne 'queued'
 1110: 	    && $submitonly ne 'all') {
 1111: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1112: 	    my $submitted = 0;
 1113: 	    my $graded = 0;
 1114: 	    my $incorrect = 0;
 1115: 	    foreach (keys(%status)) {
 1116: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1117: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1118: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1119: 		
 1120: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1121: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1122: 		    $submitted = 0;
 1123: 		    my ($part)=split(/\./,$partid);
 1124: 		    $gradeTable.='<input type="hidden" name="'.
 1125: 			$student.':'.$part.':submitted_by" value="'.
 1126: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1127: 		}
 1128: 	    }
 1129: 	    
 1130: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1131: 				     $submitonly eq 'incorrect' ||
 1132: 				     $submitonly eq 'graded'));
 1133: 	    next if (!$graded && ($submitonly eq 'graded'));
 1134: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1135: 	}
 1136: 
 1137: 	$ctr++;
 1138: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1139:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1140: 	if ( $perm{'vgr'} eq 'F' ) {
 1141: 	    if ($ctr%2 ==1) {
 1142: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1143: 	    }
 1144: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1145:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1146:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1147: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1148: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1149: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1150: 
 1151: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1152: 		foreach (sort(keys(%status))) {
 1153: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1154: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1155: 		}
 1156: 	    }
 1157: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1158: 	    if ($ctr%2 ==0) {
 1159: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1160: 	    }
 1161: 	}
 1162:     }
 1163:     if ($ctr%2 ==1) {
 1164: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1165: 	    if ($env{'form.showgrading'} eq 'yes' 
 1166: 		&& $submitonly ne 'queued'
 1167: 		&& $submitonly ne 'all') {
 1168: 		foreach (@$partlist) {
 1169: 		    $gradeTable.='<td>&nbsp;</td>';
 1170: 		}
 1171: 	    } elsif ($submitonly eq 'queued') {
 1172: 		$gradeTable.='<td>&nbsp;</td>';
 1173: 	    }
 1174: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1175:     }
 1176: 
 1177:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1178: 	'<input type="button" '.
 1179: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1180: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1181:     if ($ctr == 0) {
 1182: 	my $num_students=(scalar(keys(%$fullname)));
 1183: 	if ($num_students eq 0) {
 1184: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1185: 	} else {
 1186: 	    my $submissions='submissions';
 1187: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1188: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1189: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1190: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1191: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1192: 		    $num_students).
 1193: 		'</span><br />';
 1194: 	}
 1195:     } elsif ($ctr == 1) {
 1196: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1197:     }
 1198:     $gradeTable.=&show_grading_menu_form($symb);
 1199:     $request->print($gradeTable);
 1200:     return '';
 1201: }
 1202: 
 1203: #---- Called from the listStudents routine
 1204: 
 1205: sub check_script {
 1206:     my ($form, $type)=@_;
 1207:     my $chkallscript='<script type="text/javascript">
 1208:     function checkall() {
 1209:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1210:             ele = document.forms.'.$form.'.elements[i];
 1211:             if (ele.name == "'.$type.'") {
 1212:             document.forms.'.$form.'.elements[i].checked=true;
 1213:                                        }
 1214:         }
 1215:     }
 1216: 
 1217:     function checksec() {
 1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1219:             ele = document.forms.'.$form.'.elements[i];
 1220:            string = document.forms.'.$form.'.chksec.value;
 1221:            if
 1222:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1223:               document.forms.'.$form.'.elements[i].checked=true;
 1224:             }
 1225:         }
 1226:     }
 1227: 
 1228: 
 1229:     function uncheckall() {
 1230:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1231:             ele = document.forms.'.$form.'.elements[i];
 1232:             if (ele.name == "'.$type.'") {
 1233:             document.forms.'.$form.'.elements[i].checked=false;
 1234:                                        }
 1235:         }
 1236:     }
 1237: 
 1238: </script>'."\n";
 1239:     return $chkallscript;
 1240: }
 1241: 
 1242: sub check_buttons {
 1243:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1244:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1245:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1246:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1247:     return $buttons;
 1248: }
 1249: 
 1250: #     Displays the submissions for one student or a group of students
 1251: sub processGroup {
 1252:     my ($request)  = shift;
 1253:     my $ctr        = 0;
 1254:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1255:     my $total      = scalar(@stuchecked)-1;
 1256: 
 1257:     foreach my $student (@stuchecked) {
 1258: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1259: 	$env{'form.student'}        = $uname;
 1260: 	$env{'form.userdom'}        = $udom;
 1261: 	$env{'form.fullname'}       = $fullname;
 1262: 	&submission($request,$ctr,$total);
 1263: 	$ctr++;
 1264:     }
 1265:     return '';
 1266: }
 1267: 
 1268: #------------------------------------------------------------------------------------
 1269: #
 1270: #-------------------------- Next few routines handles grading by student, essentially
 1271: #                           handles essay response type problem/part
 1272: #
 1273: #--- Javascript to handle the submission page functionality ---
 1274: sub sub_page_js {
 1275:     my $request = shift;
 1276:     $request->print(<<SUBJAVASCRIPT);
 1277: <script type="text/javascript" language="javascript">
 1278:     function updateRadio(formname,id,weight) {
 1279: 	var gradeBox = formname["GD_BOX"+id];
 1280: 	var radioButton = formname["RADVAL"+id];
 1281: 	var oldpts = formname["oldpts"+id].value;
 1282: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1283: 	gradeBox.value = pts;
 1284: 	var resetbox = false;
 1285: 	if (isNaN(pts) || pts < 0) {
 1286: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1287: 	    for (var i=0; i<radioButton.length; i++) {
 1288: 		if (radioButton[i].checked) {
 1289: 		    gradeBox.value = i;
 1290: 		    resetbox = true;
 1291: 		}
 1292: 	    }
 1293: 	    if (!resetbox) {
 1294: 		formtextbox.value = "";
 1295: 	    }
 1296: 	    return;
 1297: 	}
 1298: 
 1299: 	if (pts > weight) {
 1300: 	    var resp = confirm("You entered a value ("+pts+
 1301: 			       ") greater than the weight for the part. Accept?");
 1302: 	    if (resp == false) {
 1303: 		gradeBox.value = oldpts;
 1304: 		return;
 1305: 	    }
 1306: 	}
 1307: 
 1308: 	for (var i=0; i<radioButton.length; i++) {
 1309: 	    radioButton[i].checked=false;
 1310: 	    if (pts == i && pts != "") {
 1311: 		radioButton[i].checked=true;
 1312: 	    }
 1313: 	}
 1314: 	updateSelect(formname,id);
 1315: 	formname["stores"+id].value = "0";
 1316:     }
 1317: 
 1318:     function writeBox(formname,id,pts) {
 1319: 	var gradeBox = formname["GD_BOX"+id];
 1320: 	if (checkSolved(formname,id) == 'update') {
 1321: 	    gradeBox.value = pts;
 1322: 	} else {
 1323: 	    var oldpts = formname["oldpts"+id].value;
 1324: 	    gradeBox.value = oldpts;
 1325: 	    var radioButton = formname["RADVAL"+id];
 1326: 	    for (var i=0; i<radioButton.length; i++) {
 1327: 		radioButton[i].checked=false;
 1328: 		if (i == oldpts) {
 1329: 		    radioButton[i].checked=true;
 1330: 		}
 1331: 	    }
 1332: 	}
 1333: 	formname["stores"+id].value = "0";
 1334: 	updateSelect(formname,id);
 1335: 	return;
 1336:     }
 1337: 
 1338:     function clearRadBox(formname,id) {
 1339: 	if (checkSolved(formname,id) == 'noupdate') {
 1340: 	    updateSelect(formname,id);
 1341: 	    return;
 1342: 	}
 1343: 	gradeSelect = formname["GD_SEL"+id];
 1344: 	for (var i=0; i<gradeSelect.length; i++) {
 1345: 	    if (gradeSelect[i].selected) {
 1346: 		var selectx=i;
 1347: 	    }
 1348: 	}
 1349: 	var stores = formname["stores"+id];
 1350: 	if (selectx == stores.value) { return };
 1351: 	var gradeBox = formname["GD_BOX"+id];
 1352: 	gradeBox.value = "";
 1353: 	var radioButton = formname["RADVAL"+id];
 1354: 	for (var i=0; i<radioButton.length; i++) {
 1355: 	    radioButton[i].checked=false;
 1356: 	}
 1357: 	stores.value = selectx;
 1358:     }
 1359: 
 1360:     function checkSolved(formname,id) {
 1361: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1362: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1363: 	    if (!reply) {return "noupdate";}
 1364: 	    formname.overRideScore.value = 'yes';
 1365: 	}
 1366: 	return "update";
 1367:     }
 1368: 
 1369:     function updateSelect(formname,id) {
 1370: 	formname["GD_SEL"+id][0].selected = true;
 1371: 	return;
 1372:     }
 1373: 
 1374: //=========== Check that a point is assigned for all the parts  ============
 1375:     function checksubmit(formname,val,total,parttot) {
 1376: 	formname.gradeOpt.value = val;
 1377: 	if (val == "Save & Next") {
 1378: 	    for (i=0;i<=total;i++) {
 1379: 		for (j=0;j<parttot;j++) {
 1380: 		    var partid = formname["partid"+i+"_"+j].value;
 1381: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1382: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1383: 			if (points == "") {
 1384: 			    var name = formname["name"+i].value;
 1385: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1386: 			    var resp = confirm("You did not assign a score for "+studentID+
 1387: 					       ", part "+partid+". Continue?");
 1388: 			    if (resp == false) {
 1389: 				formname["GD_BOX"+i+"_"+partid].focus();
 1390: 				return false;
 1391: 			    }
 1392: 			}
 1393: 		    }
 1394: 		    
 1395: 		}
 1396: 	    }
 1397: 	    
 1398: 	}
 1399: 	if (val == "Grade Student") {
 1400: 	    formname.showgrading.value = "yes";
 1401: 	    if (formname.Status.value == "") {
 1402: 		formname.Status.value = "Active";
 1403: 	    }
 1404: 	    formname.studentNo.value = total;
 1405: 	}
 1406: 	formname.submit();
 1407:     }
 1408: 
 1409: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1410:     function checkSubmitPage(formname,total) {
 1411: 	noscore = new Array(100);
 1412: 	var ptr = 0;
 1413: 	for (i=1;i<total;i++) {
 1414: 	    var partid = formname["q_"+i].value;
 1415: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1416: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1417: 		var status = formname["solved"+i+"_"+partid].value;
 1418: 		if (points == "" && status != "correct_by_student") {
 1419: 		    noscore[ptr] = i;
 1420: 		    ptr++;
 1421: 		}
 1422: 	    }
 1423: 	}
 1424: 	if (ptr != 0) {
 1425: 	    var sense = ptr == 1 ? ": " : "s: ";
 1426: 	    var prolist = "";
 1427: 	    if (ptr == 1) {
 1428: 		prolist = noscore[0];
 1429: 	    } else {
 1430: 		var i = 0;
 1431: 		while (i < ptr-1) {
 1432: 		    prolist += noscore[i]+", ";
 1433: 		    i++;
 1434: 		}
 1435: 		prolist += "and "+noscore[i];
 1436: 	    }
 1437: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1438: 	    if (resp == false) {
 1439: 		return false;
 1440: 	    }
 1441: 	}
 1442: 
 1443: 	formname.submit();
 1444:     }
 1445: </script>
 1446: SUBJAVASCRIPT
 1447: }
 1448: 
 1449: #--- javascript for essay type problem --
 1450: sub sub_page_kw_js {
 1451:     my $request = shift;
 1452:     my $iconpath = $request->dir_config('lonIconsURL');
 1453:     &commonJSfunctions($request);
 1454: 
 1455:     my $inner_js_msg_central=<<INNERJS;
 1456:     <script text="text/javascript">
 1457:     function checkInput() {
 1458:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1459:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1460:       var usrctr = document.msgcenter.usrctr.value;
 1461:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1462:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1463: 
 1464:       var msgchk = "";
 1465:       if (document.msgcenter.subchk.checked) {
 1466:          msgchk = "msgsub,";
 1467:       }
 1468:       var includemsg = 0;
 1469:       for (var i=1; i<=nmsg; i++) {
 1470:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1471:           var frmmsg = document.msgcenter["msg"+i];
 1472:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1473:           var showflg = opener.document.SCORE["shownOnce"+i];
 1474:           showflg.value = "1";
 1475:           var chkbox = document.msgcenter["msgn"+i];
 1476:           if (chkbox.checked) {
 1477:              msgchk += "savemsg"+i+",";
 1478:              includemsg = 1;
 1479:           }
 1480:       }
 1481:       if (document.msgcenter.newmsgchk.checked) {
 1482:          msgchk += "newmsg"+usrctr;
 1483:          includemsg = 1;
 1484:       }
 1485:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1486:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1487:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1488:       includemsg.value = msgchk;
 1489: 
 1490:       self.close()
 1491: 
 1492:     }
 1493:     </script>
 1494: INNERJS
 1495: 
 1496:     my $inner_js_highlight_central=<<INNERJS;
 1497:  <script type="text/javascript">
 1498:     function updateChoice(flag) {
 1499:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1500:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1501:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1502:       opener.document.SCORE.refresh.value = "on";
 1503:       if (opener.document.SCORE.keywords.value!=""){
 1504:          opener.document.SCORE.submit();
 1505:       }
 1506:       self.close()
 1507:     }
 1508: </script>
 1509: INNERJS
 1510: 
 1511:     my $start_page_msg_central = 
 1512:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1513: 				       {'js_ready'  => 1,
 1514: 					'only_body' => 1,
 1515: 					'bgcolor'   =>'#FFFFFF',});
 1516:     my $end_page_msg_central = 
 1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1518: 
 1519: 
 1520:     my $start_page_highlight_central = 
 1521:         &Apache::loncommon::start_page('Highlight Central',
 1522: 				       $inner_js_highlight_central,
 1523: 				       {'js_ready'  => 1,
 1524: 					'only_body' => 1,
 1525: 					'bgcolor'   =>'#FFFFFF',});
 1526:     my $end_page_highlight_central = 
 1527: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1528: 
 1529:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1530:     $docopen=~s/^document\.//;
 1531:     $request->print(<<SUBJAVASCRIPT);
 1532: <script type="text/javascript" language="javascript">
 1533: 
 1534: //===================== Show list of keywords ====================
 1535:   function keywords(formname) {
 1536:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1537:     if (nret==null) return;
 1538:     formname.keywords.value = nret;
 1539: 
 1540:     if (formname.keywords.value != "") {
 1541: 	formname.refresh.value = "on";
 1542: 	formname.submit();
 1543:     }
 1544:     return;
 1545:   }
 1546: 
 1547: //===================== Script to view submitted by ==================
 1548:   function viewSubmitter(submitter) {
 1549:     document.SCORE.refresh.value = "on";
 1550:     document.SCORE.NCT.value = "1";
 1551:     document.SCORE.unamedom0.value = submitter;
 1552:     document.SCORE.submit();
 1553:     return;
 1554:   }
 1555: 
 1556: //===================== Script to add keyword(s) ==================
 1557:   function getSel() {
 1558:     if (document.getSelection) txt = document.getSelection();
 1559:     else if (document.selection) txt = document.selection.createRange().text;
 1560:     else return;
 1561:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1562:     if (cleantxt=="") {
 1563: 	alert("Please select a word or group of words from document and then click this link.");
 1564: 	return;
 1565:     }
 1566:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1567:     if (nret==null) return;
 1568:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1569:     if (document.SCORE.keywords.value != "") {
 1570: 	document.SCORE.refresh.value = "on";
 1571: 	document.SCORE.submit();
 1572:     }
 1573:     return;
 1574:   }
 1575: 
 1576: //====================== Script for composing message ==============
 1577:    // preload images
 1578:    img1 = new Image();
 1579:    img1.src = "$iconpath/mailbkgrd.gif";
 1580:    img2 = new Image();
 1581:    img2.src = "$iconpath/mailto.gif";
 1582: 
 1583:   function msgCenter(msgform,usrctr,fullname) {
 1584:     var Nmsg  = msgform.savemsgN.value;
 1585:     savedMsgHeader(Nmsg,usrctr,fullname);
 1586:     var subject = msgform.msgsub.value;
 1587:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1588:     re = /msgsub/;
 1589:     var shwsel = "";
 1590:     if (re.test(msgchk)) { shwsel = "checked" }
 1591:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1592:     displaySubject(checkEntities(subject),shwsel);
 1593:     for (var i=1; i<=Nmsg; i++) {
 1594: 	var testmsg = "savemsg"+i+",";
 1595: 	re = new RegExp(testmsg,"g");
 1596: 	shwsel = "";
 1597: 	if (re.test(msgchk)) { shwsel = "checked" }
 1598: 	var message = document.SCORE["savemsg"+i].value;
 1599: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1600: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1601: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1602:     }
 1603:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1604:     shwsel = "";
 1605:     re = /newmsg/;
 1606:     if (re.test(msgchk)) { shwsel = "checked" }
 1607:     newMsg(newmsg,shwsel);
 1608:     msgTail(); 
 1609:     return;
 1610:   }
 1611: 
 1612:   function checkEntities(strx) {
 1613:     if (strx.length == 0) return strx;
 1614:     var orgStr = ["&", "<", ">", '"']; 
 1615:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1616:     var counter = 0;
 1617:     while (counter < 4) {
 1618: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1619: 	counter++;
 1620:     }
 1621:     return strx;
 1622:   }
 1623: 
 1624:   function strReplace(strx, orgStr, newStr) {
 1625:     return strx.split(orgStr).join(newStr);
 1626:   }
 1627: 
 1628:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1629:     var height = 70*Nmsg+250;
 1630:     var scrollbar = "no";
 1631:     if (height > 600) {
 1632: 	height = 600;
 1633: 	scrollbar = "yes";
 1634:     }
 1635:     var xpos = (screen.width-600)/2;
 1636:     xpos = (xpos < 0) ? '0' : xpos;
 1637:     var ypos = (screen.height-height)/2-30;
 1638:     ypos = (ypos < 0) ? '0' : ypos;
 1639: 
 1640:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1641:     pWin.focus();
 1642:     pDoc = pWin.document;
 1643:     pDoc.$docopen;
 1644:     pDoc.write('$start_page_msg_central');
 1645: 
 1646:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1647:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1648:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1649: 
 1650:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1651:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1652:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1653: }
 1654:     function displaySubject(msg,shwsel) {
 1655:     pDoc = pWin.document;
 1656:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1657:     pDoc.write("<td>Subject<\\/td>");
 1658:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1659:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1660: }
 1661: 
 1662:   function displaySavedMsg(ctr,msg,shwsel) {
 1663:     pDoc = pWin.document;
 1664:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1665:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1666:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1667:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1668: }
 1669: 
 1670:   function newMsg(newmsg,shwsel) {
 1671:     pDoc = pWin.document;
 1672:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1673:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1674:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1675:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1676: }
 1677: 
 1678:   function msgTail() {
 1679:     pDoc = pWin.document;
 1680:     pDoc.write("<\\/table>");
 1681:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1682:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1683:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1684:     pDoc.write("<\\/form>");
 1685:     pDoc.write('$end_page_msg_central');
 1686:     pDoc.close();
 1687: }
 1688: 
 1689: //====================== Script for keyword highlight options ==============
 1690:   function kwhighlight() {
 1691:     var kwclr    = document.SCORE.kwclr.value;
 1692:     var kwsize   = document.SCORE.kwsize.value;
 1693:     var kwstyle  = document.SCORE.kwstyle.value;
 1694:     var redsel = "";
 1695:     var grnsel = "";
 1696:     var blusel = "";
 1697:     if (kwclr=="red")   {var redsel="checked"};
 1698:     if (kwclr=="green") {var grnsel="checked"};
 1699:     if (kwclr=="blue")  {var blusel="checked"};
 1700:     var sznsel = "";
 1701:     var sz1sel = "";
 1702:     var sz2sel = "";
 1703:     if (kwsize=="0")  {var sznsel="checked"};
 1704:     if (kwsize=="+1") {var sz1sel="checked"};
 1705:     if (kwsize=="+2") {var sz2sel="checked"};
 1706:     var synsel = "";
 1707:     var syisel = "";
 1708:     var sybsel = "";
 1709:     if (kwstyle=="")    {var synsel="checked"};
 1710:     if (kwstyle=="<i>") {var syisel="checked"};
 1711:     if (kwstyle=="<b>") {var sybsel="checked"};
 1712:     highlightCentral();
 1713:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1714:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1715:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1716:     highlightend();
 1717:     return;
 1718:   }
 1719: 
 1720:   function highlightCentral() {
 1721: //    if (window.hwdWin) window.hwdWin.close();
 1722:     var xpos = (screen.width-400)/2;
 1723:     xpos = (xpos < 0) ? '0' : xpos;
 1724:     var ypos = (screen.height-330)/2-30;
 1725:     ypos = (ypos < 0) ? '0' : ypos;
 1726: 
 1727:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1728:     hwdWin.focus();
 1729:     var hDoc = hwdWin.document;
 1730:     hDoc.$docopen;
 1731:     hDoc.write('$start_page_highlight_central');
 1732:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1733:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1734: 
 1735:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1736:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1737:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1738:   }
 1739: 
 1740:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1741:     var hDoc = hwdWin.document;
 1742:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1743:     hDoc.write("<td align=\\"left\\">");
 1744:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1745:     hDoc.write("<td align=\\"left\\">");
 1746:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1747:     hDoc.write("<td align=\\"left\\">");
 1748:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1749:     hDoc.write("<\\/tr>");
 1750:   }
 1751: 
 1752:   function highlightend() { 
 1753:     var hDoc = hwdWin.document;
 1754:     hDoc.write("<\\/table>");
 1755:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1756:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1757:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1758:     hDoc.write("<\\/form>");
 1759:     hDoc.write('$end_page_highlight_central');
 1760:     hDoc.close();
 1761:   }
 1762: 
 1763: </script>
 1764: SUBJAVASCRIPT
 1765: }
 1766: 
 1767: sub get_increment {
 1768:     my $increment = $env{'form.increment'};
 1769:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1770:         $increment != .1) {
 1771:         $increment = 1;
 1772:     }
 1773:     return $increment;
 1774: }
 1775: 
 1776: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1777: sub gradeBox {
 1778:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1779:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1780: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1781:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1782:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1783:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1784:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1785:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1786: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1787:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1788:     my $display_part= &get_display_part($partid,$symb);
 1789:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1790: 				       [$partid]);
 1791:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1792:     if ($last_resets{$partid}) {
 1793:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1794:     }
 1795:     $result.='<table border="0"><tr>';
 1796:     my $ctr = 0;
 1797:     my $thisweight = 0;
 1798:     my $increment = &get_increment();
 1799: 
 1800:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1801:     while ($thisweight<=$wgt) {
 1802: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1803: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1804: 	    $thisweight.')" value="'.$thisweight.'" '.
 1805: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1806: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1807:         $thisweight += $increment;
 1808: 	$ctr++;
 1809:     }
 1810:     $radio.='</tr></table>';
 1811: 
 1812:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1813: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1814: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1815: 	$wgt.')" /></td>'."\n";
 1816:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1817: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1818: 	' </td><td>'."\n";
 1819:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1820: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1821:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1822: 	$line.='<option></option>'.
 1823: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1824:     } else {
 1825: 	$line.='<option selected="selected"></option>'.
 1826: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1827:     }
 1828:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1829: 
 1830: 
 1831:     $result .= 
 1832: 	&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
 1833: 
 1834:     
 1835:     $result.='</tr></table>'."\n";
 1836:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1837: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1838: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1839: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1840:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1841:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1842:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1843:         $aggtries.'" />'."\n";
 1844:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1845:     return $result;
 1846: }
 1847: 
 1848: sub handback_box {
 1849:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1850:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1851:     my (@respids);
 1852:      my @part_response_id = &flatten_responseType($responseType);
 1853:     foreach my $part_response_id (@part_response_id) {
 1854:     	my ($part,$resp) = @{ $part_response_id };
 1855:         if ($part eq $partid) {
 1856:             push(@respids,$resp);
 1857:         }
 1858:     }
 1859:     my $result;
 1860:     foreach my $respid (@respids) {
 1861: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1862: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1863: 	next if (!@$files);
 1864: 	my $file_counter = 1;
 1865: 	foreach my $file (@$files) {
 1866: 	    if ($file =~ /\/portfolio\//) {
 1867:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1868:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1869:     	        $file_disp = "$name.$ext";
 1870:     	        $file = $file_path.$file_disp;
 1871:     	        $result.=&mt('Return commented version of [_1] to student.',
 1872:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1873:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1874:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1875:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1876:     	        $file_counter++;
 1877: 	    }
 1878: 	}
 1879:     }
 1880:     return $result;    
 1881: }
 1882: 
 1883: sub show_problem {
 1884:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1885:     my $rendered;
 1886:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1887:     &Apache::lonxml::remember_problem_counter();
 1888:     if ($mode eq 'both' or $mode eq 'text') {
 1889: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1890: 						       $env{'request.course.id'},
 1891: 						       undef,\%form);
 1892:     }
 1893:     if ($removeform) {
 1894: 	$rendered=~s|<form(.*?)>||g;
 1895: 	$rendered=~s|</form>||g;
 1896: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1897:     }
 1898:     my $companswer;
 1899:     if ($mode eq 'both' or $mode eq 'answer') {
 1900: 	&Apache::lonxml::restore_problem_counter();
 1901: 	$companswer=
 1902: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1903: 						    $env{'request.course.id'},
 1904: 						    %form);
 1905:     }
 1906:     if ($removeform) {
 1907: 	$companswer=~s|<form(.*?)>||g;
 1908: 	$companswer=~s|</form>||g;
 1909: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1910:     }
 1911:     $rendered=
 1912: 	'<div class="LC_grade_show_problem_header">'.
 1913: 	&mt('View of the problem').
 1914: 	'</div><div class="LC_grade_show_problem_problem">'.
 1915: 	$rendered.
 1916: 	'</div>';
 1917:     $companswer=
 1918: 	'<div class="LC_grade_show_problem_header">'.
 1919: 	&mt('Correct answer').
 1920: 	'</div><div class="LC_grade_show_problem_problem">'.
 1921: 	$companswer.
 1922: 	'</div>';
 1923:     my $result;
 1924:     if ($mode eq 'both') {
 1925: 	$result=$rendered.$companswer;
 1926:     } elsif ($mode eq 'text') {
 1927: 	$result=$rendered;
 1928:     } elsif ($mode eq 'answer') {
 1929: 	$result=$companswer;
 1930:     }
 1931:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1932:     return $result;
 1933: }
 1934: 
 1935: sub files_exist {
 1936:     my ($r, $symb) = @_;
 1937:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1938: 
 1939:     foreach my $student (@students) {
 1940:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1941:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1942: 					      $udom,$uname);
 1943:         my ($string,$timestamp)= &get_last_submission(\%record);
 1944:         foreach my $submission (@$string) {
 1945:             my ($partid,$respid) =
 1946: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1947:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1948: 					   \%record);
 1949:             return 1 if (@$files);
 1950:         }
 1951:     }
 1952:     return 0;
 1953: }
 1954: 
 1955: sub download_all_link {
 1956:     my ($r,$symb) = @_;
 1957:     my $all_students = 
 1958: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1959: 
 1960:     my $parts =
 1961: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1962: 
 1963:     my $identifier = &Apache::loncommon::get_cgi_id();
 1964:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1965:                              'cgi.'.$identifier.'.symb' => $symb,
 1966:                              'cgi.'.$identifier.'.parts' => $parts,});
 1967:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1968: 	      &mt('Download All Submitted Documents').'</a>');
 1969:     return
 1970: }
 1971: 
 1972: sub build_section_inputs {
 1973:     my $section_inputs;
 1974:     if ($env{'form.section'} eq '') {
 1975:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1976:     } else {
 1977:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1978:         foreach my $section (@sections) {
 1979:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1980:         }
 1981:     }
 1982:     return $section_inputs;
 1983: }
 1984: 
 1985: # --------------------------- show submissions of a student, option to grade 
 1986: sub submission {
 1987:     my ($request,$counter,$total) = @_;
 1988:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1989:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1990:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1991:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1992:     my $symb = &get_symb($request); 
 1993:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1994: 
 1995:     if (!&canview($usec)) {
 1996: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1997: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1998: 			$env{'request.course.id'}.')</span>');
 1999: 	$request->print(&show_grading_menu_form($symb));
 2000: 	return;
 2001:     }
 2002: 
 2003:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2004:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2005:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2006:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2007:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2008: 	'" src="'.$request->dir_config('lonIconsURL').
 2009: 	'/check.gif" height="16" border="0" />';
 2010: 
 2011:     my %old_essays;
 2012:     # header info
 2013:     if ($counter == 0) {
 2014: 	&sub_page_js($request);
 2015: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2016: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2017: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2018: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2019: 	    &download_all_link($request, $symb);
 2020: 	}
 2021: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2022: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2023: 
 2024: 	# option to display problem, only once else it cause problems 
 2025:         # with the form later since the problem has a form.
 2026: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2027: 	    my $mode;
 2028: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2029: 		$mode='both';
 2030: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2031: 		$mode='text';
 2032: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2033: 		$mode='answer';
 2034: 	    }
 2035: 	    &Apache::lonxml::clear_problem_counter();
 2036: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2037: 	}
 2038: 
 2039: 	# kwclr is the only variable that is guaranteed to be non blank 
 2040:         # if this subroutine has been called once.
 2041: 	my %keyhash = ();
 2042: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2043: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2044: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2045: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2046: 
 2047: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2048: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2049: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2050: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2051: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2052: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2053: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2054: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2055: 	}
 2056: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2057: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2058: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2059: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2060: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2061: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2062: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2063: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2064: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2065: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2066: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2067: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2068: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2069: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2070: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2071: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2072: 			&build_section_inputs().
 2073: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2074: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2075: 			'<input type="hidden" name="NCT"'.
 2076: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2077: 	if ($env{'form.handgrade'} eq 'yes') {
 2078: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2079: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2080: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2081: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2082: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2083: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2084: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2085: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2086: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2087: 	    }
 2088: 	}
 2089: 	
 2090: 	my ($cts,$prnmsg) = (1,'');
 2091: 	while ($cts <= $env{'form.savemsgN'}) {
 2092: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2093: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2094: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2095: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2096: 		'" />'."\n".
 2097: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2098: 	    $cts++;
 2099: 	}
 2100: 	$request->print($prnmsg);
 2101: 
 2102: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2103: #
 2104: # Print out the keyword options line
 2105: #
 2106: 	    $request->print(<<KEYWORDS);
 2107: &nbsp;<b>Keyword Options:</b>&nbsp;
 2108: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2109: <a href="#" onMouseDown="javascript:getSel(); return false"
 2110:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2111: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2112: KEYWORDS
 2113: #
 2114: # Load the other essays for similarity check
 2115: #
 2116:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2117: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2118: 	    $apath=&escape($apath);
 2119: 	    $apath=~s/\W/\_/gs;
 2120: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2121:         }
 2122:     }
 2123: 
 2124: # This is where output for one specific student would start
 2125:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2126:     $request->print("\n\n".
 2127:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2128: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2129: 		    '<div class="LC_grade_show_user_body">'."\n");
 2130: 
 2131:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2132: 	my $mode;
 2133: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2134: 	    $mode='both';
 2135: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2136: 	    $mode='text';
 2137: 	} elsif ($env{'form.vAns'} eq 'all') {
 2138: 	    $mode='answer';
 2139: 	}
 2140: 	&Apache::lonxml::clear_problem_counter();
 2141: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2142:     }
 2143: 
 2144:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2146: 
 2147:     # Display student info
 2148:     $request->print(($counter == 0 ? '' : '<br />'));
 2149:     my $result='<div class="LC_grade_submissions">';
 2150:     
 2151:     $result.='<div class="LC_grade_submissions_header">';
 2152:     $result.= &mt('Submissions');
 2153:     $result.='<input type="hidden" name="name'.$counter.
 2154: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2155:     if ($env{'form.handgrade'} eq 'no') {
 2156: 	$result.='<span class="LC_grade_check_note">'.
 2157: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2158: 
 2159:     }
 2160: 
 2161: 
 2162: 
 2163:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2164:     my $fullname;
 2165:     my $col_fullnames = [];
 2166:     if ($env{'form.handgrade'} eq 'yes') {
 2167: 	(my $sub_result,$fullname,$col_fullnames)=
 2168: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2169: 				 $counter);
 2170: 	$result.=$sub_result;
 2171:     }
 2172:     $request->print($result."\n");
 2173:     $request->print('</div>'."\n");
 2174:     # print student answer/submission
 2175:     # Options are (1) Handgaded submission only
 2176:     #             (2) Last submission, includes submission that is not handgraded 
 2177:     #                  (for multi-response type part)
 2178:     #             (3) Last submission plus the parts info
 2179:     #             (4) The whole record for this student
 2180:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2181: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2182: 	
 2183: 	my $lastsubonly;
 2184: 
 2185: 	if ($$timestamp eq '') {
 2186: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2187: 	} else {
 2188: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2189: 
 2190: 	    my %seenparts;
 2191: 	    my @part_response_id = &flatten_responseType($responseType);
 2192: 	    foreach my $part (@part_response_id) {
 2193: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2194: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2195: 
 2196: 		my ($partid,$respid) = @{ $part };
 2197: 		my $display_part=&get_display_part($partid,$symb);
 2198: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2199: 		    if (exists($seenparts{$partid})) { next; }
 2200: 		    $seenparts{$partid}=1;
 2201: 		    my $submitby='<b>Part:</b> '.$display_part.
 2202: 			' <b>Collaborative submission by:</b> '.
 2203: 			'<a href="javascript:viewSubmitter(\''.
 2204: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2205: 			'\');" target="_self">'.
 2206: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2207: 		    $request->print($submitby);
 2208: 		    next;
 2209: 		}
 2210: 		my $responsetype = $responseType->{$partid}->{$respid};
 2211: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2212: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2213: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2214: 			' )</span>&nbsp; &nbsp;'.
 2215: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2216: 		    next;
 2217: 		}
 2218: 		foreach my $submission (@$string) {
 2219: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2220: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2221: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2222: 		    # Similarity check
 2223: 		    my $similar='';
 2224: 		    if($env{'form.checkPlag'}){
 2225: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2226: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2227: 			if ($osim) {
 2228: 			    $osim=int($osim*100.0);
 2229: 			    my %old_course_desc = 
 2230: 				&Apache::lonnet::coursedescription($ocrsid,
 2231: 								   {'one_time' => 1});
 2232: 
 2233: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2234: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2235: 				    $osim,
 2236: 				    &Apache::loncommon::plainname($oname,$odom),
 2237: 				    $oname,$odom,
 2238: 				    $old_course_desc{'description'},
 2239: 				    $old_course_desc{'num'},
 2240: 				    $old_course_desc{'domain'}).
 2241: 				'</span></h3><blockquote><i>'.
 2242: 				&keywords_highlight($oessay).
 2243: 				'</i></blockquote><hr />';
 2244: 			}
 2245: 		    }
 2246: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2247: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2248: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2249: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2250: 			my $display_part=&get_display_part($partid,$symb);
 2251: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2252: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2253: 			    ' )</span>&nbsp; &nbsp;';
 2254: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2255: 			if (@$files) {
 2256: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
 2257: 			    my $file_counter = 0;
 2258: 			    foreach my $file (@$files) {
 2259: 			        $file_counter++;
 2260: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2261: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2262: 			    }
 2263: 			    $lastsubonly.='<br />';
 2264: 			}
 2265: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2266: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2267: 					 $respid,\%record,$order);
 2268: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2269: 			$lastsubonly.='</div>';
 2270: 		    }
 2271: 		}
 2272: 	    }
 2273: 	    $lastsubonly.='</div>'."\n";
 2274: 	}
 2275: 	$request->print($lastsubonly);
 2276:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2277: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2278: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2279:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2280: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2281: 								 $env{'request.course.id'},
 2282: 								 $last,'.submission',
 2283: 								 'Apache::grades::keywords_highlight'));
 2284:     }
 2285: 
 2286:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2287: 	.$udom.'" />'."\n");
 2288:     # return if view submission with no grading option
 2289:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2290: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2291: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2292: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2293: 	$toGrade.='</div>'."\n";
 2294: 	if (($env{'form.command'} eq 'submission') || 
 2295: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2296: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2297: 	}
 2298: 	$request->print($toGrade);
 2299: 	return;
 2300:     } else {
 2301: 	$request->print('</div>'."\n");
 2302:     }
 2303: 
 2304:     # essay grading message center
 2305:     if ($env{'form.handgrade'} eq 'yes') {
 2306: 	my $result='<div class="LC_grade_message_center">';
 2307:     
 2308: 	$result.='<div class="LC_grade_message_center_header">'.
 2309: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2310: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2311: 	my $msgfor = $givenn.' '.$lastname;
 2312: 	if (scalar(@$col_fullnames) > 0) {
 2313: 	    my $lastone = pop(@$col_fullnames);
 2314: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2315: 	}
 2316: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2317: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2318: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2319: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2320: 	    ',\''.$msgfor.'\');" target="_self">'.
 2321: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2322: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2323: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2324: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2325: 	    '<br />&nbsp;('.
 2326: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2327: 	$result.='</div></div>';
 2328: 	$request->print($result);
 2329:     }
 2330: 
 2331:     my %seen = ();
 2332:     my @partlist;
 2333:     my @gradePartRespid;
 2334:     my @part_response_id = &flatten_responseType($responseType);
 2335:     $request->print('<div class="LC_grade_assign">'.
 2336: 		    
 2337: 		    '<div class="LC_grade_assign_header">'.
 2338: 		    &mt('Assign Grades').'</div>'.
 2339: 		    '<div class="LC_grade_assign_body">');
 2340:     foreach my $part_response_id (@part_response_id) {
 2341:     	my ($partid,$respid) = @{ $part_response_id };
 2342: 	my $part_resp = join('_',@{ $part_response_id });
 2343: 	next if ($seen{$partid} > 0);
 2344: 	$seen{$partid}++;
 2345: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2346: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2347: 	push(@partlist,$partid);
 2348: 	push(@gradePartRespid,$partid.'.'.$respid);
 2349: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2350:     }
 2351:     $request->print('</div></div>');
 2352: 
 2353:     $request->print('<div class="LC_grade_info_links">');
 2354:     if ($perm{'vgr'}) {
 2355: 	$request->print(
 2356: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2357: 						   $uname,$udom,'check'));
 2358:     }
 2359:     if ($perm{'opa'}) {
 2360: 	$request->print(
 2361: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2362: 					 $uname,$udom,$symb,'check'));
 2363:     }
 2364:     $request->print('</div>');
 2365: 
 2366:     $result='<input type="hidden" name="partlist'.$counter.
 2367: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2368:     $result.='<input type="hidden" name="gradePartRespid'.
 2369: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2370:     my $ctr = 0;
 2371:     while ($ctr < scalar(@partlist)) {
 2372: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2373: 	    $partlist[$ctr].'" />'."\n";
 2374: 	$ctr++;
 2375:     }
 2376:     $request->print($result.''."\n");
 2377: 
 2378: # Done with printing info for one student
 2379: 
 2380:     $request->print('</div>');#LC_grade_show_user_body
 2381:     $request->print('</div>');#LC_grade_show_user
 2382: 
 2383: 
 2384:     # print end of form
 2385:     if ($counter == $total) {
 2386: 	my $endform='<table border="0"><tr><td>'."\n";
 2387: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2388: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2389: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2390: 	my $ntstu ='<select name="NTSTU">'.
 2391: 	    '<option>1</option><option>2</option>'.
 2392: 	    '<option>3</option><option>5</option>'.
 2393: 	    '<option>7</option><option>10</option></select>'."\n";
 2394: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2395: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2396: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2397: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2398: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2399: 	    '<input type="button" value="'.&mt('Next').'" '.
 2400: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2401: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2402:         $endform.="<input type='hidden' value='".&get_increment().
 2403:             "' name='increment' />";
 2404: 	$endform.='</td></tr></table></form>';
 2405: 	$endform.=&show_grading_menu_form($symb);
 2406: 	$request->print($endform);
 2407:     }
 2408:     return '';
 2409: }
 2410: 
 2411: sub check_collaborators {
 2412:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2413:     my ($result,@col_fullnames);
 2414:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2415:     foreach my $part (keys(%$handgrade)) {
 2416: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2417: 					'.maxcollaborators',
 2418: 					$symb,$udom,$uname);
 2419: 	next if ($ncol <= 0);
 2420: 	$part =~ s/\_/\./g;
 2421: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2422: 	my (@good_collaborators, @bad_collaborators);
 2423: 	foreach my $possible_collaborator
 2424: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2425: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2426: 	    next if ($possible_collaborator eq '');
 2427: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2428: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2429: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2430: 	    # Doing this grep allows 'fuzzy' specification
 2431: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2432: 			       keys(%$classlist));
 2433: 	    if (! scalar(@matches)) {
 2434: 		push(@bad_collaborators, $possible_collaborator);
 2435: 	    } else {
 2436: 		push(@good_collaborators, @matches);
 2437: 	    }
 2438: 	}
 2439: 	if (scalar(@good_collaborators) != 0) {
 2440: 	    $result.='<br />'.&mt('Collaborators: ');
 2441: 	    foreach my $name (@good_collaborators) {
 2442: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2443: 		push(@col_fullnames, $givenn.' '.$lastname);
 2444: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2445: 	    }
 2446: 	    $result.='<br />'."\n";
 2447: 	    my ($part)=split(/\./,$part);
 2448: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2449: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2450: 		"\n";
 2451: 	}
 2452: 	if (scalar(@bad_collaborators) > 0) {
 2453: 	    $result.='<div class="LC_warning">';
 2454: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2455: 	    $result .= '</div>';
 2456: 	}         
 2457: 	if (scalar(@bad_collaborators > $ncol)) {
 2458: 	    $result .= '<div class="LC_warning">';
 2459: 	    $result .= &mt('This student has submitted too many '.
 2460: 		'collaborators.  Maximum is [_1].',$ncol);
 2461: 	    $result .= '</div>';
 2462: 	}
 2463:     }
 2464:     return ($result,$fullname,\@col_fullnames);
 2465: }
 2466: 
 2467: #--- Retrieve the last submission for all the parts
 2468: sub get_last_submission {
 2469:     my ($returnhash)=@_;
 2470:     my (@string,$timestamp);
 2471:     if ($$returnhash{'version'}) {
 2472: 	my %lasthash=();
 2473: 	my ($version);
 2474: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2475: 	    foreach my $key (sort(split(/\:/,
 2476: 					$$returnhash{$version.':keys'}))) {
 2477: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2478: 		$timestamp = 
 2479: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2480: 	    }
 2481: 	}
 2482: 	foreach my $key (keys(%lasthash)) {
 2483: 	    next if ($key !~ /\.submission$/);
 2484: 
 2485: 	    my ($partid,$foo) = split(/submission$/,$key);
 2486: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2487: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2488: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2489: 	}
 2490:     }
 2491:     if (!@string) {
 2492: 	$string[0] =
 2493: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2494:     }
 2495:     return (\@string,\$timestamp);
 2496: }
 2497: 
 2498: #--- High light keywords, with style choosen by user.
 2499: sub keywords_highlight {
 2500:     my $string    = shift;
 2501:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2502:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2503:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2504:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2505:     foreach my $keyword (@keylist) {
 2506: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2507:     }
 2508:     return $string;
 2509: }
 2510: 
 2511: #--- Called from submission routine
 2512: sub processHandGrade {
 2513:     my ($request) = shift;
 2514:     my $symb   = &get_symb($request);
 2515:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2516:     my $button = $env{'form.gradeOpt'};
 2517:     my $ngrade = $env{'form.NCT'};
 2518:     my $ntstu  = $env{'form.NTSTU'};
 2519:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2520:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2521: 
 2522:     if ($button eq 'Save & Next') {
 2523: 	my $ctr = 0;
 2524: 	while ($ctr < $ngrade) {
 2525: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2526: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2527: 	    if ($errorflag eq 'no_score') {
 2528: 		$ctr++;
 2529: 		next;
 2530: 	    }
 2531: 	    if ($errorflag eq 'not_allowed') {
 2532: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2533: 		$ctr++;
 2534: 		next;
 2535: 	    }
 2536: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2537: 	    my ($subject,$message,$msgstatus) = ('','','');
 2538: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2539:             my ($feedurl,$showsymb) =
 2540: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2541: 	    my $messagetail;
 2542: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2543: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2544: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2545: 		$subject.=' ['.$restitle.']';
 2546: 		my (@msgnum) = split(/,/,$includemsg);
 2547: 		foreach (@msgnum) {
 2548: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2549: 		}
 2550: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2551: 		if ($env{'form.withgrades'.$ctr}) {
 2552: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2553: 		    $messagetail = " for <a href=\"".
 2554: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2555: 		}
 2556: 		$msgstatus = 
 2557:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2558: 						     $message.$messagetail,
 2559:                                                      undef,$feedurl,undef,
 2560:                                                      undef,undef,$showsymb,
 2561:                                                      $restitle);
 2562: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2563: 				$msgstatus);
 2564: 	    }
 2565: 	    if ($env{'form.collaborator'.$ctr}) {
 2566: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2567: 		foreach my $collabstr (@collabstrs) {
 2568: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2569: 		    foreach my $collaborator (@collaborators) {
 2570: 			my ($errorflag,$pts,$wgt) = 
 2571: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2572: 					   $env{'form.unamedom'.$ctr},$part);
 2573: 			if ($errorflag eq 'not_allowed') {
 2574: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2575: 			    next;
 2576: 			} elsif ($message ne '') {
 2577: 			    my ($baseurl,$showsymb) = 
 2578: 				&get_feedurl_and_symb($symb,$collaborator,
 2579: 						      $udom);
 2580: 			    if ($env{'form.withgrades'.$ctr}) {
 2581: 				$messagetail = " for <a href=\"".
 2582:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2583: 			    }
 2584: 			    $msgstatus = 
 2585: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2586: 			}
 2587: 		    }
 2588: 		}
 2589: 	    }
 2590: 	    $ctr++;
 2591: 	}
 2592:     }
 2593: 
 2594:     if ($env{'form.handgrade'} eq 'yes') {
 2595: 	# Keywords sorted in alphabatical order
 2596: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2597: 	my %keyhash = ();
 2598: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2599: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2600: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2601: 	$env{'form.keywords'} = join(' ',@keywords);
 2602: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2603: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2604: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2605: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2606: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2607: 
 2608: 	# message center - Order of message gets changed. Blank line is eliminated.
 2609: 	# New messages are saved in env for the next student.
 2610: 	# All messages are saved in nohist_handgrade.db
 2611: 	my ($ctr,$idx) = (1,1);
 2612: 	while ($ctr <= $env{'form.savemsgN'}) {
 2613: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2614: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2615: 		$idx++;
 2616: 	    }
 2617: 	    $ctr++;
 2618: 	}
 2619: 	$ctr = 0;
 2620: 	while ($ctr < $ngrade) {
 2621: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2622: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2623: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2624: 		$idx++;
 2625: 	    }
 2626: 	    $ctr++;
 2627: 	}
 2628: 	$env{'form.savemsgN'} = --$idx;
 2629: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2630: 	my $putresult = &Apache::lonnet::put
 2631: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2632:     }
 2633:     # Called by Save & Refresh from Highlight Attribute Window
 2634:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2635:     if ($env{'form.refresh'} eq 'on') {
 2636: 	my ($ctr,$total) = (0,0);
 2637: 	while ($ctr < $ngrade) {
 2638: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2639: 	    $ctr++;
 2640: 	}
 2641: 	$env{'form.NTSTU'}=$ngrade;
 2642: 	$ctr = 0;
 2643: 	while ($ctr < $total) {
 2644: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2645: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2646: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2647: 	    &submission($request,$ctr,$total-1);
 2648: 	    $ctr++;
 2649: 	}
 2650: 	return '';
 2651:     }
 2652: 
 2653: # Go directly to grade student - from submission or link from chart page
 2654:     if ($button eq 'Grade Student') {
 2655: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2656: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2657: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2658: 	$env{'form.fullname'} = $$fullname{$processUser};
 2659: 	&submission($request,0,0);
 2660: 	return '';
 2661:     }
 2662: 
 2663:     # Get the next/previous one or group of students
 2664:     my $firststu = $env{'form.unamedom0'};
 2665:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2666:     my $ctr = 2;
 2667:     while ($laststu eq '') {
 2668: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2669: 	$ctr++;
 2670: 	$laststu = $firststu if ($ctr > $ngrade);
 2671:     }
 2672: 
 2673:     my (@parsedlist,@nextlist);
 2674:     my ($nextflg) = 0;
 2675:     foreach my $item (sort 
 2676: 	     {
 2677: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2678: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2679: 		 }
 2680: 		 return $a cmp $b;
 2681: 	     } (keys(%$fullname))) {
 2682: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2683: 	    push(@parsedlist,$item);
 2684: 	}
 2685: 	$nextflg = 1 if ($item eq $laststu);
 2686: 	if ($button eq 'Previous') {
 2687: 	    last if ($item eq $firststu);
 2688: 	    push(@parsedlist,$item);
 2689: 	}
 2690:     }
 2691:     $ctr = 0;
 2692:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2693:     my ($partlist) = &response_type($symb);
 2694:     foreach my $student (@parsedlist) {
 2695: 	my $submitonly=$env{'form.submitonly'};
 2696: 	my ($uname,$udom) = split(/:/,$student);
 2697: 	
 2698: 	if ($submitonly eq 'queued') {
 2699: 	    my %queue_status = 
 2700: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2701: 							$udom,$uname);
 2702: 	    next if (!defined($queue_status{'gradingqueue'}));
 2703: 	}
 2704: 
 2705: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2706: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2707: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2708: 	    my $submitted = 0;
 2709: 	    my $ungraded = 0;
 2710: 	    my $incorrect = 0;
 2711: 	    foreach my $item (keys(%status)) {
 2712: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2713: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2714: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2715: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2716: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2717: 		    $submitted = 0;
 2718: 		}
 2719: 	    }
 2720: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2721: 				     $submitonly eq 'incorrect' ||
 2722: 				     $submitonly eq 'graded'));
 2723: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2724: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2725: 	}
 2726: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2727: 	last if ($ctr == $ntstu);
 2728: 	$ctr++;
 2729:     }
 2730: 
 2731:     $ctr = 0;
 2732:     my $total = scalar(@nextlist)-1;
 2733: 
 2734:     foreach (sort(@nextlist)) {
 2735: 	my ($uname,$udom,$submitter) = split(/:/);
 2736: 	$env{'form.student'}  = $uname;
 2737: 	$env{'form.userdom'}  = $udom;
 2738: 	$env{'form.fullname'} = $$fullname{$_};
 2739: 	&submission($request,$ctr,$total);
 2740: 	$ctr++;
 2741:     }
 2742:     if ($total < 0) {
 2743: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2744: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2745: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2746: 	$the_end.=&show_grading_menu_form($symb);
 2747: 	$request->print($the_end);
 2748:     }
 2749:     return '';
 2750: }
 2751: 
 2752: #---- Save the score and award for each student, if changed
 2753: sub saveHandGrade {
 2754:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2755:     my @version_parts;
 2756:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2757: 					   $env{'request.course.id'});
 2758:     if (!&canmodify($usec)) { return('not_allowed'); }
 2759:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2760:     my @parts_graded;
 2761:     my %newrecord  = ();
 2762:     my ($pts,$wgt) = ('','');
 2763:     my %aggregate = ();
 2764:     my $aggregateflag = 0;
 2765:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2766:     foreach my $new_part (@parts) {
 2767: 	#collaborator ($submi may vary for different parts
 2768: 	if ($submitter && $new_part ne $part) { next; }
 2769: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2770: 	if ($dropMenu eq 'excused') {
 2771: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2772: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2773: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2774: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2775: 		}
 2776: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2777: 	    }
 2778: 	} elsif ($dropMenu eq 'reset status'
 2779: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2780: 	    foreach my $key (keys(%record)) {
 2781: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2782: 	    }
 2783: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2784: 		"$env{'user.name'}:$env{'user.domain'}";
 2785:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2786: 
 2787:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2788: 					       [$new_part]);
 2789:             my $aggtries =$totaltries;
 2790:             if ($last_resets{$new_part}) {
 2791:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2792: 					   $new_part);
 2793:             }
 2794: 
 2795:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2796:             if ($aggtries > 0) {
 2797:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2798:                 $aggregateflag = 1;
 2799:             }
 2800: 	} elsif ($dropMenu eq '') {
 2801: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2802: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2803: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2804: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2805: 		next;
 2806: 	    }
 2807: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2808: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2809: 	    my $partial= $pts/$wgt;
 2810: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2811: 		#do not update score for part if not changed.
 2812:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2813: 		next;
 2814: 	    } else {
 2815: 	        push(@parts_graded,$new_part);
 2816: 	    }
 2817: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2818: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2819: 	    }
 2820: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2821: 	    if ($partial == 0) {
 2822: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2823: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2824: 		}
 2825: 	    } else {
 2826: 		if ($record{$reckey} ne 'correct_by_override') {
 2827: 		    $newrecord{$reckey} = 'correct_by_override';
 2828: 		}
 2829: 	    }	    
 2830: 	    if ($submitter && 
 2831: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2832: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2833: 	    }
 2834: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2835: 		"$env{'user.name'}:$env{'user.domain'}";
 2836: 	}
 2837: 	# unless problem has been graded, set flag to version the submitted files
 2838: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2839: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2840: 	        $dropMenu eq 'reset status')
 2841: 	   {
 2842: 	    push(@version_parts,$new_part);
 2843: 	}
 2844:     }
 2845:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2846:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2847: 
 2848:     if (%newrecord) {
 2849:         if (@version_parts) {
 2850:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2851:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2852: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2853: 	    foreach my $new_part (@version_parts) {
 2854: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2855: 				$new_part,\%newrecord);
 2856: 	    }
 2857:         }
 2858: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2859: 				$env{'request.course.id'},$domain,$stuname);
 2860: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2861: 				     $cdom,$cnum,$domain,$stuname);
 2862:     }
 2863:     if ($aggregateflag) {
 2864:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2865: 			      $cdom,$cnum);
 2866:     }
 2867:     return ('',$pts,$wgt);
 2868: }
 2869: 
 2870: sub check_and_remove_from_queue {
 2871:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2872:     my @ungraded_parts;
 2873:     foreach my $part (@{$parts}) {
 2874: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2875: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2876: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2877: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2878: 		) {
 2879: 	    push(@ungraded_parts, $part);
 2880: 	}
 2881:     }
 2882:     if ( !@ungraded_parts ) {
 2883: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2884: 					       $cnum,$domain,$stuname);
 2885:     }
 2886: }
 2887: 
 2888: sub handback_files {
 2889:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2890:     my $portfolio_root = '/userfiles/portfolio';
 2891:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2892: 
 2893:     my @part_response_id = &flatten_responseType($responseType);
 2894:     foreach my $part_response_id (@part_response_id) {
 2895:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2896: 	my $part_resp = join('_',@{ $part_response_id });
 2897:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2898:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2899:                 my $file_counter = 1;
 2900: 		my $file_msg;
 2901:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2902:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2903:                     my ($directory,$answer_file) = 
 2904:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2905:                     my ($answer_name,$answer_ver,$answer_ext) =
 2906: 		        &file_name_version_ext($answer_file);
 2907: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2908:                     my $getpropath = 1;
 2909: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2910: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2911:                     # fix file name
 2912:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2913:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2914:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2915:             	                                $save_file_name);
 2916:                     if ($result !~ m|^/uploaded/|) {
 2917:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2918:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2919:                     } else {
 2920:                         # mark the file as read only
 2921:                         my @files = ($save_file_name);
 2922:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2923:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2924: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2925: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2926: 			}
 2927:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2928: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2929: 
 2930:                     }
 2931:                     $request->print("<br />".$fname." will be the uploaded file name");
 2932:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2933:                     $file_counter++;
 2934:                 }
 2935: 		my $subject = "File Handed Back by Instructor ";
 2936: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2937: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2938: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2939: 		$message .= " and can be found in your portfolio space.";
 2940: 		my ($feedurl,$showsymb) = 
 2941: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2942:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2943: 		my $msgstatus = 
 2944:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2945: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2946:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2947:             }
 2948:         }
 2949:     return;
 2950: }
 2951: 
 2952: sub get_feedurl_and_symb {
 2953:     my ($symb,$uname,$udom) = @_;
 2954:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2955:     $url = &Apache::lonnet::clutter($url);
 2956:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2957: 					$symb,$udom,$uname);
 2958:     if ($encrypturl =~ /^yes$/i) {
 2959: 	&Apache::lonenc::encrypted(\$url,1);
 2960: 	&Apache::lonenc::encrypted(\$symb,1);
 2961:     }
 2962:     return ($url,$symb);
 2963: }
 2964: 
 2965: sub get_submitted_files {
 2966:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2967:     my @files;
 2968:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2969:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2970:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2971:     	    push(@files,$file_url.$file);
 2972:         }
 2973:     }
 2974:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2975:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2976:     }
 2977:     return (\@files);
 2978: }
 2979: 
 2980: # ----------- Provides number of tries since last reset.
 2981: sub get_num_tries {
 2982:     my ($record,$last_reset,$part) = @_;
 2983:     my $timestamp = '';
 2984:     my $num_tries = 0;
 2985:     if ($$record{'version'}) {
 2986:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2987:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2988:                 $timestamp = $$record{$version.':timestamp'};
 2989:                 if ($timestamp > $last_reset) {
 2990:                     $num_tries ++;
 2991:                 } else {
 2992:                     last;
 2993:                 }
 2994:             }
 2995:         }
 2996:     }
 2997:     return $num_tries;
 2998: }
 2999: 
 3000: # ----------- Determine decrements required in aggregate totals 
 3001: sub decrement_aggs {
 3002:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3003:     my %decrement = (
 3004:                         attempts => 0,
 3005:                         users => 0,
 3006:                         correct => 0
 3007:                     );
 3008:     $decrement{'attempts'} = $aggtries;
 3009:     if ($solvedstatus =~ /^correct/) {
 3010:         $decrement{'correct'} = 1;
 3011:     }
 3012:     if ($aggtries == $totaltries) {
 3013:         $decrement{'users'} = 1;
 3014:     }
 3015:     foreach my $type (keys(%decrement)) {
 3016:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3017:     }
 3018:     return;
 3019: }
 3020: 
 3021: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3022: sub get_last_resets {
 3023:     my ($symb,$courseid,$partids) =@_;
 3024:     my %last_resets;
 3025:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3026:     my $cname = $env{'course.'.$courseid.'.num'};
 3027:     my @keys;
 3028:     foreach my $part (@{$partids}) {
 3029: 	push(@keys,"$symb\0$part\0resettime");
 3030:     }
 3031:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3032: 				     $cdom,$cname);
 3033:     foreach my $part (@{$partids}) {
 3034: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3035:     }
 3036:     return %last_resets;
 3037: }
 3038: 
 3039: # ----------- Handles creating versions for portfolio files as answers
 3040: sub version_portfiles {
 3041:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3042:     my $version_parts = join('|',@$v_flag);
 3043:     my @returned_keys;
 3044:     my $parts = join('|', @$parts_graded);
 3045:     my $portfolio_root = '/userfiles/portfolio';
 3046:     foreach my $key (keys(%$record)) {
 3047:         my $new_portfiles;
 3048:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3049:             my @versioned_portfiles;
 3050:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3051:             foreach my $file (@portfiles) {
 3052:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3053:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3054: 		my ($answer_name,$answer_ver,$answer_ext) =
 3055: 		    &file_name_version_ext($answer_file);
 3056:                 my $getpropath = 1;    
 3057:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3058:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3059:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3060:                 if ($new_answer ne 'problem getting file') {
 3061:                     push(@versioned_portfiles, $directory.$new_answer);
 3062:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3063:                         [$directory.$new_answer],
 3064:                         [$symb,$env{'request.course.id'},'graded']);
 3065:                 }
 3066:             }
 3067:             $$record{$key} = join(',',@versioned_portfiles);
 3068:             push(@returned_keys,$key);
 3069:         }
 3070:     } 
 3071:     return (@returned_keys);   
 3072: }
 3073: 
 3074: sub get_next_version {
 3075:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3076:     my $version;
 3077:     foreach my $row (@$dir_list) {
 3078:         my ($file) = split(/\&/,$row,2);
 3079:         my ($file_name,$file_version,$file_ext) =
 3080: 	    &file_name_version_ext($file);
 3081:         if (($file_name eq $answer_name) && 
 3082: 	    ($file_ext eq $answer_ext)) {
 3083:                 # gets here if filename and extension match, regardless of version
 3084:                 if ($file_version ne '') {
 3085:                 # a versioned file is found  so save it for later
 3086:                 if ($file_version > $version) {
 3087: 		    $version = $file_version;
 3088: 	        }
 3089:             }
 3090:         }
 3091:     } 
 3092:     $version ++;
 3093:     return($version);
 3094: }
 3095: 
 3096: sub version_selected_portfile {
 3097:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3098:     my ($answer_name,$answer_ver,$answer_ext) =
 3099:         &file_name_version_ext($file_name);
 3100:     my $new_answer;
 3101:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3102:     if($env{'form.copy'} eq '-1') {
 3103:         $new_answer = 'problem getting file';
 3104:     } else {
 3105:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3106:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3107:                             $stu_name,$domain,'copy',
 3108: 		        '/portfolio'.$directory.$new_answer);
 3109:     }    
 3110:     return ($new_answer);
 3111: }
 3112: 
 3113: sub file_name_version_ext {
 3114:     my ($file)=@_;
 3115:     my @file_parts = split(/\./, $file);
 3116:     my ($name,$version,$ext);
 3117:     if (@file_parts > 1) {
 3118: 	$ext=pop(@file_parts);
 3119: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3120: 	    $version=pop(@file_parts);
 3121: 	}
 3122: 	$name=join('.',@file_parts);
 3123:     } else {
 3124: 	$name=join('.',@file_parts);
 3125:     }
 3126:     return($name,$version,$ext);
 3127: }
 3128: 
 3129: #--------------------------------------------------------------------------------------
 3130: #
 3131: #-------------------------- Next few routines handles grading by section or whole class
 3132: #
 3133: #--- Javascript to handle grading by section or whole class
 3134: sub viewgrades_js {
 3135:     my ($request) = shift;
 3136: 
 3137:     $request->print(<<VIEWJAVASCRIPT);
 3138: <script type="text/javascript" language="javascript">
 3139:    function writePoint(partid,weight,point) {
 3140: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3141: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3142: 	if (point == "textval") {
 3143: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3144: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3145: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3146: 		var resetbox = false;
 3147: 		for (var i=0; i<radioButton.length; i++) {
 3148: 		    if (radioButton[i].checked) {
 3149: 			textbox.value = i;
 3150: 			resetbox = true;
 3151: 		    }
 3152: 		}
 3153: 		if (!resetbox) {
 3154: 		    textbox.value = "";
 3155: 		}
 3156: 		return;
 3157: 	    }
 3158: 	    if (parseFloat(point) > parseFloat(weight)) {
 3159: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3160: 				   ") greater than the weight for the part. Accept?");
 3161: 		if (resp == false) {
 3162: 		    textbox.value = "";
 3163: 		    return;
 3164: 		}
 3165: 	    }
 3166: 	    for (var i=0; i<radioButton.length; i++) {
 3167: 		radioButton[i].checked=false;
 3168: 		if (parseFloat(point) == i) {
 3169: 		    radioButton[i].checked=true;
 3170: 		}
 3171: 	    }
 3172: 
 3173: 	} else {
 3174: 	    textbox.value = parseFloat(point);
 3175: 	}
 3176: 	for (i=0;i<document.classgrade.total.value;i++) {
 3177: 	    var user = document.classgrade["ctr"+i].value;
 3178: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3179: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3180: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3181: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3182: 	    if (saveval != "correct") {
 3183: 		scorename.value = point;
 3184: 		if (selname[0].selected != true) {
 3185: 		    selname[0].selected = true;
 3186: 		}
 3187: 	    }
 3188: 	}
 3189: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3190:     }
 3191: 
 3192:     function writeRadText(partid,weight) {
 3193: 	var selval   = document.classgrade["SELVAL_"+partid];
 3194: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3195:         var override = document.classgrade["FORCE_"+partid].checked;
 3196: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3197: 	if (selval[1].selected || selval[2].selected) {
 3198: 	    for (var i=0; i<radioButton.length; i++) {
 3199: 		radioButton[i].checked=false;
 3200: 
 3201: 	    }
 3202: 	    textbox.value = "";
 3203: 
 3204: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3205: 		var user = document.classgrade["ctr"+i].value;
 3206: 		user = user.replace(new RegExp(':', 'g'),"_");
 3207: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3208: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3209: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3210: 		if ((saveval != "correct") || override) {
 3211: 		    scorename.value = "";
 3212: 		    if (selval[1].selected) {
 3213: 			selname[1].selected = true;
 3214: 		    } else {
 3215: 			selname[2].selected = true;
 3216: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3217: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3218: 		    }
 3219: 		}
 3220: 	    }
 3221: 	} else {
 3222: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3223: 		var user = document.classgrade["ctr"+i].value;
 3224: 		user = user.replace(new RegExp(':', 'g'),"_");
 3225: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3226: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3227: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3228: 		if ((saveval != "correct") || override) {
 3229: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3230: 		    selname[0].selected = true;
 3231: 		}
 3232: 	    }
 3233: 	}	    
 3234:     }
 3235: 
 3236:     function changeSelect(partid,user) {
 3237: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3238: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3239: 	var point  = textbox.value;
 3240: 	var weight = document.classgrade["weight_"+partid].value;
 3241: 
 3242: 	if (isNaN(point) || parseFloat(point) < 0) {
 3243: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3244: 	    textbox.value = "";
 3245: 	    return;
 3246: 	}
 3247: 	if (parseFloat(point) > parseFloat(weight)) {
 3248: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3249: 			       ") greater than the weight of the part. Accept?");
 3250: 	    if (resp == false) {
 3251: 		textbox.value = "";
 3252: 		return;
 3253: 	    }
 3254: 	}
 3255: 	selval[0].selected = true;
 3256:     }
 3257: 
 3258:     function changeOneScore(partid,user) {
 3259: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3260: 	if (selval[1].selected || selval[2].selected) {
 3261: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3262: 	    if (selval[2].selected) {
 3263: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3264: 	    }
 3265:         }
 3266:     }
 3267: 
 3268:     function resetEntry(numpart) {
 3269: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3270: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3271: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3272: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3273: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3274: 	    for (var i=0; i<radioButton.length; i++) {
 3275: 		radioButton[i].checked=false;
 3276: 
 3277: 	    }
 3278: 	    textbox.value = "";
 3279: 	    selval[0].selected = true;
 3280: 
 3281: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3282: 		var user = document.classgrade["ctr"+i].value;
 3283: 		user = user.replace(new RegExp(':', 'g'),"_");
 3284: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3285: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3286: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3287: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3288: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3289: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3290: 		if (saveselval == "excused") {
 3291: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3292: 		} else {
 3293: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3294: 		}
 3295: 	    }
 3296: 	}
 3297:     }
 3298: 
 3299: </script>
 3300: VIEWJAVASCRIPT
 3301: }
 3302: 
 3303: #--- show scores for a section or whole class w/ option to change/update a score
 3304: sub viewgrades {
 3305:     my ($request) = shift;
 3306:     &viewgrades_js($request);
 3307: 
 3308:     my ($symb) = &get_symb($request);
 3309:     #need to make sure we have the correct data for later EXT calls, 
 3310:     #thus invalidate the cache
 3311:     &Apache::lonnet::devalidatecourseresdata(
 3312:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3313:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3314:     &Apache::lonnet::clear_EXT_cache_status();
 3315: 
 3316:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3317:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3318: 
 3319:     #view individual student submission form - called using Javascript viewOneStudent
 3320:     $result.=&jscriptNform($symb);
 3321: 
 3322:     #beginning of class grading form
 3323:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3324:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3325: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3326: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3327: 	&build_section_inputs().
 3328: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3329: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3330: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3331: 
 3332:     my $sectionClass;
 3333:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3334:     if ($env{'form.section'} eq 'all') {
 3335: 	$sectionClass='Class';
 3336:     } elsif ($env{'form.section'} eq 'none') {
 3337: 	$sectionClass='Students in no Section';
 3338:     } else {
 3339: 	$sectionClass='Students in Section(s) [_1]';
 3340:     }
 3341:     $result.=
 3342: 	'<h3>'.
 3343: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3344:     $result.= &Apache::loncommon::start_data_table();
 3345:     #radio buttons/text box for assigning points for a section or class.
 3346:     #handles different parts of a problem
 3347:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3348:     my %weight = ();
 3349:     my $ctsparts = 0;
 3350:     my %seen = ();
 3351:     my @part_response_id = &flatten_responseType($responseType);
 3352:     foreach my $part_response_id (@part_response_id) {
 3353:     	my ($partid,$respid) = @{ $part_response_id };
 3354: 	my $part_resp = join('_',@{ $part_response_id });
 3355: 	next if $seen{$partid};
 3356: 	$seen{$partid}++;
 3357: 	my $handgrade=$$handgrade{$part_resp};
 3358: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3359: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3360: 
 3361: 	my $display_part=&get_display_part($partid,$symb);
 3362: 	my $radio.='<table border="0"><tr>';  
 3363: 	my $ctr = 0;
 3364: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3365: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3366: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3367: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3368: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3369: 	    $ctr++;
 3370: 	}
 3371: 	$radio.='</tr></table>';
 3372: 	my $line = '<input type="text" name="TEXTVAL_'.
 3373: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3374: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3375: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3376: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3377: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3378: 		$weight{$partid}.')"> '.
 3379: 	    '<option selected="selected"> </option>'.
 3380: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3381: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3382: 	    '</select></td>'.
 3383:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3384: 	$line.='<input type="hidden" name="partid_'.
 3385: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3386: 	$line.='<input type="hidden" name="weight_'.
 3387: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3388: 
 3389: 	$result.=
 3390: 	    &Apache::loncommon::start_data_table_row()."\n".
 3391: 	    &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line).
 3392: 	    &Apache::loncommon::end_data_table_row()."\n";
 3393: 	$ctsparts++;
 3394:     }
 3395:     $result.=&Apache::loncommon::end_data_table()."\n".
 3396: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3397:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3398: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3399: 
 3400:     #table listing all the students in a section/class
 3401:     #header of table
 3402:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3403: 			 $section_display).'</h3>';
 3404:     $result.= &Apache::loncommon::start_data_table().
 3405: 	&Apache::loncommon::start_data_table_header_row().
 3406: 	'<th>'.&mt('No.').'</th>'.
 3407: 	'<th>'.&nameUserString('header')."</th>\n";
 3408:     my (@parts) = sort(&getpartlist($symb));
 3409:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3410:     my @partids = ();
 3411:     foreach my $part (@parts) {
 3412: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3413: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3414: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3415: 	my ($partid) = &split_part_type($part);
 3416:         push(@partids,$partid);
 3417: 	my $display_part=&get_display_part($partid,$symb);
 3418: 	if ($display =~ /^Partial Credit Factor/) {
 3419: 	    $result.='<th>'.
 3420: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3421: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3422: 	    next;
 3423: 	    
 3424: 	} else {
 3425: 	    if ($display =~ /Problem Status/) {
 3426: 		my $grade_status_mt = &mt('Grade Status');
 3427: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3428: 	    }
 3429: 	    my $part_mt = &mt('Part:');
 3430: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3431: 	}
 3432: 
 3433: 	$result.='<th>'.$display.'</th>'."\n";
 3434:     }
 3435:     $result.=&Apache::loncommon::end_data_table_header_row();
 3436: 
 3437:     my %last_resets = 
 3438: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3439: 
 3440:     #get info for each student
 3441:     #list all the students - with points and grade status
 3442:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3443:     my $ctr = 0;
 3444:     foreach (sort 
 3445: 	     {
 3446: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3447: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3448: 		 }
 3449: 		 return $a cmp $b;
 3450: 	     } (keys(%$fullname))) {
 3451: 	$ctr++;
 3452: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3453: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3454:     }
 3455:     $result.=&Apache::loncommon::end_data_table();
 3456:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3457:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3458: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3459:     if (scalar(%$fullname) eq 0) {
 3460: 	my $colspan=3+scalar(@parts);
 3461: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3462:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3463: 	$result='<span class="LC_warning">'.
 3464: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3465: 	        $section_display, $stu_status).
 3466: 	    '</span>';
 3467:     }
 3468:     $result.=&show_grading_menu_form($symb);
 3469:     return $result;
 3470: }
 3471: 
 3472: #--- call by previous routine to display each student
 3473: sub viewstudentgrade {
 3474:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3475:     my ($uname,$udom) = split(/:/,$student);
 3476:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3477:     my %aggregates = (); 
 3478:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3479: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3480: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3481: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3482: 	'\');" target="_self">'.$fullname.'</a> '.
 3483: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3484:     $student=~s/:/_/; # colon doen't work in javascript for names
 3485:     foreach my $apart (@$parts) {
 3486: 	my ($part,$type) = &split_part_type($apart);
 3487: 	my $score=$record{"resource.$part.$type"};
 3488:         $result.='<td align="center">';
 3489:         my ($aggtries,$totaltries);
 3490:         unless (exists($aggregates{$part})) {
 3491: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3492: 
 3493: 	    $aggtries = $totaltries;
 3494:             if ($$last_resets{$part}) {  
 3495:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3496: 					   $part);
 3497:             }
 3498:             $result.='<input type="hidden" name="'.
 3499:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3500:             $result.='<input type="hidden" name="'.
 3501:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3502:             $aggregates{$part} = 1;
 3503:         }
 3504: 	if ($type eq 'awarded') {
 3505: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3506: 	    $result.='<input type="hidden" name="'.
 3507: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3508: 	    $result.='<input type="text" name="'.
 3509: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3510: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3511: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3512: 	} elsif ($type eq 'solved') {
 3513: 	    my ($status,$foo)=split(/_/,$score,2);
 3514: 	    $status = 'nothing' if ($status eq '');
 3515: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3516: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3517: 	    $result.='&nbsp;<select name="'.
 3518: 		'GD_'.$student.'_'.$part.'_solved" '.
 3519: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3520: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3521: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3522: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3523: 	    $result.="</select>&nbsp;</td>\n";
 3524: 	} else {
 3525: 	    $result.='<input type="hidden" name="'.
 3526: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3527: 		    "\n";
 3528: 	    $result.='<input type="text" name="'.
 3529: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3530: 		'value="'.$score.'" size="4" /></td>'."\n";
 3531: 	}
 3532:     }
 3533:     $result.=&Apache::loncommon::end_data_table_row();
 3534:     return $result;
 3535: }
 3536: 
 3537: #--- change scores for all the students in a section/class
 3538: #    record does not get update if unchanged
 3539: sub editgrades {
 3540:     my ($request) = @_;
 3541: 
 3542:     my $symb=&get_symb($request);
 3543:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3544:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3545:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3546:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3547: 
 3548:     my $result= &Apache::loncommon::start_data_table().
 3549: 	&Apache::loncommon::start_data_table_header_row().
 3550: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3551: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3552:     my %scoreptr = (
 3553: 		    'correct'  =>'correct_by_override',
 3554: 		    'incorrect'=>'incorrect_by_override',
 3555: 		    'excused'  =>'excused',
 3556: 		    'ungraded' =>'ungraded_attempted',
 3557: 		    'nothing'  => '',
 3558: 		    );
 3559:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3560: 
 3561:     my (@partid);
 3562:     my %weight = ();
 3563:     my %columns = ();
 3564:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3565: 
 3566:     my (@parts) = sort(&getpartlist($symb));
 3567:     my $header;
 3568:     while ($ctr < $env{'form.totalparts'}) {
 3569: 	my $partid = $env{'form.partid_'.$ctr};
 3570: 	push(@partid,$partid);
 3571: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3572: 	$ctr++;
 3573:     }
 3574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3575:     foreach my $partid (@partid) {
 3576: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3577: 	    '<th align="center">'.&mt('New Score').'</th>';
 3578: 	$columns{$partid}=2;
 3579: 	foreach my $stores (@parts) {
 3580: 	    my ($part,$type) = &split_part_type($stores);
 3581: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3582: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3583: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3584: 	    $display =~ s/\[Part: (\w)+\]//;
 3585: 	    $display =~ s/Number of Attempts/Tries/;
 3586: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3587: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3588: 	    $columns{$partid}+=2;
 3589: 	}
 3590:     }
 3591:     foreach my $partid (@partid) {
 3592: 	my $display_part=&get_display_part($partid,$symb);
 3593: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3594: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3595: 	    '</th>';
 3596: 
 3597:     }
 3598:     $result .= &Apache::loncommon::end_data_table_header_row().
 3599: 	&Apache::loncommon::start_data_table_header_row().
 3600: 	$header.
 3601: 	&Apache::loncommon::end_data_table_header_row();
 3602:     my @noupdate;
 3603:     my ($updateCtr,$noupdateCtr) = (1,1);
 3604:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3605: 	my $line;
 3606: 	my $user = $env{'form.ctr'.$i};
 3607: 	my ($uname,$udom)=split(/:/,$user);
 3608: 	my %newrecord;
 3609: 	my $updateflag = 0;
 3610: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3611: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3612: 	if (!&canmodify($usec)) {
 3613: 	    my $numcols=scalar(@partid)*4+2;
 3614: 	    push(@noupdate,
 3615: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3616: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3617: 	    next;
 3618: 	}
 3619:         my %aggregate = ();
 3620:         my $aggregateflag = 0;
 3621: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3622: 	foreach (@partid) {
 3623: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3624: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3625: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3626: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3627: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3628: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3629: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3630: 	    my $score;
 3631: 	    if ($partial eq '') {
 3632: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3633: 	    } elsif ($partial > 0) {
 3634: 		$score = 'correct_by_override';
 3635: 	    } elsif ($partial == 0) {
 3636: 		$score = 'incorrect_by_override';
 3637: 	    }
 3638: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3639: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3640: 
 3641: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3642: 		"$env{'user.name'}:$env{'user.domain'}";
 3643: 	    if ($dropMenu eq 'reset status' &&
 3644: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3645: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3646: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3647: 		$newrecord{'resource.'.$_.'.award'} = '';
 3648: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3649: 		$updateflag = 1;
 3650:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3651:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3652:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3653:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3654:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3655:                     $aggregateflag = 1;
 3656:                 }
 3657: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3658: 		$updateflag = 1;
 3659: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3660: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3661: 		$rec_update++;
 3662: 	    }
 3663: 
 3664: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3665: 		'<td align="center">'.$awarded.
 3666: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3667: 
 3668: 
 3669: 	    my $partid=$_;
 3670: 	    foreach my $stores (@parts) {
 3671: 		my ($part,$type) = &split_part_type($stores);
 3672: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3673: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3674: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3675: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3676: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3677: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3678: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3679: 		    $updateflag=1;
 3680: 		}
 3681: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3682: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3683: 	    }
 3684: 	}
 3685: 	$line.="\n";
 3686: 
 3687: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3688: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3689: 
 3690: 	if ($updateflag) {
 3691: 	    $count++;
 3692: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3693: 				    $udom,$uname);
 3694: 
 3695: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3696: 					      $cnum,$udom,$uname)) {
 3697: 		# need to figure out if should be in queue.
 3698: 		my %record =  
 3699: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3700: 					     $udom,$uname);
 3701: 		my $all_graded = 1;
 3702: 		my $none_graded = 1;
 3703: 		foreach my $part (@parts) {
 3704: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3705: 			$all_graded = 0;
 3706: 		    } else {
 3707: 			$none_graded = 0;
 3708: 		    }
 3709: 		}
 3710: 
 3711: 		if ($all_graded || $none_graded) {
 3712: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3713: 							   $symb,$cdom,$cnum,
 3714: 							   $udom,$uname);
 3715: 		}
 3716: 	    }
 3717: 
 3718: 	    $result.=&Apache::loncommon::start_data_table_row().
 3719: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3720: 		&Apache::loncommon::end_data_table_row();
 3721: 	    $updateCtr++;
 3722: 	} else {
 3723: 	    push(@noupdate,
 3724: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3725: 	    $noupdateCtr++;
 3726: 	}
 3727:         if ($aggregateflag) {
 3728:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3729: 				  $cdom,$cnum);
 3730:         }
 3731:     }
 3732:     if (@noupdate) {
 3733: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3734: 	my $numcols=scalar(@partid)*4+2;
 3735: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3736: 	    '<td align="center" colspan="'.$numcols.'">'.
 3737: 	    &mt('No Changes Occurred For the Students Below').
 3738: 	    '</td>'.
 3739: 	    &Apache::loncommon::end_data_table_row();
 3740: 	foreach my $line (@noupdate) {
 3741: 	    $result.=
 3742: 		&Apache::loncommon::start_data_table_row().
 3743: 		$line.
 3744: 		&Apache::loncommon::end_data_table_row();
 3745: 	}
 3746:     }
 3747:     $result .= &Apache::loncommon::end_data_table().
 3748: 	&show_grading_menu_form($symb);
 3749:     my $msg = '<p><b>'.
 3750: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3751: 	    $rec_update,$count).'</b><br />'.
 3752: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3753: 	'</b></p>';
 3754:     return $title.$msg.$result;
 3755: }
 3756: 
 3757: sub split_part_type {
 3758:     my ($partstr) = @_;
 3759:     my ($temp,@allparts)=split(/_/,$partstr);
 3760:     my $type=pop(@allparts);
 3761:     my $part=join('_',@allparts);
 3762:     return ($part,$type);
 3763: }
 3764: 
 3765: #------------- end of section for handling grading by section/class ---------
 3766: #
 3767: #----------------------------------------------------------------------------
 3768: 
 3769: 
 3770: #----------------------------------------------------------------------------
 3771: #
 3772: #-------------------------- Next few routines handles grading by csv upload
 3773: #
 3774: #--- Javascript to handle csv upload
 3775: sub csvupload_javascript_reverse_associate {
 3776:     my $error1=&mt('You need to specify the username or ID');
 3777:     my $error2=&mt('You need to specify at least one grading field');
 3778:   return(<<ENDPICK);
 3779:   function verify(vf) {
 3780:     var foundsomething=0;
 3781:     var founduname=0;
 3782:     var foundID=0;
 3783:     for (i=0;i<=vf.nfields.value;i++) {
 3784:       tw=eval('vf.f'+i+'.selectedIndex');
 3785:       if (i==0 && tw!=0) { foundID=1; }
 3786:       if (i==1 && tw!=0) { founduname=1; }
 3787:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3788:     }
 3789:     if (founduname==0 && foundID==0) {
 3790: 	alert('$error1');
 3791: 	return;
 3792:     }
 3793:     if (foundsomething==0) {
 3794: 	alert('$error2');
 3795: 	return;
 3796:     }
 3797:     vf.submit();
 3798:   }
 3799:   function flip(vf,tf) {
 3800:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3801:     var i;
 3802:     for (i=0;i<=vf.nfields.value;i++) {
 3803:       //can not pick the same destination field for both name and domain
 3804:       if (((i ==0)||(i ==1)) && 
 3805:           ((tf==0)||(tf==1)) && 
 3806:           (i!=tf) &&
 3807:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3808:         eval('vf.f'+i+'.selectedIndex=0;')
 3809:       }
 3810:     }
 3811:   }
 3812: ENDPICK
 3813: }
 3814: 
 3815: sub csvupload_javascript_forward_associate {
 3816:     my $error1=&mt('You need to specify the username or ID');
 3817:     my $error2=&mt('You need to specify at least one grading field');
 3818:   return(<<ENDPICK);
 3819:   function verify(vf) {
 3820:     var foundsomething=0;
 3821:     var founduname=0;
 3822:     var foundID=0;
 3823:     for (i=0;i<=vf.nfields.value;i++) {
 3824:       tw=eval('vf.f'+i+'.selectedIndex');
 3825:       if (tw==1) { foundID=1; }
 3826:       if (tw==2) { founduname=1; }
 3827:       if (tw>3) { foundsomething=1; }
 3828:     }
 3829:     if (founduname==0 && foundID==0) {
 3830: 	alert('$error1');
 3831: 	return;
 3832:     }
 3833:     if (foundsomething==0) {
 3834: 	alert('$error2');
 3835: 	return;
 3836:     }
 3837:     vf.submit();
 3838:   }
 3839:   function flip(vf,tf) {
 3840:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3841:     var i;
 3842:     //can not pick the same destination field twice
 3843:     for (i=0;i<=vf.nfields.value;i++) {
 3844:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3845:         eval('vf.f'+i+'.selectedIndex=0;')
 3846:       }
 3847:     }
 3848:   }
 3849: ENDPICK
 3850: }
 3851: 
 3852: sub csvuploadmap_header {
 3853:     my ($request,$symb,$datatoken,$distotal)= @_;
 3854:     my $javascript;
 3855:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3856: 	$javascript=&csvupload_javascript_reverse_associate();
 3857:     } else {
 3858: 	$javascript=&csvupload_javascript_forward_associate();
 3859:     }
 3860: 
 3861:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3862:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3863:     my $ignore=&mt('Ignore First Line');
 3864:     $symb = &Apache::lonenc::check_encrypt($symb);
 3865:     $request->print(<<ENDPICK);
 3866: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3867: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3868: $result
 3869: <hr />
 3870: <h3>Identify fields</h3>
 3871: Total number of records found in file: $distotal <hr />
 3872: Enter as many fields as you can. The system will inform you and bring you back
 3873: to this page if the data selected is insufficient to run your class.<hr />
 3874: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3875: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3876: <input type="hidden" name="associate"  value="" />
 3877: <input type="hidden" name="phase"      value="three" />
 3878: <input type="hidden" name="datatoken"  value="$datatoken" />
 3879: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3880: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3881: <input type="hidden" name="upfile_associate" 
 3882:                                        value="$env{'form.upfile_associate'}" />
 3883: <input type="hidden" name="symb"       value="$symb" />
 3884: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3885: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3886: <input type="hidden" name="command"    value="csvuploadoptions" />
 3887: <hr />
 3888: <script type="text/javascript" language="Javascript">
 3889: $javascript
 3890: </script>
 3891: ENDPICK
 3892:     return '';
 3893: 
 3894: }
 3895: 
 3896: sub csvupload_fields {
 3897:     my ($symb) = @_;
 3898:     my (@parts) = &getpartlist($symb);
 3899:     my @fields=(['ID','Student ID'],
 3900: 		['username','Student Username'],
 3901: 		['domain','Student Domain']);
 3902:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3903:     foreach my $part (sort(@parts)) {
 3904: 	my @datum;
 3905: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3906: 	my $name=$part;
 3907: 	if  (!$display) { $display = $name; }
 3908: 	@datum=($name,$display);
 3909: 	if ($name=~/^stores_(.*)_awarded/) {
 3910: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3911: 	}
 3912: 	push(@fields,\@datum);
 3913:     }
 3914:     return (@fields);
 3915: }
 3916: 
 3917: sub csvuploadmap_footer {
 3918:     my ($request,$i,$keyfields) =@_;
 3919:     $request->print(<<ENDPICK);
 3920: </table>
 3921: <input type="hidden" name="nfields" value="$i" />
 3922: <input type="hidden" name="keyfields" value="$keyfields" />
 3923: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3924: </form>
 3925: ENDPICK
 3926: }
 3927: 
 3928: sub checkforfile_js {
 3929:     my $result =<<CSVFORMJS;
 3930: <script type="text/javascript" language="javascript">
 3931:     function checkUpload(formname) {
 3932: 	if (formname.upfile.value == "") {
 3933: 	    alert("Please use the browse button to select a file from your local directory.");
 3934: 	    return false;
 3935: 	}
 3936: 	formname.submit();
 3937:     }
 3938:     </script>
 3939: CSVFORMJS
 3940:     return $result;
 3941: }
 3942: 
 3943: sub upcsvScores_form {
 3944:     my ($request) = shift;
 3945:     my ($symb)=&get_symb($request);
 3946:     if (!$symb) {return '';}
 3947:     my $result=&checkforfile_js();
 3948:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3949:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3950:     $result.=$table;
 3951:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3952:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3953:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3954: 	'.</b></td></tr>'."\n";
 3955:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3956:     my $upload=&mt("Upload Scores");
 3957:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3958:     my $ignore=&mt('Ignore First Line');
 3959:     $symb = &Apache::lonenc::check_encrypt($symb);
 3960:     $result.=<<ENDUPFORM;
 3961: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3962: <input type="hidden" name="symb" value="$symb" />
 3963: <input type="hidden" name="command" value="csvuploadmap" />
 3964: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3965: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3966: $upfile_select
 3967: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3968: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3969: </form>
 3970: ENDUPFORM
 3971:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3972:                            &mt("How do I create a CSV file from a spreadsheet"))
 3973:     .'</td></tr></table>'."\n";
 3974:     $result.='</td></tr></table><br /><br />'."\n";
 3975:     $result.=&show_grading_menu_form($symb);
 3976:     return $result;
 3977: }
 3978: 
 3979: 
 3980: sub csvuploadmap {
 3981:     my ($request)= @_;
 3982:     my ($symb)=&get_symb($request);
 3983:     if (!$symb) {return '';}
 3984: 
 3985:     my $datatoken;
 3986:     if (!$env{'form.datatoken'}) {
 3987: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3988:     } else {
 3989: 	$datatoken=$env{'form.datatoken'};
 3990: 	&Apache::loncommon::load_tmp_file($request);
 3991:     }
 3992:     my @records=&Apache::loncommon::upfile_record_sep();
 3993:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3994:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3995:     my ($i,$keyfields);
 3996:     if (@records) {
 3997: 	my @fields=&csvupload_fields($symb);
 3998: 
 3999: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4000: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4001: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4002: 							  \@fields);
 4003: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4004: 	    chop($keyfields);
 4005: 	} else {
 4006: 	    unshift(@fields,['none','']);
 4007: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4008: 							    \@fields);
 4009:             foreach my $rec (@records) {
 4010:                 my %temp = &Apache::loncommon::record_sep($rec);
 4011:                 if (%temp) {
 4012:                     $keyfields=join(',',sort(keys(%temp)));
 4013:                     last;
 4014:                 }
 4015:             }
 4016: 	}
 4017:     }
 4018:     &csvuploadmap_footer($request,$i,$keyfields);
 4019:     $request->print(&show_grading_menu_form($symb));
 4020: 
 4021:     return '';
 4022: }
 4023: 
 4024: sub csvuploadoptions {
 4025:     my ($request)= @_;
 4026:     my ($symb)=&get_symb($request);
 4027:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4028:     my $ignore=&mt('Ignore First Line');
 4029:     $request->print(<<ENDPICK);
 4030: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4031: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4032: <input type="hidden" name="command"    value="csvuploadassign" />
 4033: <!--
 4034: <p>
 4035: <label>
 4036:    <input type="checkbox" name="show_full_results" />
 4037:    Show a table of all changes
 4038: </label>
 4039: </p>
 4040: -->
 4041: <p>
 4042: <label>
 4043:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4044:    Overwrite any existing score
 4045: </label>
 4046: </p>
 4047: ENDPICK
 4048:     my %fields=&get_fields();
 4049:     if (!defined($fields{'domain'})) {
 4050: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4051: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4052:     }
 4053:     foreach my $key (sort(keys(%env))) {
 4054: 	if ($key !~ /^form\.(.*)$/) { next; }
 4055: 	my $cleankey=$1;
 4056: 	if ($cleankey eq 'command') { next; }
 4057: 	$request->print('<input type="hidden" name="'.$cleankey.
 4058: 			'"  value="'.$env{$key}.'" />'."\n");
 4059:     }
 4060:     # FIXME do a check for any duplicated user ids...
 4061:     # FIXME do a check for any invalid user ids?...
 4062:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4063: <hr /></form>'."\n");
 4064:     $request->print(&show_grading_menu_form($symb));
 4065:     return '';
 4066: }
 4067: 
 4068: sub get_fields {
 4069:     my %fields;
 4070:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4071:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4072: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4073: 	    if ($env{'form.f'.$i} ne 'none') {
 4074: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4075: 	    }
 4076: 	} else {
 4077: 	    if ($env{'form.f'.$i} ne 'none') {
 4078: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4079: 	    }
 4080: 	}
 4081:     }
 4082:     return %fields;
 4083: }
 4084: 
 4085: sub csvuploadassign {
 4086:     my ($request)= @_;
 4087:     my ($symb)=&get_symb($request);
 4088:     if (!$symb) {return '';}
 4089:     my $error_msg = '';
 4090:     &Apache::loncommon::load_tmp_file($request);
 4091:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4092:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4093:     my %fields=&get_fields();
 4094:     $request->print('<h3>Assigning Grades</h3>');
 4095:     my $courseid=$env{'request.course.id'};
 4096:     my ($classlist) = &getclasslist('all',0);
 4097:     my @notallowed;
 4098:     my @skipped;
 4099:     my $countdone=0;
 4100:     foreach my $grade (@gradedata) {
 4101: 	my %entries=&Apache::loncommon::record_sep($grade);
 4102: 	my $domain;
 4103: 	if ($entries{$fields{'domain'}}) {
 4104: 	    $domain=$entries{$fields{'domain'}};
 4105: 	} else {
 4106: 	    $domain=$env{'form.default_domain'};
 4107: 	}
 4108: 	$domain=~s/\s//g;
 4109: 	my $username=$entries{$fields{'username'}};
 4110: 	$username=~s/\s//g;
 4111: 	if (!$username) {
 4112: 	    my $id=$entries{$fields{'ID'}};
 4113: 	    $id=~s/\s//g;
 4114: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4115: 	    $username=$ids{$id};
 4116: 	}
 4117: 	if (!exists($$classlist{"$username:$domain"})) {
 4118: 	    my $id=$entries{$fields{'ID'}};
 4119: 	    $id=~s/\s//g;
 4120: 	    if ($id) {
 4121: 		push(@skipped,"$id:$domain");
 4122: 	    } else {
 4123: 		push(@skipped,"$username:$domain");
 4124: 	    }
 4125: 	    next;
 4126: 	}
 4127: 	my $usec=$classlist->{"$username:$domain"}[5];
 4128: 	if (!&canmodify($usec)) {
 4129: 	    push(@notallowed,"$username:$domain");
 4130: 	    next;
 4131: 	}
 4132: 	my %points;
 4133: 	my %grades;
 4134: 	foreach my $dest (keys(%fields)) {
 4135: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4136: 		$dest eq 'domain') { next; }
 4137: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4138: 	    if ($dest=~/stores_(.*)_points/) {
 4139: 		my $part=$1;
 4140: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4141: 					      $symb,$domain,$username);
 4142:                 if ($wgt) {
 4143:                     $entries{$fields{$dest}}=~s/\s//g;
 4144:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4145:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4146:                                           : 'correct_by_override';
 4147:                     $grades{"resource.$part.awarded"}=$pcr;
 4148:                     $grades{"resource.$part.solved"}=$award;
 4149:                     $points{$part}=1;
 4150:                 } else {
 4151:                     $error_msg = "<br />" .
 4152:                         &mt("Some point values were assigned"
 4153:                             ." for problems with a weight "
 4154:                             ."of zero. These values were "
 4155:                             ."ignored.");
 4156:                 }
 4157: 	    } else {
 4158: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4159: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4160: 		my $store_key=$dest;
 4161: 		$store_key=~s/^stores/resource/;
 4162: 		$store_key=~s/_/\./g;
 4163: 		$grades{$store_key}=$entries{$fields{$dest}};
 4164: 	    }
 4165: 	}
 4166: 	if (! %grades) { 
 4167:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4168:         } else {
 4169: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4170: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4171: 					   $env{'request.course.id'},
 4172: 					   $domain,$username);
 4173: 	   if ($result eq 'ok') {
 4174: 	      $request->print('.');
 4175: 	   } else {
 4176: 	      $request->print("<p><span class=\"LC_error\">".
 4177:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4178:                                   "$username:$domain",$result)."</span></p>");
 4179: 	   }
 4180: 	   $request->rflush();
 4181: 	   $countdone++;
 4182:         }
 4183:     }
 4184:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4185:     if (@skipped) {
 4186: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4187: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4188:     }
 4189:     if (@notallowed) {
 4190: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4191: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4192:     }
 4193:     $request->print("<br />\n");
 4194:     $request->print(&show_grading_menu_form($symb));
 4195:     return $error_msg;
 4196: }
 4197: #------------- end of section for handling csv file upload ---------
 4198: #
 4199: #-------------------------------------------------------------------
 4200: #
 4201: #-------------- Next few routines handle grading by page/sequence
 4202: #
 4203: #--- Select a page/sequence and a student to grade
 4204: sub pickStudentPage {
 4205:     my ($request) = shift;
 4206: 
 4207:     $request->print(<<LISTJAVASCRIPT);
 4208: <script type="text/javascript" language="javascript">
 4209: 
 4210: function checkPickOne(formname) {
 4211:     if (radioSelection(formname.student) == null) {
 4212: 	alert("Please select the student you wish to grade.");
 4213: 	return;
 4214:     }
 4215:     ptr = pullDownSelection(formname.selectpage);
 4216:     formname.page.value = formname["page"+ptr].value;
 4217:     formname.title.value = formname["title"+ptr].value;
 4218:     formname.submit();
 4219: }
 4220: 
 4221: </script>
 4222: LISTJAVASCRIPT
 4223:     &commonJSfunctions($request);
 4224:     my ($symb) = &get_symb($request);
 4225:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4226:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4227:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4228: 
 4229:     my $result='<h3><span class="LC_info">&nbsp;'.
 4230: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4231: 
 4232:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4233:     my ($titles,$symbx) = &getSymbMap();
 4234:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4235: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4236: #    my $type=($curpage =~ /\.(page|sequence)/);
 4237:     my $select = '<select name="selectpage">'."\n";
 4238:     my $ctr=0;
 4239:     foreach (@$titles) {
 4240: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4241: 	$select.='<option value="'.$ctr.'" '.
 4242: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4243: 	    '>'.$showtitle.'</option>'."\n";
 4244: 	$ctr++;
 4245:     }
 4246:     $select.= '</select>';
 4247:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4248: 
 4249:     $ctr=0;
 4250:     foreach (@$titles) {
 4251: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4252: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4253: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4254: 	$ctr++;
 4255:     }
 4256:     $result.='<input type="hidden" name="page" />'."\n".
 4257: 	'<input type="hidden" name="title" />'."\n";
 4258: 
 4259:     my $options =
 4260: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4261: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4262:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4263: 
 4264:     $options =
 4265: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4266: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4267: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4268:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4269:     
 4270:     $result.=&build_section_inputs();
 4271:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4272:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4273: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4274: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4275: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4276: 
 4277:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4278: 			  '<input type="text" name="CODE" value="" />').
 4279: 			      '<br />'."\n";
 4280: 
 4281:     $result.='&nbsp;<input type="button" '.
 4282: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4283: 
 4284:     $request->print($result);
 4285: 
 4286:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4287: 	&Apache::loncommon::start_data_table().
 4288: 	&Apache::loncommon::start_data_table_header_row().
 4289: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4290: 	'<th>'.&nameUserString('header').'</th>'.
 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4292: 	'<th>'.&nameUserString('header').'</th>'.
 4293: 	&Apache::loncommon::end_data_table_header_row();
 4294:  
 4295:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4296:     my $ptr = 1;
 4297:     foreach my $student (sort 
 4298: 			 {
 4299: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4300: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4301: 			     }
 4302: 			     return $a cmp $b;
 4303: 			 } (keys(%$fullname))) {
 4304: 	my ($uname,$udom) = split(/:/,$student);
 4305: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4306:                                   : '</td>');
 4307: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4308: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4309: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4310: 	$studentTable.=
 4311: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4312:                          : '');
 4313: 	$ptr++;
 4314:     }
 4315:     if ($ptr%2 == 0) {
 4316: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4317: 	    &Apache::loncommon::end_data_table_row();
 4318:     }
 4319:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4320:     $studentTable.='<input type="button" '.
 4321: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4322: 
 4323:     $studentTable.=&show_grading_menu_form($symb);
 4324:     $request->print($studentTable);
 4325: 
 4326:     return '';
 4327: }
 4328: 
 4329: sub getSymbMap {
 4330:     my $navmap = Apache::lonnavmaps::navmap->new();
 4331: 
 4332:     my %symbx = ();
 4333:     my @titles = ();
 4334:     my $minder = 0;
 4335: 
 4336:     # Gather every sequence that has problems.
 4337:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4338: 					       1,0,1);
 4339:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4340: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4341: 	    my $title = $minder.'.'.
 4342: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4343: 	    push(@titles, $title); # minder in case two titles are identical
 4344: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4345: 	    $minder++;
 4346: 	}
 4347:     }
 4348:     return \@titles,\%symbx;
 4349: }
 4350: 
 4351: #
 4352: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4353: sub displayPage {
 4354:     my ($request) = shift;
 4355: 
 4356:     my ($symb) = &get_symb($request);
 4357:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4358:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4359:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4360:     my $pageTitle = $env{'form.page'};
 4361:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4362:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4363:     my $usec=$classlist->{$env{'form.student'}}[5];
 4364: 
 4365:     #need to make sure we have the correct data for later EXT calls, 
 4366:     #thus invalidate the cache
 4367:     &Apache::lonnet::devalidatecourseresdata(
 4368:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4369:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4370:     &Apache::lonnet::clear_EXT_cache_status();
 4371: 
 4372:     if (!&canview($usec)) {
 4373: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4374: 	$request->print(&show_grading_menu_form($symb));
 4375: 	return;
 4376:     }
 4377:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4378:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4379: 	'</h3>'."\n";
 4380:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4381:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4382: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4383:     } else {
 4384: 	delete($env{'form.CODE'});
 4385:     }
 4386:     &sub_page_js($request);
 4387:     $request->print($result);
 4388: 
 4389:     my $navmap = Apache::lonnavmaps::navmap->new();
 4390:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4391:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4392:     if (!$map) {
 4393: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4394: 	$request->print(&show_grading_menu_form($symb));
 4395: 	return; 
 4396:     }
 4397:     my $iterator = $navmap->getIterator($map->map_start(),
 4398: 					$map->map_finish());
 4399: 
 4400:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4401: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4402: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4403: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4404: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4405: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4406: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4407: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4408: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4409: 
 4410:     if (defined($env{'form.CODE'})) {
 4411: 	$studentTable.=
 4412: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4413:     }
 4414:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4415: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4416: 
 4417:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4418: 	&Apache::loncommon::start_data_table().
 4419: 	&Apache::loncommon::start_data_table_header_row().
 4420: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4421: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4422: 	&Apache::loncommon::end_data_table_header_row();
 4423: 
 4424:     &Apache::lonxml::clear_problem_counter();
 4425:     my ($depth,$question,$prob) = (1,1,1);
 4426:     $iterator->next(); # skip the first BEGIN_MAP
 4427:     my $curRes = $iterator->next(); # for "current resource"
 4428:     while ($depth > 0) {
 4429:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4430:         if($curRes == $iterator->END_MAP) { $depth--; }
 4431: 
 4432:         if (ref($curRes) && $curRes->is_problem()) {
 4433: 	    my $parts = $curRes->parts();
 4434:             my $title = $curRes->compTitle();
 4435: 	    my $symbx = $curRes->symb();
 4436: 	    $studentTable.=
 4437: 		&Apache::loncommon::start_data_table_row().
 4438: 		'<td align="center" valign="top" >'.$prob.
 4439: 		(scalar(@{$parts}) == 1 ? '' 
 4440: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4441: 							scalar(@{$parts}))
 4442: 		 ).
 4443: 		 '</td>';
 4444: 	    $studentTable.='<td valign="top">';
 4445: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4446: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4447: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4448: 					     undef,'both',\%form);
 4449: 	    } else {
 4450: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4451: 		$companswer =~ s|<form(.*?)>||g;
 4452: 		$companswer =~ s|</form>||g;
 4453: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4454: #		    $companswer =~ s/$1/ /ms;
 4455: #		    $request->print('match='.$1."<br />\n");
 4456: #		}
 4457: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4458: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4459: 	    }
 4460: 
 4461: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4462: 
 4463: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4464: 		if ($record{'version'} eq '') {
 4465: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4466: 		} else {
 4467: 		    my %responseType = ();
 4468: 		    foreach my $partid (@{$parts}) {
 4469: 			my @responseIds =$curRes->responseIds($partid);
 4470: 			my @responseType =$curRes->responseType($partid);
 4471: 			my %responseIds;
 4472: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4473: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4474: 			}
 4475: 			$responseType{$partid} = \%responseIds;
 4476: 		    }
 4477: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4478: 
 4479: 		}
 4480: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4481: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4482: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4483: 									$env{'request.course.id'},
 4484: 									'','.submission');
 4485:  
 4486: 	    }
 4487: 	    if (&canmodify($usec)) {
 4488: 		foreach my $partid (@{$parts}) {
 4489: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4490: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4491: 		    $question++;
 4492: 		}
 4493: 		$prob++;
 4494: 	    }
 4495: 	    $studentTable.='</td></tr>';
 4496: 
 4497: 	}
 4498:         $curRes = $iterator->next();
 4499:     }
 4500: 
 4501:     $studentTable.='</table>'."\n".
 4502: 	'<input type="button" value="'.&mt('Save').'" '.
 4503: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4504: 	'</form>'."\n";
 4505:     $studentTable.=&show_grading_menu_form($symb);
 4506:     $request->print($studentTable);
 4507: 
 4508:     return '';
 4509: }
 4510: 
 4511: sub displaySubByDates {
 4512:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4513:     my $isCODE=0;
 4514:     my $isTask = ($symb =~/\.task$/);
 4515:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4516:     my $studentTable=&Apache::loncommon::start_data_table().
 4517: 	&Apache::loncommon::start_data_table_header_row().
 4518: 	'<th>'.&mt('Date/Time').'</th>'.
 4519: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4520: 	'<th>'.&mt('Submission').'</th>'.
 4521: 	'<th>'.&mt('Status').'</th>'.
 4522: 	&Apache::loncommon::end_data_table_header_row();
 4523:     my ($version);
 4524:     my %mark;
 4525:     my %orders;
 4526:     $mark{'correct_by_student'} = $checkIcon;
 4527:     if (!exists($$record{'1:timestamp'})) {
 4528: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4529:     }
 4530: 
 4531:     my $interaction;
 4532:     my $no_increment = 1;
 4533:     for ($version=1;$version<=$$record{'version'};$version++) {
 4534: 	my $timestamp = 
 4535: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4536: 	if (exists($$record{$version.':resource.0.version'})) {
 4537: 	    $interaction = $$record{$version.':resource.0.version'};
 4538: 	}
 4539: 
 4540: 	my $where = ($isTask ? "$version:resource.$interaction"
 4541: 		             : "$version:resource");
 4542: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4543: 	    '<td>'.$timestamp.'</td>';
 4544: 	if ($isCODE) {
 4545: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4546: 	}
 4547: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4548: 	my @displaySub = ();
 4549: 	foreach my $partid (@{$parts}) {
 4550: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4551: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4552: 	    
 4553: 
 4554: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4555: 	    my $display_part=&get_display_part($partid,$symb);
 4556: 	    foreach my $matchKey (@matchKey) {
 4557: 		if (exists($$record{$version.':'.$matchKey}) &&
 4558: 		    $$record{$version.':'.$matchKey} ne '') {
 4559: 
 4560: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4561: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4562: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4563: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4564: 			$responseId.')</span>&nbsp;<b>';
 4565: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4566: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4567: 		    } else {
 4568: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4569: 					    $$record{"$where.$partid.tries"});
 4570: 		    }
 4571: 		    my $responseType=($isTask ? 'Task'
 4572:                                               : $responseType->{$partid}->{$responseId});
 4573: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4574: 		    if (!exists($orders{$partid}->{$responseId})) {
 4575: 			$orders{$partid}->{$responseId}=
 4576: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4577:                                        $no_increment);
 4578: 		    }
 4579: 		    $displaySub[0].='</b>&nbsp; '.
 4580: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4581: 		}
 4582: 	    }
 4583: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4584: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4585: 				    $$record{"$where.$partid.checkedin"},
 4586: 				    $$record{"$where.$partid.checkedin.slot"}).
 4587: 					'<br />';
 4588: 	    }
 4589: 	    if (exists $$record{"$where.$partid.award"}) {
 4590: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4591: 		    lc($$record{"$where.$partid.award"}).' '.
 4592: 		    $mark{$$record{"$where.$partid.solved"}}.
 4593: 		    '<br />';
 4594: 	    }
 4595: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4596: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4597: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4598: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4599: 		$displaySub[2].=
 4600: 		    $$record{"$version:resource.$partid.regrader"}.
 4601: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4602: 	    }
 4603: 	}
 4604: 	# needed because old essay regrader has not parts info
 4605: 	if (exists $$record{"$version:resource.regrader"}) {
 4606: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4607: 	}
 4608: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4609: 	if ($displaySub[2]) {
 4610: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4611: 	}
 4612: 	$studentTable.='&nbsp;</td>'.
 4613: 	    &Apache::loncommon::end_data_table_row();
 4614:     }
 4615:     $studentTable.=&Apache::loncommon::end_data_table();
 4616:     return $studentTable;
 4617: }
 4618: 
 4619: sub updateGradeByPage {
 4620:     my ($request) = shift;
 4621: 
 4622:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4623:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4624:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4625:     my $pageTitle = $env{'form.page'};
 4626:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4627:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4628:     my $usec=$classlist->{$env{'form.student'}}[5];
 4629:     if (!&canmodify($usec)) {
 4630: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4631: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4632: 	return;
 4633:     }
 4634:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4635:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4636: 	'</h3>'."\n";
 4637: 
 4638:     $request->print($result);
 4639: 
 4640:     my $navmap = Apache::lonnavmaps::navmap->new();
 4641:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4642:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4643:     if (!$map) {
 4644: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4645: 	my ($symb)=&get_symb($request);
 4646: 	$request->print(&show_grading_menu_form($symb));
 4647: 	return; 
 4648:     }
 4649:     my $iterator = $navmap->getIterator($map->map_start(),
 4650: 					$map->map_finish());
 4651: 
 4652:     my $studentTable=
 4653: 	&Apache::loncommon::start_data_table().
 4654: 	&Apache::loncommon::start_data_table_header_row().
 4655: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4656: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4657: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4658: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4659: 	&Apache::loncommon::end_data_table_header_row();
 4660: 
 4661:     $iterator->next(); # skip the first BEGIN_MAP
 4662:     my $curRes = $iterator->next(); # for "current resource"
 4663:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4664:     while ($depth > 0) {
 4665:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4666:         if($curRes == $iterator->END_MAP) { $depth--; }
 4667: 
 4668:         if (ref($curRes) && $curRes->is_problem()) {
 4669: 	    my $parts = $curRes->parts();
 4670:             my $title = $curRes->compTitle();
 4671: 	    my $symbx = $curRes->symb();
 4672: 	    $studentTable.=
 4673: 		&Apache::loncommon::start_data_table_row().
 4674: 		'<td align="center" valign="top" >'.$prob.
 4675: 		(scalar(@{$parts}) == 1 ? '' 
 4676:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4677: 		.')').'</td>';
 4678: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4679: 
 4680: 	    my %newrecord=();
 4681: 	    my @displayPts=();
 4682:             my %aggregate = ();
 4683:             my $aggregateflag = 0;
 4684: 	    foreach my $partid (@{$parts}) {
 4685: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4686: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4687: 
 4688: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4689: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4690: 		my $partial = $newpts/$wgt;
 4691: 		my $score;
 4692: 		if ($partial > 0) {
 4693: 		    $score = 'correct_by_override';
 4694: 		} elsif ($newpts ne '') { #empty is taken as 0
 4695: 		    $score = 'incorrect_by_override';
 4696: 		}
 4697: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4698: 		if ($dropMenu eq 'excused') {
 4699: 		    $partial = '';
 4700: 		    $score = 'excused';
 4701: 		} elsif ($dropMenu eq 'reset status'
 4702: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4703: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4704: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4705: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4706: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4707: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4708: 		    $changeflag++;
 4709: 		    $newpts = '';
 4710:                     
 4711:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4712:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4713:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4714:                     if ($aggtries > 0) {
 4715:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4716:                         $aggregateflag = 1;
 4717:                     }
 4718: 		}
 4719: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4720: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4721: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4722: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4723: 		    '&nbsp;<br />';
 4724: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4725: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4726: 		    '&nbsp;<br />';
 4727: 		$question++;
 4728: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4729: 
 4730: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4731: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4732: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4733: 		    if (scalar(keys(%newrecord)) > 0);
 4734: 
 4735: 		$changeflag++;
 4736: 	    }
 4737: 	    if (scalar(keys(%newrecord)) > 0) {
 4738: 		my %record = 
 4739: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4740: 					     $udom,$uname);
 4741: 
 4742: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4743: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4744: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4745: 		    $newrecord{'resource.CODE'} = '';
 4746: 		}
 4747: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4748: 					$udom,$uname);
 4749: 		%record = &Apache::lonnet::restore($symbx,
 4750: 						   $env{'request.course.id'},
 4751: 						   $udom,$uname);
 4752: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4753: 					     $cdom,$cnum,$udom,$uname);
 4754: 	    }
 4755: 	    
 4756:             if ($aggregateflag) {
 4757:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4758:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4759:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4760:             }
 4761: 
 4762: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4763: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4764: 		&Apache::loncommon::end_data_table_row();
 4765: 
 4766: 	    $prob++;
 4767: 	}
 4768:         $curRes = $iterator->next();
 4769:     }
 4770: 
 4771:     $studentTable.=&Apache::loncommon::end_data_table();
 4772:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4773:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4774: 		  &mt('The scores were changed for [quant,_1,problem].',
 4775: 		  $changeflag));
 4776:     $request->print($grademsg.$studentTable);
 4777: 
 4778:     return '';
 4779: }
 4780: 
 4781: #-------- end of section for handling grading by page/sequence ---------
 4782: #
 4783: #-------------------------------------------------------------------
 4784: 
 4785: #--------------------Scantron Grading-----------------------------------
 4786: #
 4787: #------ start of section for handling grading by page/sequence ---------
 4788: 
 4789: =pod
 4790: 
 4791: =head1 Bubble sheet grading routines
 4792: 
 4793:   For this documentation:
 4794: 
 4795:    'scanline' refers to the full line of characters
 4796:    from the file that we are parsing that represents one entire sheet
 4797: 
 4798:    'bubble line' refers to the data
 4799:    representing the line of bubbles that are on the physical bubble sheet
 4800: 
 4801: 
 4802: The overall process is that a scanned in bubble sheet data is uploaded
 4803: into a course. When a user wants to grade, they select a
 4804: sequence/folder of resources, a file of bubble sheet info, and pick
 4805: one of the predefined configurations for what each scanline looks
 4806: like.
 4807: 
 4808: Next each scanline is checked for any errors of either 'missing
 4809: bubbles' (it's an error because it may have been mis-scanned
 4810: because too light bubbling), 'double bubble' (each bubble line should
 4811: have no more that one letter picked), invalid or duplicated CODE,
 4812: invalid student ID
 4813: 
 4814: If the CODE option is used that determines the randomization of the
 4815: homework problems, either way the student ID is looked up into a
 4816: username:domain.
 4817: 
 4818: During the validation phase the instructor can choose to skip scanlines. 
 4819: 
 4820: After the validation phase, there are now 3 bubble sheet files
 4821: 
 4822:   scantron_original_filename (unmodified original file)
 4823:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4824:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4825: 
 4826: Also there is a separate hash nohist_scantrondata that contains extra
 4827: correction information that isn't representable in the bubble sheet
 4828: file (see &scantron_getfile() for more information)
 4829: 
 4830: After all scanlines are either valid, marked as valid or skipped, then
 4831: foreach line foreach problem in the picked sequence, an ssi request is
 4832: made that simulates a user submitting their selected letter(s) against
 4833: the homework problem.
 4834: 
 4835: =over 4
 4836: 
 4837: 
 4838: 
 4839: =item defaultFormData
 4840: 
 4841:   Returns html hidden inputs used to hold context/default values.
 4842: 
 4843:  Arguments:
 4844:   $symb - $symb of the current resource 
 4845: 
 4846: =cut
 4847: 
 4848: sub defaultFormData {
 4849:     my ($symb)=@_;
 4850:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4851:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4852:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4853: }
 4854: 
 4855: 
 4856: =pod 
 4857: 
 4858: =item getSequenceDropDown
 4859: 
 4860:    Return html dropdown of possible sequences to grade
 4861:  
 4862:  Arguments:
 4863:    $symb - $symb of the current resource 
 4864: 
 4865: =cut
 4866: 
 4867: sub getSequenceDropDown {
 4868:     my ($symb)=@_;
 4869:     my $result='<select name="selectpage">'."\n";
 4870:     my ($titles,$symbx) = &getSymbMap();
 4871:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4872:     my $ctr=0;
 4873:     foreach (@$titles) {
 4874: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4875: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4876: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4877: 	    '>'.$showtitle.'</option>'."\n";
 4878: 	$ctr++;
 4879:     }
 4880:     $result.= '</select>';
 4881:     return $result;
 4882: }
 4883: 
 4884: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4885:                                    # index is "symb.part_id"
 4886: 
 4887: my %first_bubble_line;             # First bubble line no. for each bubble.
 4888: 
 4889: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4890:                                    # matchresponse or rankresponse, where 
 4891:                                    # an individual response can have multiple 
 4892:                                    # lines
 4893: 
 4894: my %responsetype_per_response;     # responsetype for each response
 4895: 
 4896: # Save and restore the bubble lines array to the form env.
 4897: 
 4898: 
 4899: sub save_bubble_lines {
 4900:     foreach my $line (keys(%bubble_lines_per_response)) {
 4901: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4902: 	$env{"form.scantron.first_bubble_line.$line"} =
 4903: 	    $first_bubble_line{$line};
 4904:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4905:             $subdivided_bubble_lines{$line};
 4906:         $env{"form.scantron.responsetype.$line"} =
 4907:             $responsetype_per_response{$line};
 4908:     }
 4909: }
 4910: 
 4911: 
 4912: sub restore_bubble_lines {
 4913:     my $line = 0;
 4914:     %bubble_lines_per_response = ();
 4915:     while ($env{"form.scantron.bubblelines.$line"}) {
 4916: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4917: 	$bubble_lines_per_response{$line} = $value;
 4918: 	$first_bubble_line{$line}  =
 4919: 	    $env{"form.scantron.first_bubble_line.$line"};
 4920:         $subdivided_bubble_lines{$line} =
 4921:             $env{"form.scantron.sub_bubblelines.$line"};
 4922:         $responsetype_per_response{$line} =
 4923:             $env{"form.scantron.responsetype.$line"};
 4924: 	$line++;
 4925:     }
 4926: 
 4927: }
 4928: 
 4929: #  Given the parsed scanline, get the response for 
 4930: #  'answer' number n:
 4931: 
 4932: sub get_response_bubbles {
 4933:     my ($parsed_line, $response)  = @_;
 4934: 
 4935: 
 4936:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4937:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4938:     
 4939:     my $selected = "";
 4940: 
 4941:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4942: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4943: 	$bubble_line++;
 4944:     }
 4945:     return $selected;
 4946: }
 4947: 
 4948: =pod 
 4949: 
 4950: =item scantron_filenames
 4951: 
 4952:    Returns a list of the scantron files in the current course 
 4953: 
 4954: =cut
 4955: 
 4956: sub scantron_filenames {
 4957:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4959:     my $getpropath = 1;
 4960:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4961:                                        $getpropath);
 4962:     my @possiblenames;
 4963:     foreach my $filename (sort(@files)) {
 4964: 	($filename)=split(/&/,$filename);
 4965: 	if ($filename!~/^scantron_orig_/) { next ; }
 4966: 	$filename=~s/^scantron_orig_//;
 4967: 	push(@possiblenames,$filename);
 4968:     }
 4969:     return @possiblenames;
 4970: }
 4971: 
 4972: =pod 
 4973: 
 4974: =item scantron_uploads
 4975: 
 4976:    Returns  html drop-down list of scantron files in current course.
 4977: 
 4978:  Arguments:
 4979:    $file2grade - filename to set as selected in the dropdown
 4980: 
 4981: =cut
 4982: 
 4983: sub scantron_uploads {
 4984:     my ($file2grade) = @_;
 4985:     my $result=	'<select name="scantron_selectfile">';
 4986:     $result.="<option></option>";
 4987:     foreach my $filename (sort(&scantron_filenames())) {
 4988: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4989:     }
 4990:     $result.="</select>";
 4991:     return $result;
 4992: }
 4993: 
 4994: =pod 
 4995: 
 4996: =item scantron_scantab
 4997: 
 4998:   Returns html drop down of the scantron formats in the scantronformat.tab
 4999:   file.
 5000: 
 5001: =cut
 5002: 
 5003: sub scantron_scantab {
 5004:     my $result='<select name="scantron_format">'."\n";
 5005:     $result.='<option></option>'."\n";
 5006:     my @lines = &get_scantronformat_file();
 5007:     if (@lines > 0) {
 5008:         foreach my $line (@lines) {
 5009:             next if (($line =~ /^\#/) || ($line eq ''));
 5010: 	    my ($name,$descrip)=split(/:/,$line);
 5011: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5012:         }
 5013:     }
 5014:     $result.='</select>'."\n";
 5015:     return $result;
 5016: }
 5017: 
 5018: =pod
 5019: 
 5020: =item get_scantronformat_file
 5021: 
 5022:   Returns an array containing lines from the scantron format file for
 5023:   the domain of the course.
 5024: 
 5025:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5026:   lines are from this file.
 5027: 
 5028:   Otherwise, if a default.tab has been published in RES space by the 
 5029:   domainconfig user, lines are from this file.
 5030: 
 5031:   Otherwise, fall back to getting lines from the legacy file on the
 5032:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5033: 
 5034: =cut
 5035: 
 5036: sub get_scantronformat_file {
 5037:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5038:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5039:     my $gottab = 0;
 5040:     my @lines;
 5041:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5042:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5043:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5044:             if ($formatfile ne '-1') {
 5045:                 @lines = split("\n",$formatfile,-1);
 5046:                 $gottab = 1;
 5047:             }
 5048:         }
 5049:     }
 5050:     if (!$gottab) {
 5051:         my $confname = $cdom.'-domainconfig';
 5052:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5053:         my $formatfile =  &Apache::lonnet::getfile($default);
 5054:         if ($formatfile ne '-1') {
 5055:             @lines = split("\n",$formatfile,-1);
 5056:             $gottab = 1;
 5057:         }
 5058:     }
 5059:     if (!$gottab) {
 5060:         my @domains = &Apache::lonnet::current_machine_domains();
 5061:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5062:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5063:             @lines = <$fh>;
 5064:             close($fh);
 5065:         } else {
 5066:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5067:             @lines = <$fh>;
 5068:             close($fh);
 5069:         }
 5070:     }
 5071:     return @lines;
 5072: }
 5073: 
 5074: =pod 
 5075: 
 5076: =item scantron_CODElist
 5077: 
 5078:   Returns html drop down of the saved CODE lists from current course,
 5079:   generated from earlier printings.
 5080: 
 5081: =cut
 5082: 
 5083: sub scantron_CODElist {
 5084:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5085:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5086:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5087:     my $namechoice='<option></option>';
 5088:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5089: 	if ($name =~ /^error: 2 /) { next; }
 5090: 	if ($name =~ /^type\0/) { next; }
 5091: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5092:     }
 5093:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5094:     return $namechoice;
 5095: }
 5096: 
 5097: =pod 
 5098: 
 5099: =item scantron_CODEunique
 5100: 
 5101:   Returns the html for "Each CODE to be used once" radio.
 5102: 
 5103: =cut
 5104: 
 5105: sub scantron_CODEunique {
 5106:     my $result='<span style="white-space: nowrap;">
 5107:                  <label><input type="radio" name="scantron_CODEunique"
 5108:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5109:                 </span>
 5110:                 <span style="white-space: nowrap;">
 5111:                  <label><input type="radio" name="scantron_CODEunique"
 5112:                         value="no" />'.&mt('No').' </label>
 5113:                 </span>';
 5114:     return $result;
 5115: }
 5116: 
 5117: =pod 
 5118: 
 5119: =item scantron_selectphase
 5120: 
 5121:   Generates the initial screen to start the bubble sheet process.
 5122:   Allows for - starting a grading run.
 5123:              - downloading existing scan data (original, corrected
 5124:                                                 or skipped info)
 5125: 
 5126:              - uploading new scan data
 5127: 
 5128:  Arguments:
 5129:   $r          - The Apache request object
 5130:   $file2grade - name of the file that contain the scanned data to score
 5131: 
 5132: =cut
 5133: 
 5134: sub scantron_selectphase {
 5135:     my ($r,$file2grade) = @_;
 5136:     my ($symb)=&get_symb($r);
 5137:     if (!$symb) {return '';}
 5138:     my $sequence_selector=&getSequenceDropDown($symb);
 5139:     my $default_form_data=&defaultFormData($symb);
 5140:     my $grading_menu_button=&show_grading_menu_form($symb);
 5141:     my $file_selector=&scantron_uploads($file2grade);
 5142:     my $format_selector=&scantron_scantab();
 5143:     my $CODE_selector=&scantron_CODElist();
 5144:     my $CODE_unique=&scantron_CODEunique();
 5145:     my $result;
 5146: 
 5147:     $ssi_error = 0;
 5148: 
 5149:     # Chunk of form to prompt for a file to grade and how:
 5150: 
 5151:     $result.= '
 5152:     <br />
 5153:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5154:     <input type="hidden" name="command" value="scantron_warning" />
 5155:     '.$default_form_data.'
 5156:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5157:        '.&Apache::loncommon::start_data_table_header_row().'
 5158:             <th colspan="2">
 5159:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5160:             </th>
 5161:        '.&Apache::loncommon::end_data_table_header_row().'
 5162:        '.&Apache::loncommon::start_data_table_row().'
 5163:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5164:        '.&Apache::loncommon::end_data_table_row().'
 5165:        '.&Apache::loncommon::start_data_table_row().'
 5166:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5167:        '.&Apache::loncommon::end_data_table_row().'
 5168:        '.&Apache::loncommon::start_data_table_row().'
 5169:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5170:        '.&Apache::loncommon::end_data_table_row().'
 5171:        '.&Apache::loncommon::start_data_table_row().'
 5172:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5173:        '.&Apache::loncommon::end_data_table_row().'
 5174:        '.&Apache::loncommon::start_data_table_row().'
 5175:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5176:        '.&Apache::loncommon::end_data_table_row().'
 5177:        '.&Apache::loncommon::start_data_table_row().'
 5178: 	    <td> '.&mt('Options:').' </td>
 5179:             <td>
 5180: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5181:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5182:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5183: 	    </td>
 5184:        '.&Apache::loncommon::end_data_table_row().'
 5185:        '.&Apache::loncommon::start_data_table_row().'
 5186:             <td colspan="2">
 5187:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5188:             </td>
 5189:        '.&Apache::loncommon::end_data_table_row().'
 5190:     '.&Apache::loncommon::end_data_table().'
 5191:     </form>
 5192: ';
 5193:    
 5194:     $r->print($result);
 5195: 
 5196:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5197:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5198: 
 5199: 	# Chunk of form to prompt for a scantron file upload.
 5200: 
 5201:         $r->print('
 5202:     <br />
 5203:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5204:        '.&Apache::loncommon::start_data_table_header_row().'
 5205:             <th>
 5206:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5207:             </th>
 5208:        '.&Apache::loncommon::end_data_table_header_row().'
 5209:        '.&Apache::loncommon::start_data_table_row().'
 5210:             <td>
 5211: ');
 5212:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5213:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5214:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5215:     $r->print('
 5216:               <script type="text/javascript" language="javascript">
 5217:     function checkUpload(formname) {
 5218: 	if (formname.upfile.value == "") {
 5219: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5220: 	    return false;
 5221: 	}
 5222: 	formname.submit();
 5223:     }
 5224:               </script>
 5225: 
 5226:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5227:                 '.$default_form_data.'
 5228:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5229:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5230:                 <input name="command" value="scantronupload_save" type="hidden" />
 5231:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5232:                 <br />
 5233:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5234:               </form>
 5235: ');
 5236: 
 5237:         $r->print('
 5238:             </td>
 5239:        '.&Apache::loncommon::end_data_table_row().'
 5240:        '.&Apache::loncommon::end_data_table().'
 5241: ');
 5242:     }
 5243: 
 5244:     # Chunk of the form that prompts to view a scoring office file,
 5245:     # corrected file, skipped records in a file.
 5246: 
 5247:     $r->print('
 5248:    <br />
 5249:    <form action="/adm/grades" name="scantron_download">
 5250:      '.$default_form_data.'
 5251:      <input type="hidden" name="command" value="scantron_download" />
 5252:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5253:        '.&Apache::loncommon::start_data_table_header_row().'
 5254:               <th>
 5255:                 &nbsp;'.&mt('Download a scoring office file').'
 5256:               </th>
 5257:        '.&Apache::loncommon::end_data_table_header_row().'
 5258:        '.&Apache::loncommon::start_data_table_row().'
 5259:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5260:                 <br />
 5261:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5262:        '.&Apache::loncommon::end_data_table_row().'
 5263:      '.&Apache::loncommon::end_data_table().'
 5264:    </form>
 5265:    <br />
 5266: ');
 5267: 
 5268:     &Apache::lonpickcode::code_list($r,2);
 5269: 
 5270:     $r->print('<br /><form method="post" name="checkscantron">'.
 5271:              $default_form_data."\n".
 5272:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5273:              &Apache::loncommon::start_data_table_header_row()."\n".
 5274:              '<th colspan="2">
 5275:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5276:              '</th>'."\n".
 5277:               &Apache::loncommon::end_data_table_header_row()."\n".
 5278:               &Apache::loncommon::start_data_table_row()."\n".
 5279:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5280:               '<td> '.$sequence_selector.' </td>'.
 5281:               &Apache::loncommon::end_data_table_row()."\n".
 5282:               &Apache::loncommon::start_data_table_row()."\n".
 5283:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5284:               '<td> '.$file_selector.' </td>'."\n".
 5285:               &Apache::loncommon::end_data_table_row()."\n".
 5286:               &Apache::loncommon::start_data_table_row()."\n".
 5287:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5288:               '<td> '.$format_selector.' </td>'."\n".
 5289:               &Apache::loncommon::end_data_table_row()."\n".
 5290:               &Apache::loncommon::start_data_table_row()."\n".
 5291:               '<td colspan="2">'."\n".
 5292:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5293:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5294:               '</td>'."\n".
 5295:               &Apache::loncommon::end_data_table_row()."\n".
 5296:               &Apache::loncommon::end_data_table()."\n".
 5297:               '</form><br />');
 5298:     $r->print($grading_menu_button);
 5299:     return;
 5300: }
 5301: 
 5302: =pod
 5303: 
 5304: =item get_scantron_config
 5305: 
 5306:    Parse and return the scantron configuration line selected as a
 5307:    hash of configuration file fields.
 5308: 
 5309:  Arguments:
 5310:     which - the name of the configuration to parse from the file.
 5311: 
 5312: 
 5313:  Returns:
 5314:             If the named configuration is not in the file, an empty
 5315:             hash is returned.
 5316:     a hash with the fields
 5317:       name         - internal name for the this configuration setup
 5318:       description  - text to display to operator that describes this config
 5319:       CODElocation - if 0 or the string 'none'
 5320:                           - no CODE exists for this config
 5321:                      if -1 || the string 'letter'
 5322:                           - a CODE exists for this config and is
 5323:                             a string of letters
 5324:                      Unsupported value (but planned for future support)
 5325:                           if a positive integer
 5326:                                - The CODE exists as the first n items from
 5327:                                  the question section of the form
 5328:                           if the string 'number'
 5329:                                - The CODE exists for this config and is
 5330:                                  a string of numbers
 5331:       CODEstart   - (only matter if a CODE exists) column in the line where
 5332:                      the CODE starts
 5333:       CODElength  - length of the CODE
 5334:       IDstart     - column where the student ID number starts
 5335:       IDlength    - length of the student ID info
 5336:       Qstart      - column where the information from the bubbled
 5337:                     'questions' start
 5338:       Qlength     - number of columns comprising a single bubble line from
 5339:                     the sheet. (usually either 1 or 10)
 5340:       Qon         - either a single character representing the character used
 5341:                     to signal a bubble was chosen in the positional setup, or
 5342:                     the string 'letter' if the letter of the chosen bubble is
 5343:                     in the final, or 'number' if a number representing the
 5344:                     chosen bubble is in the file (1->A 0->J)
 5345:       Qoff        - the character used to represent that a bubble was
 5346:                     left blank
 5347:       PaperID     - if the scanning process generates a unique number for each
 5348:                     sheet scanned the column that this ID number starts in
 5349:       PaperIDlength - number of columns that comprise the unique ID number
 5350:                       for the sheet of paper
 5351:       FirstName   - column that the first name starts in
 5352:       FirstNameLength - number of columns that the first name spans
 5353:  
 5354:       LastName    - column that the last name starts in
 5355:       LastNameLength - number of columns that the last name spans
 5356: 
 5357: =cut
 5358: 
 5359: sub get_scantron_config {
 5360:     my ($which) = @_;
 5361:     my @lines = &get_scantronformat_file();
 5362:     my %config;
 5363:     #FIXME probably should move to XML it has already gotten a bit much now
 5364:     foreach my $line (@lines) {
 5365: 	my ($name,$descrip)=split(/:/,$line);
 5366: 	if ($name ne $which ) { next; }
 5367: 	chomp($line);
 5368: 	my @config=split(/:/,$line);
 5369: 	$config{'name'}=$config[0];
 5370: 	$config{'description'}=$config[1];
 5371: 	$config{'CODElocation'}=$config[2];
 5372: 	$config{'CODEstart'}=$config[3];
 5373: 	$config{'CODElength'}=$config[4];
 5374: 	$config{'IDstart'}=$config[5];
 5375: 	$config{'IDlength'}=$config[6];
 5376: 	$config{'Qstart'}=$config[7];
 5377:  	$config{'Qlength'}=$config[8];
 5378: 	$config{'Qoff'}=$config[9];
 5379: 	$config{'Qon'}=$config[10];
 5380: 	$config{'PaperID'}=$config[11];
 5381: 	$config{'PaperIDlength'}=$config[12];
 5382: 	$config{'FirstName'}=$config[13];
 5383: 	$config{'FirstNamelength'}=$config[14];
 5384: 	$config{'LastName'}=$config[15];
 5385: 	$config{'LastNamelength'}=$config[16];
 5386: 	last;
 5387:     }
 5388:     return %config;
 5389: }
 5390: 
 5391: =pod 
 5392: 
 5393: =item username_to_idmap
 5394: 
 5395:     creates a hash keyed by student id with values of the corresponding
 5396:     student username:domain.
 5397: 
 5398:   Arguments:
 5399: 
 5400:     $classlist - reference to the class list hash. This is a hash
 5401:                  keyed by student name:domain  whose elements are references
 5402:                  to arrays containing various chunks of information
 5403:                  about the student. (See loncoursedata for more info).
 5404: 
 5405:   Returns
 5406:     %idmap - the constructed hash
 5407: 
 5408: =cut
 5409: 
 5410: sub username_to_idmap {
 5411:     my ($classlist)= @_;
 5412:     my %idmap;
 5413:     foreach my $student (keys(%$classlist)) {
 5414: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5415: 	    $student;
 5416:     }
 5417:     return %idmap;
 5418: }
 5419: 
 5420: =pod
 5421: 
 5422: =item scantron_fixup_scanline
 5423: 
 5424:    Process a requested correction to a scanline.
 5425: 
 5426:   Arguments:
 5427:     $scantron_config   - hash from &get_scantron_config()
 5428:     $scan_data         - hash of correction information 
 5429:                           (see &scantron_getfile())
 5430:     $line              - existing scanline
 5431:     $whichline         - line number of the passed in scanline
 5432:     $field             - type of change to process 
 5433:                          (either 
 5434:                           'ID'     -> correct the student ID number
 5435:                           'CODE'   -> correct the CODE
 5436:                           'answer' -> fixup the submitted answers)
 5437:     
 5438:    $args               - hash of additional info,
 5439:                           - 'ID' 
 5440:                                'newid' -> studentID to use in replacement
 5441:                                           of existing one
 5442:                           - 'CODE' 
 5443:                                'CODE_ignore_dup' - set to true if duplicates
 5444:                                                    should be ignored.
 5445: 	                       'CODE' - is new code or 'use_unfound'
 5446:                                         if the existing unfound code should
 5447:                                         be used as is
 5448:                           - 'answer'
 5449:                                'response' - new answer or 'none' if blank
 5450:                                'question' - the bubble line to change
 5451:                                'questionnum' - the question identifier,
 5452:                                                may include subquestion. 
 5453: 
 5454:   Returns:
 5455:     $line - the modified scanline
 5456: 
 5457:   Side effects: 
 5458:     $scan_data - may be updated
 5459: 
 5460: =cut
 5461: 
 5462: 
 5463: sub scantron_fixup_scanline {
 5464:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5465:     if ($field eq 'ID') {
 5466: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5467: 	    return ($line,1,'New value too large');
 5468: 	}
 5469: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5470: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5471: 				     $args->{'newid'});
 5472: 	}
 5473: 	substr($line,$$scantron_config{'IDstart'}-1,
 5474: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5475: 	if ($args->{'newid'}=~/^\s*$/) {
 5476: 	    &scan_data($scan_data,"$whichline.user",
 5477: 		       $args->{'username'}.':'.$args->{'domain'});
 5478: 	}
 5479:     } elsif ($field eq 'CODE') {
 5480: 	if ($args->{'CODE_ignore_dup'}) {
 5481: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5482: 	}
 5483: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5484: 	if ($args->{'CODE'} ne 'use_unfound') {
 5485: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5486: 		return ($line,1,'New CODE value too large');
 5487: 	    }
 5488: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5489: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5490: 	    }
 5491: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5492: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5493: 	}
 5494:     } elsif ($field eq 'answer') {
 5495: 	my $length=$scantron_config->{'Qlength'};
 5496: 	my $off=$scantron_config->{'Qoff'};
 5497: 	my $on=$scantron_config->{'Qon'};
 5498: 	my $answer=${off}x$length;
 5499: 	if ($args->{'response'} eq 'none') {
 5500: 	    &scan_data($scan_data,
 5501: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5502: 	} else {
 5503: 	    if ($on eq 'letter') {
 5504: 		my @alphabet=('A'..'Z');
 5505: 		$answer=$alphabet[$args->{'response'}];
 5506: 	    } elsif ($on eq 'number') {
 5507: 		$answer=$args->{'response'}+1;
 5508: 		if ($answer == 10) { $answer = '0'; }
 5509: 	    } else {
 5510: 		substr($answer,$args->{'response'},1)=$on;
 5511: 	    }
 5512: 	    &scan_data($scan_data,
 5513: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5514: 	}
 5515: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5516: 	substr($line,$where-1,$length)=$answer;
 5517:     }
 5518:     return $line;
 5519: }
 5520: 
 5521: =pod
 5522: 
 5523: =item scan_data
 5524: 
 5525:     Edit or look up  an item in the scan_data hash.
 5526: 
 5527:   Arguments:
 5528:     $scan_data  - The hash (see scantron_getfile)
 5529:     $key        - shorthand of the key to edit (actual key is
 5530:                   scantronfilename_key).
 5531:     $data        - New value of the hash entry.
 5532:     $delete      - If true, the entry is removed from the hash.
 5533: 
 5534:   Returns:
 5535:     The new value of the hash table field (undefined if deleted).
 5536: 
 5537: =cut
 5538: 
 5539: 
 5540: sub scan_data {
 5541:     my ($scan_data,$key,$value,$delete)=@_;
 5542:     my $filename=$env{'form.scantron_selectfile'};
 5543:     if (defined($value)) {
 5544: 	$scan_data->{$filename.'_'.$key} = $value;
 5545:     }
 5546:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5547:     return $scan_data->{$filename.'_'.$key};
 5548: }
 5549: 
 5550: # ----- These first few routines are general use routines.----
 5551: 
 5552: # Return the number of occurences of a pattern in a string.
 5553: 
 5554: sub occurence_count {
 5555:     my ($string, $pattern) = @_;
 5556: 
 5557:     my @matches = ($string =~ /$pattern/g);
 5558: 
 5559:     return scalar(@matches);
 5560: }
 5561: 
 5562: 
 5563: # Take a string known to have digits and convert all the
 5564: # digits into letters in the range J,A..I.
 5565: 
 5566: sub digits_to_letters {
 5567:     my ($input) = @_;
 5568: 
 5569:     my @alphabet = ('J', 'A'..'I');
 5570: 
 5571:     my @input    = split(//, $input);
 5572:     my $output ='';
 5573:     for (my $i = 0; $i < scalar(@input); $i++) {
 5574: 	if ($input[$i] =~ /\d/) {
 5575: 	    $output .= $alphabet[$input[$i]];
 5576: 	} else {
 5577: 	    $output .= $input[$i];
 5578: 	}
 5579:     }
 5580:     return $output;
 5581: }
 5582: 
 5583: =pod 
 5584: 
 5585: =item scantron_parse_scanline
 5586: 
 5587:   Decodes a scanline from the selected scantron file
 5588: 
 5589:  Arguments:
 5590:     line             - The text of the scantron file line to process
 5591:     whichline        - Line number
 5592:     scantron_config  - Hash describing the format of the scantron lines.
 5593:     scan_data        - Hash of extra information about the scanline
 5594:                        (see scantron_getfile for more information)
 5595:     just_header      - True if should not process question answers but only
 5596:                        the stuff to the left of the answers.
 5597:  Returns:
 5598:    Hash containing the result of parsing the scanline
 5599: 
 5600:    Keys are all proceeded by the string 'scantron.'
 5601: 
 5602:        CODE    - the CODE in use for this scanline
 5603:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5604:                  by the operator
 5605:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5606:                             CODEs were selected, but the usage has been
 5607:                             forced by the operator
 5608:        ID  - student ID
 5609:        PaperID - if used, the ID number printed on the sheet when the 
 5610:                  paper was scanned
 5611:        FirstName - first name from the sheet
 5612:        LastName  - last name from the sheet
 5613: 
 5614:      if just_header was not true these key may also exist
 5615: 
 5616:        missingerror - a list of bubble ranges that are considered to be answers
 5617:                       to a single question that don't have any bubbles filled in.
 5618:                       Of the form questionnumber:firstbubblenumber:count.
 5619:        doubleerror  - a list of bubble ranges that are considered to be answers
 5620:                       to a single question that have more than one bubble filled in.
 5621:                       Of the form questionnumber::firstbubblenumber:count
 5622:    
 5623:                 In the above, count is the number of bubble responses in the
 5624:                 input line needed to represent the possible answers to the question.
 5625:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5626:                 per line would have count = 2.
 5627: 
 5628:        maxquest     - the number of the last bubble line that was parsed
 5629: 
 5630:        (<number> starts at 1)
 5631:        <number>.answer - zero or more letters representing the selected
 5632:                          letters from the scanline for the bubble line 
 5633:                          <number>.
 5634:                          if blank there was either no bubble or there where
 5635:                          multiple bubbles, (consult the keys missingerror and
 5636:                          doubleerror if this is an error condition)
 5637: 
 5638: =cut
 5639: 
 5640: sub scantron_parse_scanline {
 5641:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5642: 
 5643:     my %record;
 5644:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5645:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5646:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5647: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5648: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5649: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5650: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5651: 	    $record{'scantron.CODE'}=substr($data,
 5652: 					    $$scantron_config{'CODEstart'}-1,
 5653: 					    $$scantron_config{'CODElength'});
 5654: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5655: 		$record{'scantron.useCODE'}=1;
 5656: 	    }
 5657: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5658: 		$record{'scantron.CODE_ignore_dup'}=1;
 5659: 	    }
 5660: 	} else {
 5661: 	    #FIXME interpret first N questions
 5662: 	}
 5663:     }
 5664:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5665: 				  $$scantron_config{'IDlength'});
 5666:     $record{'scantron.PaperID'}=
 5667: 	substr($data,$$scantron_config{'PaperID'}-1,
 5668: 	       $$scantron_config{'PaperIDlength'});
 5669:     $record{'scantron.FirstName'}=
 5670: 	substr($data,$$scantron_config{'FirstName'}-1,
 5671: 	       $$scantron_config{'FirstNamelength'});
 5672:     $record{'scantron.LastName'}=
 5673: 	substr($data,$$scantron_config{'LastName'}-1,
 5674: 	       $$scantron_config{'LastNamelength'});
 5675:     if ($just_header) { return \%record; }
 5676: 
 5677:     my @alphabet=('A'..'Z');
 5678:     my $questnum=0;
 5679:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5680: 
 5681:     chomp($questions);		# Get rid of any trailing \n.
 5682:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5683:     while (length($questions)) {
 5684: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5685:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5686:                              || 1;
 5687:         $questnum++;
 5688:         my $quest_id = $questnum;
 5689:         my $currentquest = substr($questions,0,$answer_length);
 5690:         $questions       = substr($questions,$answer_length);
 5691:         if (length($currentquest) < $answer_length) { next; }
 5692: 
 5693:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5694:             my $subquestnum = 1;
 5695:             my $subquestions = $currentquest;
 5696:             my @subanswers_needed = 
 5697:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5698:             foreach my $subans (@subanswers_needed) {
 5699:                 my $subans_length =
 5700:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5701:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5702:                 $subquestions   = substr($subquestions,$subans_length);
 5703:                 $quest_id = "$questnum.$subquestnum";
 5704:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5705:                     ($$scantron_config{'Qon'} eq 'number')) {
 5706:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5707:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5708:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5709:                 } else {
 5710:                     $ansnum = &scantron_validator_positional($ansnum,
 5711:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5712:                 }
 5713:                 $subquestnum ++;
 5714:             }
 5715:         } else {
 5716:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5717:                 ($$scantron_config{'Qon'} eq 'number')) {
 5718:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5719:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5720:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5721:             } else {
 5722:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5723:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5724:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5725:             }
 5726:         }
 5727:     }
 5728:     $record{'scantron.maxquest'}=$questnum;
 5729:     return \%record;
 5730: }
 5731: 
 5732: sub scantron_validator_lettnum {
 5733:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5734:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5735: 
 5736:     # Qon 'letter' implies for each slot in currquest we have:
 5737:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5738:     #    about anything else (esp. a value of Qoff) for missing
 5739:     #    bubbles.
 5740:     #
 5741:     # Qon 'number' implies each slot gives a digit that indexes the
 5742:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5743:     #    and * or ? for double bubbles on a single line.
 5744:     #
 5745: 
 5746:     my $matchon;
 5747:     if ($$scantron_config{'Qon'} eq 'letter') {
 5748:         $matchon = '[A-Z]';
 5749:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5750:         $matchon = '\d';
 5751:     }
 5752:     my $occurrences = 0;
 5753:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5754:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5755:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5756:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5757:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5758:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5759:         my @singlelines = split('',$currquest);
 5760:         foreach my $entry (@singlelines) {
 5761:             $occurrences = &occurence_count($entry,$matchon);
 5762:             if ($occurrences > 1) {
 5763:                 last;
 5764:             }
 5765:         } 
 5766:     } else {
 5767:         $occurrences = &occurence_count($currquest,$matchon); 
 5768:     }
 5769:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5770:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5772:             my $bubble = substr($currquest,$ans,1);
 5773:             if ($bubble =~ /$matchon/ ) {
 5774:                 if ($$scantron_config{'Qon'} eq 'number') {
 5775:                     if ($bubble == 0) {
 5776:                         $bubble = 10; 
 5777:                     }
 5778:                     $record->{"scantron.$ansnum.answer"} = 
 5779:                         $alphabet->[$bubble-1];
 5780:                 } else {
 5781:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5782:                 }
 5783:             } else {
 5784:                 $record->{"scantron.$ansnum.answer"}='';
 5785:             }
 5786:             $ansnum++;
 5787:         }
 5788:     } elsif (!defined($currquest)
 5789:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5790:             || (&occurence_count($currquest,$matchon) == 0)) {
 5791:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5792:             $record->{"scantron.$ansnum.answer"}='';
 5793:             $ansnum++;
 5794:         }
 5795:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5796:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5797:         }
 5798:     } else {
 5799:         if ($$scantron_config{'Qon'} eq 'number') {
 5800:             $currquest = &digits_to_letters($currquest);            
 5801:         }
 5802:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5803:             my $bubble = substr($currquest,$ans,1);
 5804:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5805:             $ansnum++;
 5806:         }
 5807:     }
 5808:     return $ansnum;
 5809: }
 5810: 
 5811: sub scantron_validator_positional {
 5812:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5813:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5814: 
 5815:     # Otherwise there's a positional notation;
 5816:     # each bubble line requires Qlength items, and there are filled in
 5817:     # bubbles for each case where there 'Qon' characters.
 5818:     #
 5819: 
 5820:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5821: 
 5822:     # If the split only gives us one element.. the full length of the
 5823:     # answer string, no bubbles are filled in:
 5824: 
 5825:     if ($answers_needed eq '') {
 5826:         return;
 5827:     }
 5828: 
 5829:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5830:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5831:             $record->{"scantron.$ansnum.answer"}='';
 5832:             $ansnum++;
 5833:         }
 5834:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5835:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5836:         }
 5837:     } elsif (scalar(@array) == 2) {
 5838:         my $location = length($array[0]);
 5839:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5840:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5841:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5842:             if ($ans eq $line_num) {
 5843:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5844:             } else {
 5845:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5846:             }
 5847:             $ansnum++;
 5848:          }
 5849:     } else {
 5850:         #  If there's more than one instance of a bubble character
 5851:         #  That's a double bubble; with positional notation we can
 5852:         #  record all the bubbles filled in as well as the
 5853:         #  fact this response consists of multiple bubbles.
 5854:         #
 5855:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5856:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5857:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5858:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5859:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5860:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5861:             my $doubleerror = 0;
 5862:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5863:                    (!$doubleerror)) {
 5864:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5865:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5866:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5867:                if (length(@currarray) > 2) {
 5868:                    $doubleerror = 1;
 5869:                } 
 5870:             }
 5871:             if ($doubleerror) {
 5872:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5873:             }
 5874:         } else {
 5875:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5876:         }
 5877:         my $item = $ansnum;
 5878:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5879:             $record->{"scantron.$item.answer"} = '';
 5880:             $item ++;
 5881:         }
 5882: 
 5883:         my @ans=@array;
 5884:         my $i=0;
 5885:         my $increment = 0;
 5886:         while ($#ans) {
 5887:             $i+=length($ans[0]) + $increment;
 5888:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5889:             my $bubble = $i%$$scantron_config{'Qlength'};
 5890:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5891:             shift(@ans);
 5892:             $increment = 1;
 5893:         }
 5894:         $ansnum += $answers_needed;
 5895:     }
 5896:     return $ansnum;
 5897: }
 5898: 
 5899: =pod
 5900: 
 5901: =item scantron_add_delay
 5902: 
 5903:    Adds an error message that occurred during the grading phase to a
 5904:    queue of messages to be shown after grading pass is complete
 5905: 
 5906:  Arguments:
 5907:    $delayqueue  - arrary ref of hash ref of error messages
 5908:    $scanline    - the scanline that caused the error
 5909:    $errormesage - the error message
 5910:    $errorcode   - a numeric code for the error
 5911: 
 5912:  Side Effects:
 5913:    updates the $delayqueue to have a new hash ref of the error
 5914: 
 5915: =cut
 5916: 
 5917: sub scantron_add_delay {
 5918:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5919:     push(@$delayqueue,
 5920: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5921: 	  'ecode' => $errorcode }
 5922: 	 );
 5923: }
 5924: 
 5925: =pod
 5926: 
 5927: =item scantron_find_student
 5928: 
 5929:    Finds the username for the current scanline
 5930: 
 5931:   Arguments:
 5932:    $scantron_record - hash result from scantron_parse_scanline
 5933:    $scan_data       - hash of correction information 
 5934:                       (see &scantron_getfile() form more information)
 5935:    $idmap           - hash from &username_to_idmap()
 5936:    $line            - number of current scanline
 5937:  
 5938:   Returns:
 5939:    Either 'username:domain' or undef if unknown
 5940: 
 5941: =cut
 5942: 
 5943: sub scantron_find_student {
 5944:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5945:     my $scanID=$$scantron_record{'scantron.ID'};
 5946:     if ($scanID =~ /^\s*$/) {
 5947:  	return &scan_data($scan_data,"$line.user");
 5948:     }
 5949:     foreach my $id (keys(%$idmap)) {
 5950:  	if (lc($id) eq lc($scanID)) {
 5951:  	    return $$idmap{$id};
 5952:  	}
 5953:     }
 5954:     return undef;
 5955: }
 5956: 
 5957: =pod
 5958: 
 5959: =item scantron_filter
 5960: 
 5961:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5962:    hidden resources was selected
 5963: 
 5964: =cut
 5965: 
 5966: sub scantron_filter {
 5967:     my ($curres)=@_;
 5968: 
 5969:     if (ref($curres) && $curres->is_problem()) {
 5970: 	# if the user has asked to not have either hidden
 5971: 	# or 'randomout' controlled resources to be graded
 5972: 	# don't include them
 5973: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5974: 	    && $curres->randomout) {
 5975: 	    return 0;
 5976: 	}
 5977: 	return 1;
 5978:     }
 5979:     return 0;
 5980: }
 5981: 
 5982: =pod
 5983: 
 5984: =item scantron_process_corrections
 5985: 
 5986:    Gets correction information out of submitted form data and corrects
 5987:    the scanline
 5988: 
 5989: =cut
 5990: 
 5991: sub scantron_process_corrections {
 5992:     my ($r) = @_;
 5993:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5994:     my ($scanlines,$scan_data)=&scantron_getfile();
 5995:     my $classlist=&Apache::loncoursedata::get_classlist();
 5996:     my $which=$env{'form.scantron_line'};
 5997:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5998:     my ($skip,$err,$errmsg);
 5999:     if ($env{'form.scantron_skip_record'}) {
 6000: 	$skip=1;
 6001:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6002: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6003: 	    $env{'form.scantron_domain'};
 6004: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6005: 	($line,$err,$errmsg)=
 6006: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6007: 				     'ID',{'newid'=>$newid,
 6008: 				    'username'=>$env{'form.scantron_username'},
 6009: 				    'domain'=>$env{'form.scantron_domain'}});
 6010:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6011: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6012: 	my $newCODE;
 6013: 	my %args;
 6014: 	if      ($resolution eq 'use_unfound') {
 6015: 	    $newCODE='use_unfound';
 6016: 	} elsif ($resolution eq 'use_found') {
 6017: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6018: 	} elsif ($resolution eq 'use_typed') {
 6019: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6020: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6021: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6022: 	}
 6023: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6024: 	    $args{'CODE_ignore_dup'}=1;
 6025: 	}
 6026: 	$args{'CODE'}=$newCODE;
 6027: 	($line,$err,$errmsg)=
 6028: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6029: 				     'CODE',\%args);
 6030:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6031: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6032: 	    ($line,$err,$errmsg)=
 6033: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6034: 					 $which,'answer',
 6035: 					 { 'question'=>$question,
 6036: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6037:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6038: 	    if ($err) { last; }
 6039: 	}
 6040:     }
 6041:     if ($err) {
 6042: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6043:     } else {
 6044: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6045: 	&scantron_putfile($scanlines,$scan_data);
 6046:     }
 6047: }
 6048: 
 6049: =pod
 6050: 
 6051: =item reset_skipping_status
 6052: 
 6053:    Forgets the current set of remember skipped scanlines (and thus
 6054:    reverts back to considering all lines in the
 6055:    scantron_skipped_<filename> file)
 6056: 
 6057: =cut
 6058: 
 6059: sub reset_skipping_status {
 6060:     my ($scanlines,$scan_data)=&scantron_getfile();
 6061:     &scan_data($scan_data,'remember_skipping',undef,1);
 6062:     &scantron_putfile(undef,$scan_data);
 6063: }
 6064: 
 6065: =pod
 6066: 
 6067: =item start_skipping
 6068: 
 6069:    Marks a scanline to be skipped. 
 6070: 
 6071: =cut
 6072: 
 6073: sub start_skipping {
 6074:     my ($scan_data,$i)=@_;
 6075:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6076:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6077: 	$remembered{$i}=2;
 6078:     } else {
 6079: 	$remembered{$i}=1;
 6080:     }
 6081:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6082: }
 6083: 
 6084: =pod
 6085: 
 6086: =item should_be_skipped
 6087: 
 6088:    Checks whether a scanline should be skipped.
 6089: 
 6090: =cut
 6091: 
 6092: sub should_be_skipped {
 6093:     my ($scanlines,$scan_data,$i)=@_;
 6094:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6095: 	# not redoing old skips
 6096: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6097: 	return 0;
 6098:     }
 6099:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6100: 
 6101:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6102: 	return 0;
 6103:     }
 6104:     return 1;
 6105: }
 6106: 
 6107: =pod
 6108: 
 6109: =item remember_current_skipped
 6110: 
 6111:    Discovers what scanlines are in the scantron_skipped_<filename>
 6112:    file and remembers them into scan_data for later use.
 6113: 
 6114: =cut
 6115: 
 6116: sub remember_current_skipped {
 6117:     my ($scanlines,$scan_data)=&scantron_getfile();
 6118:     my %to_remember;
 6119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6120: 	if ($scanlines->{'skipped'}[$i]) {
 6121: 	    $to_remember{$i}=1;
 6122: 	}
 6123:     }
 6124: 
 6125:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6126:     &scantron_putfile(undef,$scan_data);
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item check_for_error
 6132: 
 6133:     Checks if there was an error when attempting to remove a specific
 6134:     scantron_.. bubble sheet data file. Prints out an error if
 6135:     something went wrong.
 6136: 
 6137: =cut
 6138: 
 6139: sub check_for_error {
 6140:     my ($r,$result)=@_;
 6141:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6142: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6143:     }
 6144: }
 6145: 
 6146: =pod
 6147: 
 6148: =item scantron_warning_screen
 6149: 
 6150:    Interstitial screen to make sure the operator has selected the
 6151:    correct options before we start the validation phase.
 6152: 
 6153: =cut
 6154: 
 6155: sub scantron_warning_screen {
 6156:     my ($button_text)=@_;
 6157:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6158:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6159:     my $CODElist;
 6160:     if ($scantron_config{'CODElocation'} &&
 6161: 	$scantron_config{'CODEstart'} &&
 6162: 	$scantron_config{'CODElength'}) {
 6163: 	$CODElist=$env{'form.scantron_CODElist'};
 6164: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6165: 	$CODElist=
 6166: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6167: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6168:     }
 6169:     return ('
 6170: <p>
 6171: <span class="LC_warning">
 6172: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6173: </p>
 6174: <table>
 6175: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6176: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6177: '.$CODElist.'
 6178: </table>
 6179: <br />
 6180: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6181: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6182: 
 6183: <br />
 6184: ');
 6185: }
 6186: 
 6187: =pod
 6188: 
 6189: =item scantron_do_warning
 6190: 
 6191:    Check if the operator has picked something for all required
 6192:    fields. Error out if something is missing.
 6193: 
 6194: =cut
 6195: 
 6196: sub scantron_do_warning {
 6197:     my ($r)=@_;
 6198:     my ($symb)=&get_symb($r);
 6199:     if (!$symb) {return '';}
 6200:     my $default_form_data=&defaultFormData($symb);
 6201:     $r->print(&scantron_form_start().$default_form_data);
 6202:     if ( $env{'form.selectpage'} eq '' ||
 6203: 	 $env{'form.scantron_selectfile'} eq '' ||
 6204: 	 $env{'form.scantron_format'} eq '' ) {
 6205: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6206: 	if ( $env{'form.selectpage'} eq '') {
 6207: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6208: 	} 
 6209: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6210: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6211: 	} 
 6212: 	if ( $env{'form.scantron_format'} eq '') {
 6213: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6214: 	} 
 6215:     } else {
 6216: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6217: 	$r->print('
 6218: '.$warning.'
 6219: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6220: <input type="hidden" name="command" value="scantron_validate" />
 6221: ');
 6222:     }
 6223:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6224:     return '';
 6225: }
 6226: 
 6227: =pod
 6228: 
 6229: =item scantron_form_start
 6230: 
 6231:     html hidden input for remembering all selected grading options
 6232: 
 6233: =cut
 6234: 
 6235: sub scantron_form_start {
 6236:     my ($max_bubble)=@_;
 6237:     my $result= <<SCANTRONFORM;
 6238: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6239:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6240:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6241:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6242:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6243:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6244:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6245:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6246:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6247:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6248: SCANTRONFORM
 6249: 
 6250:   my $line = 0;
 6251:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6252:        my $chunk =
 6253: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6254:        $chunk .=
 6255: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6256:        $chunk .= 
 6257:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6258:        $chunk .=
 6259:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6260:        $result .= $chunk;
 6261:        $line++;
 6262:    }
 6263:     return $result;
 6264: }
 6265: 
 6266: =pod
 6267: 
 6268: =item scantron_validate_file
 6269: 
 6270:     Dispatch routine for doing validation of a bubble sheet data file.
 6271: 
 6272:     Also processes any necessary information resets that need to
 6273:     occur before validation begins (ignore previous corrections,
 6274:     restarting the skipped records processing)
 6275: 
 6276: =cut
 6277: 
 6278: sub scantron_validate_file {
 6279:     my ($r) = @_;
 6280:     my ($symb)=&get_symb($r);
 6281:     if (!$symb) {return '';}
 6282:     my $default_form_data=&defaultFormData($symb);
 6283:     
 6284:     # do the detection of only doing skipped records first befroe we delete
 6285:     # them when doing the corrections reset
 6286:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6287: 	&reset_skipping_status();
 6288:     }
 6289:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6290: 	&remember_current_skipped();
 6291: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6292:     }
 6293: 
 6294:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6295: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6296: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6297: 	&check_for_error($r,&scantron_remove_scan_data());
 6298: 	$env{'form.scantron_options_ignore'}='done';
 6299:     }
 6300: 
 6301:     if ($env{'form.scantron_corrections'}) {
 6302: 	&scantron_process_corrections($r);
 6303:     }
 6304:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6305:     #get the student pick code ready
 6306:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6307:     my $max_bubble=&scantron_get_maxbubble();
 6308:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6309:     $r->print($result);
 6310:     
 6311:     my @validate_phases=( 'sequence',
 6312: 			  'ID',
 6313: 			  'CODE',
 6314: 			  'doublebubble',
 6315: 			  'missingbubbles');
 6316:     if (!$env{'form.validatepass'}) {
 6317: 	$env{'form.validatepass'} = 0;
 6318:     }
 6319:     my $currentphase=$env{'form.validatepass'};
 6320: 
 6321: 
 6322:     my $stop=0;
 6323:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6324: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6325: 	$r->rflush();
 6326: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6327: 	{
 6328: 	    no strict 'refs';
 6329: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6330: 	}
 6331:     }
 6332:     if (!$stop) {
 6333: 	my $warning=&scantron_warning_screen('Start Grading');
 6334: 	$r->print(&mt('Validation process complete.').'<br />
 6335: '.$warning.'
 6336: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6337: <input type="hidden" name="command" value="scantron_process" />
 6338: ');
 6339: 
 6340:     } else {
 6341: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6342: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6343:     }
 6344:     if ($stop) {
 6345: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6346: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6347: 	    $r->print(' '.&mt('this error').' <br />');
 6348: 
 6349: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6350: 	} else {
 6351:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6352: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6353:             } else {
 6354:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6355:             }
 6356: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6357: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6358: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6359: 	}
 6360:     }
 6361:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6362:     return '';
 6363: }
 6364: 
 6365: 
 6366: =pod
 6367: 
 6368: =item scantron_remove_file
 6369: 
 6370:    Removes the requested bubble sheet data file, makes sure that
 6371:    scantron_original_<filename> is never removed
 6372: 
 6373: 
 6374: =cut
 6375: 
 6376: sub scantron_remove_file {
 6377:     my ($which)=@_;
 6378:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6379:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6380:     my $file='scantron_';
 6381:     if ($which eq 'corrected' || $which eq 'skipped') {
 6382: 	$file.=$which.'_';
 6383:     } else {
 6384: 	return 'refused';
 6385:     }
 6386:     $file.=$env{'form.scantron_selectfile'};
 6387:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6388: }
 6389: 
 6390: 
 6391: =pod
 6392: 
 6393: =item scantron_remove_scan_data
 6394: 
 6395:    Removes all scan_data correction for the requested bubble sheet
 6396:    data file.  (In the case that both the are doing skipped records we need
 6397:    to remember the old skipped lines for the time being so that element
 6398:    persists for a while.)
 6399: 
 6400: =cut
 6401: 
 6402: sub scantron_remove_scan_data {
 6403:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6404:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6405:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6406:     my @todelete;
 6407:     my $filename=$env{'form.scantron_selectfile'};
 6408:     foreach my $key (@keys) {
 6409: 	if ($key=~/^\Q$filename\E_/) {
 6410: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6411: 		$key=~/remember_skipping/) {
 6412: 		next;
 6413: 	    }
 6414: 	    push(@todelete,$key);
 6415: 	}
 6416:     }
 6417:     my $result;
 6418:     if (@todelete) {
 6419: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6420: 				       \@todelete,$cdom,$cname);
 6421:     } else {
 6422: 	$result = 'ok';
 6423:     }
 6424:     return $result;
 6425: }
 6426: 
 6427: 
 6428: =pod
 6429: 
 6430: =item scantron_getfile
 6431: 
 6432:     Fetches the requested bubble sheet data file (all 3 versions), and
 6433:     the scan_data hash
 6434:   
 6435:   Arguments:
 6436:     None
 6437: 
 6438:   Returns:
 6439:     2 hash references
 6440: 
 6441:      - first one has 
 6442:          orig      -
 6443:          corrected -
 6444:          skipped   -  each of which points to an array ref of the specified
 6445:                       file broken up into individual lines
 6446:          count     - number of scanlines
 6447:  
 6448:      - second is the scan_data hash possible keys are
 6449:        ($number refers to scanline numbered $number and thus the key affects
 6450:         only that scanline
 6451:         $bubline refers to the specific bubble line element and the aspects
 6452:         refers to that specific bubble line element)
 6453: 
 6454:        $number.user - username:domain to use
 6455:        $number.CODE_ignore_dup 
 6456:                     - ignore the duplicate CODE error 
 6457:        $number.useCODE
 6458:                     - use the CODE in the scanline as is
 6459:        $number.no_bubble.$bubline
 6460:                     - it is valid that there is no bubbled in bubble
 6461:                       at $number $bubline
 6462:        remember_skipping
 6463:                     - a frozen hash containing keys of $number and values
 6464:                       of either 
 6465:                         1 - we are on a 'do skipped records pass' and plan
 6466:                             on processing this line
 6467:                         2 - we are on a 'do skipped records pass' and this
 6468:                             scanline has been marked to skip yet again
 6469: 
 6470: =cut
 6471: 
 6472: sub scantron_getfile {
 6473:     #FIXME really would prefer a scantron directory
 6474:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6475:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6476:     my $lines;
 6477:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6478: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6479:     my %scanlines;
 6480:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6481:     my $temp=$scanlines{'orig'};
 6482:     $scanlines{'count'}=$#$temp;
 6483: 
 6484:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6485: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6486:     if ($lines eq '-1') {
 6487: 	$scanlines{'corrected'}=[];
 6488:     } else {
 6489: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6490:     }
 6491:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6492: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6493:     if ($lines eq '-1') {
 6494: 	$scanlines{'skipped'}=[];
 6495:     } else {
 6496: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6497:     }
 6498:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6499:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6500:     my %scan_data = @tmp;
 6501:     return (\%scanlines,\%scan_data);
 6502: }
 6503: 
 6504: =pod
 6505: 
 6506: =item lonnet_putfile
 6507: 
 6508:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6509: 
 6510:  Arguments:
 6511:    $contents - data to store
 6512:    $filename - filename to store $contents into
 6513: 
 6514:  Returns:
 6515:    result value from &Apache::lonnet::finishuserfileupload
 6516: 
 6517: =cut
 6518: 
 6519: sub lonnet_putfile {
 6520:     my ($contents,$filename)=@_;
 6521:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6522:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6523:     $env{'form.sillywaytopassafilearound'}=$contents;
 6524:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6525: 
 6526: }
 6527: 
 6528: =pod
 6529: 
 6530: =item scantron_putfile
 6531: 
 6532:     Stores the current version of the bubble sheet data files, and the
 6533:     scan_data hash. (Does not modify the original version only the
 6534:     corrected and skipped versions.
 6535: 
 6536:  Arguments:
 6537:     $scanlines - hash ref that looks like the first return value from
 6538:                  &scantron_getfile()
 6539:     $scan_data - hash ref that looks like the second return value from
 6540:                  &scantron_getfile()
 6541: 
 6542: =cut
 6543: 
 6544: sub scantron_putfile {
 6545:     my ($scanlines,$scan_data) = @_;
 6546:     #FIXME really would prefer a scantron directory
 6547:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6548:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6549:     if ($scanlines) {
 6550: 	my $prefix='scantron_';
 6551: # no need to update orig, shouldn't change
 6552: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6553: #		    $env{'form.scantron_selectfile'});
 6554: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6555: 			$prefix.'corrected_'.
 6556: 			$env{'form.scantron_selectfile'});
 6557: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6558: 			$prefix.'skipped_'.
 6559: 			$env{'form.scantron_selectfile'});
 6560:     }
 6561:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6562: }
 6563: 
 6564: =pod
 6565: 
 6566: =item scantron_get_line
 6567: 
 6568:    Returns the correct version of the scanline
 6569: 
 6570:  Arguments:
 6571:     $scanlines - hash ref that looks like the first return value from
 6572:                  &scantron_getfile()
 6573:     $scan_data - hash ref that looks like the second return value from
 6574:                  &scantron_getfile()
 6575:     $i         - number of the requested line (starts at 0)
 6576: 
 6577:  Returns:
 6578:    A scanline, (either the original or the corrected one if it
 6579:    exists), or undef if the requested scanline should be
 6580:    skipped. (Either because it's an skipped scanline, or it's an
 6581:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6582:    pass.
 6583: 
 6584: =cut
 6585: 
 6586: sub scantron_get_line {
 6587:     my ($scanlines,$scan_data,$i)=@_;
 6588:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6589:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6590:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6591:     return $scanlines->{'orig'}[$i]; 
 6592: }
 6593: 
 6594: =pod
 6595: 
 6596: =item scantron_todo_count
 6597: 
 6598:     Counts the number of scanlines that need processing.
 6599: 
 6600:  Arguments:
 6601:     $scanlines - hash ref that looks like the first return value from
 6602:                  &scantron_getfile()
 6603:     $scan_data - hash ref that looks like the second return value from
 6604:                  &scantron_getfile()
 6605: 
 6606:  Returns:
 6607:     $count - number of scanlines to process
 6608: 
 6609: =cut
 6610: 
 6611: sub get_todo_count {
 6612:     my ($scanlines,$scan_data)=@_;
 6613:     my $count=0;
 6614:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6615: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6616: 	if ($line=~/^[\s\cz]*$/) { next; }
 6617: 	$count++;
 6618:     }
 6619:     return $count;
 6620: }
 6621: 
 6622: =pod
 6623: 
 6624: =item scantron_put_line
 6625: 
 6626:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6627:     data file.
 6628: 
 6629:  Arguments:
 6630:     $scanlines - hash ref that looks like the first return value from
 6631:                  &scantron_getfile()
 6632:     $scan_data - hash ref that looks like the second return value from
 6633:                  &scantron_getfile()
 6634:     $i         - line number to update
 6635:     $newline   - contents of the updated scanline
 6636:     $skip      - if true make the line for skipping and update the
 6637:                  'skipped' file
 6638: 
 6639: =cut
 6640: 
 6641: sub scantron_put_line {
 6642:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6643:     if ($skip) {
 6644: 	$scanlines->{'skipped'}[$i]=$newline;
 6645: 	&start_skipping($scan_data,$i);
 6646: 	return;
 6647:     }
 6648:     $scanlines->{'corrected'}[$i]=$newline;
 6649: }
 6650: 
 6651: =pod
 6652: 
 6653: =item scantron_clear_skip
 6654: 
 6655:    Remove a line from the 'skipped' file
 6656: 
 6657:  Arguments:
 6658:     $scanlines - hash ref that looks like the first return value from
 6659:                  &scantron_getfile()
 6660:     $scan_data - hash ref that looks like the second return value from
 6661:                  &scantron_getfile()
 6662:     $i         - line number to update
 6663: 
 6664: =cut
 6665: 
 6666: sub scantron_clear_skip {
 6667:     my ($scanlines,$scan_data,$i)=@_;
 6668:     if (exists($scanlines->{'skipped'}[$i])) {
 6669: 	undef($scanlines->{'skipped'}[$i]);
 6670: 	return 1;
 6671:     }
 6672:     return 0;
 6673: }
 6674: 
 6675: =pod
 6676: 
 6677: =item scantron_filter_not_exam
 6678: 
 6679:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6680:    filter out resources that are not marked as 'exam' mode
 6681: 
 6682: =cut
 6683: 
 6684: sub scantron_filter_not_exam {
 6685:     my ($curres)=@_;
 6686:     
 6687:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6688: 	# if the user has asked to not have either hidden
 6689: 	# or 'randomout' controlled resources to be graded
 6690: 	# don't include them
 6691: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6692: 	    && $curres->randomout) {
 6693: 	    return 0;
 6694: 	}
 6695: 	return 1;
 6696:     }
 6697:     return 0;
 6698: }
 6699: 
 6700: =pod
 6701: 
 6702: =item scantron_validate_sequence
 6703: 
 6704:     Validates the selected sequence, checking for resource that are
 6705:     not set to exam mode.
 6706: 
 6707: =cut
 6708: 
 6709: sub scantron_validate_sequence {
 6710:     my ($r,$currentphase) = @_;
 6711: 
 6712:     my $navmap=Apache::lonnavmaps::navmap->new();
 6713:     my (undef,undef,$sequence)=
 6714: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6715: 
 6716:     my $map=$navmap->getResourceByUrl($sequence);
 6717: 
 6718:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6719:                                     value="ignore" />');
 6720:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6721: 	my @resources=
 6722: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6723: 	if (@resources) {
 6724: 	    $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>");
 6725: 	    return (1,$currentphase);
 6726: 	}
 6727:     }
 6728: 
 6729:     return (0,$currentphase+1);
 6730: }
 6731: 
 6732: 
 6733: 
 6734: sub scantron_validate_ID {
 6735:     my ($r,$currentphase) = @_;
 6736:     
 6737:     #get student info
 6738:     my $classlist=&Apache::loncoursedata::get_classlist();
 6739:     my %idmap=&username_to_idmap($classlist);
 6740: 
 6741:     #get scantron line setup
 6742:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6743:     my ($scanlines,$scan_data)=&scantron_getfile();
 6744:     
 6745:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6746: 
 6747:     my %found=('ids'=>{},'usernames'=>{});
 6748:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6749: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6750: 	if ($line=~/^[\s\cz]*$/) { next; }
 6751: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6752: 						 $scan_data);
 6753: 	my $id=$$scan_record{'scantron.ID'};
 6754: 	my $found;
 6755: 	foreach my $checkid (keys(%idmap)) {
 6756: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6757: 	}
 6758: 	if ($found) {
 6759: 	    my $username=$idmap{$found};
 6760: 	    if ($found{'ids'}{$found}) {
 6761: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6762: 					 $line,'duplicateID',$found);
 6763: 		return(1,$currentphase);
 6764: 	    } elsif ($found{'usernames'}{$username}) {
 6765: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6766: 					 $line,'duplicateID',$username);
 6767: 		return(1,$currentphase);
 6768: 	    }
 6769: 	    #FIXME store away line we previously saw the ID on to use above
 6770: 	    $found{'ids'}{$found}++;
 6771: 	    $found{'usernames'}{$username}++;
 6772: 	} else {
 6773: 	    if ($id =~ /^\s*$/) {
 6774: 		my $username=&scan_data($scan_data,"$i.user");
 6775: 		if (defined($username) && $found{'usernames'}{$username}) {
 6776: 		    &scantron_get_correction($r,$i,$scan_record,
 6777: 					     \%scantron_config,
 6778: 					     $line,'duplicateID',$username);
 6779: 		    return(1,$currentphase);
 6780: 		} elsif (!defined($username)) {
 6781: 		    &scantron_get_correction($r,$i,$scan_record,
 6782: 					     \%scantron_config,
 6783: 					     $line,'incorrectID');
 6784: 		    return(1,$currentphase);
 6785: 		}
 6786: 		$found{'usernames'}{$username}++;
 6787: 	    } else {
 6788: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6789: 					 $line,'incorrectID');
 6790: 		return(1,$currentphase);
 6791: 	    }
 6792: 	}
 6793:     }
 6794: 
 6795:     return (0,$currentphase+1);
 6796: }
 6797: 
 6798: 
 6799: sub scantron_get_correction {
 6800:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6801: #FIXME in the case of a duplicated ID the previous line, probably need
 6802: #to show both the current line and the previous one and allow skipping
 6803: #the previous one or the current one
 6804: 
 6805:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6806: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6807: 			    " for PaperID <tt>[_1]</tt>",
 6808: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6809:     } else {
 6810: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6811: 			    " in scanline [_1] <pre>[_2]</pre>",
 6812: 			    $i,$line)."</p> \n");
 6813:     }
 6814:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6815: 			  "The name on the paper is [_2],[_3]",
 6816: 			  $$scan_record{'scantron.ID'},
 6817: 			  $$scan_record{'scantron.LastName'},
 6818: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6819: 
 6820:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6821:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6822:                            # Array populated for doublebubble or
 6823:     my @lines_to_correct;  # missingbubble errors to build javascript
 6824:                            # to validate radio button checking   
 6825: 
 6826:     if ($error =~ /ID$/) {
 6827: 	if ($error eq 'incorrectID') {
 6828: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6829: 		      "</p>\n");
 6830: 	} elsif ($error eq 'duplicateID') {
 6831: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6832: 	}
 6833: 	$r->print($message);
 6834: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6835: 	$r->print("\n<ul><li> ");
 6836: 	#FIXME it would be nice if this sent back the user ID and
 6837: 	#could do partial userID matches
 6838: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6839: 				       'scantron_username','scantron_domain'));
 6840: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6841: 	$r->print("\n@".
 6842: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6843: 
 6844: 	$r->print('</li>');
 6845:     } elsif ($error =~ /CODE$/) {
 6846: 	if ($error eq 'incorrectCODE') {
 6847: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6848: 	} elsif ($error eq 'duplicateCODE') {
 6849: 	    $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");
 6850: 	}
 6851: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6852: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6853: 	$r->print($message);
 6854: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6855: 	$r->print("\n<br /> ");
 6856: 	my $i=0;
 6857: 	if ($error eq 'incorrectCODE' 
 6858: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6859: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6860: 	    if ($closest > 0) {
 6861: 		foreach my $testcode (@{$closest}) {
 6862: 		    my $checked='';
 6863: 		    if (!$i) { $checked=' checked="checked" '; }
 6864: 		    $r->print("
 6865:    <label>
 6866:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6867:        ".&mt("Use the similar CODE [_1] instead.",
 6868: 	    "<b><tt>".$testcode."</tt></b>")."
 6869:     </label>
 6870:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6871: 		    $r->print("\n<br />");
 6872: 		    $i++;
 6873: 		}
 6874: 	    }
 6875: 	}
 6876: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6877: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6878: 	    $r->print("
 6879:     <label>
 6880:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6881:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6882: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6883:     </label>");
 6884: 	    $r->print("\n<br />");
 6885: 	}
 6886: 
 6887: 	$r->print(<<ENDSCRIPT);
 6888: <script type="text/javascript">
 6889: function change_radio(field) {
 6890:     var slct=document.scantronupload.scantron_CODE_resolution;
 6891:     var i;
 6892:     for (i=0;i<slct.length;i++) {
 6893:         if (slct[i].value==field) { slct[i].checked=true; }
 6894:     }
 6895: }
 6896: </script>
 6897: ENDSCRIPT
 6898: 	my $href="/adm/pickcode?".
 6899: 	   "form=".&escape("scantronupload").
 6900: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6901: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6902: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6903: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6904: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6905: 	    $r->print("
 6906:     <label>
 6907:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6908:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6909: 	     "<a target='_blank' href='$href'>","</a>")."
 6910:     </label> 
 6911:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
 6912: 	    $r->print("\n<br />");
 6913: 	}
 6914: 	$r->print("
 6915:     <label>
 6916:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6917:        ".&mt("Use [_1] as the CODE.",
 6918: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6919: 	$r->print("\n<br /><br />");
 6920:     } elsif ($error eq 'doublebubble') {
 6921: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6922: 
 6923: 	# The form field scantron_questions is acutally a list of line numbers.
 6924: 	# represented by this form so:
 6925: 
 6926: 	my $line_list = &questions_to_line_list($arg);
 6927: 
 6928: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6929: 		  $line_list.'" />');
 6930: 	$r->print($message);
 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6932: 	foreach my $question (@{$arg}) {
 6933: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6934:                                                    $scan_record, $error);
 6935:             push(@lines_to_correct,@linenums);
 6936: 	}
 6937:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6938:     } elsif ($error eq 'missingbubble') {
 6939: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6940: 	$r->print($message);
 6941: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6942: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6943: 
 6944: 	# The form field scantron_questions is actually a list of line numbers not
 6945: 	# a list of question numbers. Therefore:
 6946: 	#
 6947: 	
 6948: 	my $line_list = &questions_to_line_list($arg);
 6949: 
 6950: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6951: 		  $line_list.'" />');
 6952: 	foreach my $question (@{$arg}) {
 6953: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6954:                                                    $scan_record, $error);
 6955:             push(@lines_to_correct,@linenums);
 6956: 	}
 6957:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6958:     } else {
 6959: 	$r->print("\n<ul>");
 6960:     }
 6961:     $r->print("\n</li></ul>");
 6962: }
 6963: 
 6964: sub verify_bubbles_checked {
 6965:     my (@ansnums) = @_;
 6966:     my $ansnumstr = join('","',@ansnums);
 6967:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6968:     my $output = (<<ENDSCRIPT);
 6969: <script type="text/javascript">
 6970: function verify_bubble_radio(form) {
 6971:     var ansnumArray = new Array ("$ansnumstr");
 6972:     var need_bubble_count = 0;
 6973:     for (var i=0; i<ansnumArray.length; i++) {
 6974:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6975:             var bubble_picked = 0; 
 6976:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6977:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6978:                     bubble_picked = 1;
 6979:                 }
 6980:             }
 6981:             if (bubble_picked == 0) {
 6982:                 need_bubble_count ++;
 6983:             }
 6984:         }
 6985:     }
 6986:     if (need_bubble_count) {
 6987:         alert("$warning");
 6988:         return;
 6989:     }
 6990:     form.submit(); 
 6991: }
 6992: </script>
 6993: ENDSCRIPT
 6994:     return $output;
 6995: }
 6996: 
 6997: =pod
 6998: 
 6999: =item  questions_to_line_list
 7000: 
 7001: Converts a list of questions into a string of comma separated
 7002: line numbers in the answer sheet used by the questions.  This is
 7003: used to fill in the scantron_questions form field.
 7004: 
 7005:   Arguments:
 7006:      questions    - Reference to an array of questions.
 7007: 
 7008: =cut
 7009: 
 7010: 
 7011: sub questions_to_line_list {
 7012:     my ($questions) = @_;
 7013:     my @lines;
 7014: 
 7015:     foreach my $item (@{$questions}) {
 7016:         my $question = $item;
 7017:         my ($first,$count,$last);
 7018:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7019:             $question = $1;
 7020:             my $subquestion = $2;
 7021:             $first = $first_bubble_line{$question-1} + 1;
 7022:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7023:             my $subcount = 1;
 7024:             while ($subcount<$subquestion) {
 7025:                 $first += $subans[$subcount-1];
 7026:                 $subcount ++;
 7027:             }
 7028:             $count = $subans[$subquestion-1];
 7029:         } else {
 7030: 	    $first   = $first_bubble_line{$question-1} + 1;
 7031: 	    $count   = $bubble_lines_per_response{$question-1};
 7032:         }
 7033:         $last = $first+$count-1;
 7034:         push(@lines, ($first..$last));
 7035:     }
 7036:     return join(',', @lines);
 7037: }
 7038: 
 7039: =pod 
 7040: 
 7041: =item prompt_for_corrections
 7042: 
 7043: Prompts for a potentially multiline correction to the
 7044: user's bubbling (factors out common code from scantron_get_correction
 7045: for multi and missing bubble cases).
 7046: 
 7047:  Arguments:
 7048:    $r           - Apache request object.
 7049:    $question    - The question number to prompt for.
 7050:    $scan_config - The scantron file configuration hash.
 7051:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7052:    $error       - Type of error
 7053: 
 7054:  Implicit inputs:
 7055:    %bubble_lines_per_response   - Starting line numbers for each question.
 7056:                                   Numbered from 0 (but question numbers are from
 7057:                                   1.
 7058:    %first_bubble_line           - Starting bubble line for each question.
 7059:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7060:                                   type problems render as separate sub-questions, 
 7061:                                   in exam mode. This hash contains a 
 7062:                                   comma-separated list of the lines per 
 7063:                                   sub-question.
 7064:    %responsetype_per_response   - essayresponse, formularesponse,
 7065:                                   stringresponse, imageresponse, reactionresponse,
 7066:                                   and organicresponse type problem parts can have
 7067:                                   multiple lines per response if the weight
 7068:                                   assigned exceeds 10.  In this case, only
 7069:                                   one bubble per line is permitted, but more 
 7070:                                   than one line might contain bubbles, e.g.
 7071:                                   bubbling of: line 1 - J, line 2 - J, 
 7072:                                   line 3 - B would assign 22 points.  
 7073: 
 7074: =cut
 7075: 
 7076: sub prompt_for_corrections {
 7077:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7078:     my ($current_line,$lines);
 7079:     my @linenums;
 7080:     my $questionnum = $question;
 7081:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7082:         $question = $1;
 7083:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7084:         my $subquestion = $2;
 7085:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7086:         my $subcount = 1;
 7087:         while ($subcount<$subquestion) {
 7088:             $current_line += $subans[$subcount-1];
 7089:             $subcount ++;
 7090:         }
 7091:         $lines = $subans[$subquestion-1];
 7092:     } else {
 7093:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7094:         $lines        = $bubble_lines_per_response{$question-1};
 7095:     }
 7096:     if ($lines > 1) {
 7097:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7098:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7099:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7100:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7101:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7102:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7103:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7104:             $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 />');
 7105:         } else {
 7106:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7107:         }
 7108:     }
 7109:     for (my $i =0; $i < $lines; $i++) {
 7110:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7111: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7112: 	        		  $questionnum,$error,split('', $selected));
 7113:         push(@linenums,$current_line);
 7114: 	$current_line++;
 7115:     }
 7116:     if ($lines > 1) {
 7117: 	$r->print("<hr /><br />");
 7118:     }
 7119:     return @linenums;
 7120: }
 7121: 
 7122: =pod
 7123: 
 7124: =item scantron_bubble_selector
 7125:   
 7126:    Generates the html radiobuttons to correct a single bubble line
 7127:    possibly showing the existing the selected bubbles if known
 7128: 
 7129:  Arguments:
 7130:     $r           - Apache request object
 7131:     $scan_config - hash from &get_scantron_config()
 7132:     $line        - Number of the line being displayed.
 7133:     $questionnum - Question number (may include subquestion)
 7134:     $error       - Type of error.
 7135:     @selected    - Array of bubbles picked on this line.
 7136: 
 7137: =cut
 7138: 
 7139: sub scantron_bubble_selector {
 7140:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7141:     my $max=$$scan_config{'Qlength'};
 7142: 
 7143:     my $scmode=$$scan_config{'Qon'};
 7144:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7145: 
 7146:     my @alphabet=('A'..'Z');
 7147:     $r->print(&Apache::loncommon::start_data_table().
 7148:               &Apache::loncommon::start_data_table_row());
 7149:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7150:     for (my $i=0;$i<$max+1;$i++) {
 7151: 	$r->print("\n".'<td align="center">');
 7152: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7153: 	else { $r->print('&nbsp;'); }
 7154: 	$r->print('</td>');
 7155:     }
 7156:     $r->print(&Apache::loncommon::end_data_table_row().
 7157:               &Apache::loncommon::start_data_table_row());
 7158:     for (my $i=0;$i<$max;$i++) {
 7159: 	$r->print("\n".
 7160: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7161: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7162:     }
 7163:     my $nobub_checked = ' ';
 7164:     if ($error eq 'missingbubble') {
 7165:         $nobub_checked = ' checked = "checked" ';
 7166:     }
 7167:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7168: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7169:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7170:               $line.'" value="'.$questionnum.'" /></td>');
 7171:     $r->print(&Apache::loncommon::end_data_table_row().
 7172:               &Apache::loncommon::end_data_table());
 7173: }
 7174: 
 7175: =pod
 7176: 
 7177: =item num_matches
 7178: 
 7179:    Counts the number of characters that are the same between the two arguments.
 7180: 
 7181:  Arguments:
 7182:    $orig - CODE from the scanline
 7183:    $code - CODE to match against
 7184: 
 7185:  Returns:
 7186:    $count - integer count of the number of same characters between the
 7187:             two arguments
 7188: 
 7189: =cut
 7190: 
 7191: sub num_matches {
 7192:     my ($orig,$code) = @_;
 7193:     my @code=split(//,$code);
 7194:     my @orig=split(//,$orig);
 7195:     my $same=0;
 7196:     for (my $i=0;$i<scalar(@code);$i++) {
 7197: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7198:     }
 7199:     return $same;
 7200: }
 7201: 
 7202: =pod
 7203: 
 7204: =item scantron_get_closely_matching_CODEs
 7205: 
 7206:    Cycles through all CODEs and finds the set that has the greatest
 7207:    number of same characters as the provided CODE
 7208: 
 7209:  Arguments:
 7210:    $allcodes - hash ref returned by &get_codes()
 7211:    $CODE     - CODE from the current scanline
 7212: 
 7213:  Returns:
 7214:    2 element list
 7215:     - first elements is number of how closely matching the best fit is 
 7216:       (5 means best set has 5 matching characters)
 7217:     - second element is an arrary ref containing the set of valid CODEs
 7218:       that best fit the passed in CODE
 7219: 
 7220: =cut
 7221: 
 7222: sub scantron_get_closely_matching_CODEs {
 7223:     my ($allcodes,$CODE)=@_;
 7224:     my @CODEs;
 7225:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7226: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7227:     }
 7228: 
 7229:     return ($#CODEs,$CODEs[-1]);
 7230: }
 7231: 
 7232: =pod
 7233: 
 7234: =item get_codes
 7235: 
 7236:    Builds a hash which has keys of all of the valid CODEs from the selected
 7237:    set of remembered CODEs.
 7238: 
 7239:  Arguments:
 7240:   $old_name - name of the set of remembered CODEs
 7241:   $cdom     - domain of the course
 7242:   $cnum     - internal course name
 7243: 
 7244:  Returns:
 7245:   %allcodes - keys are the valid CODEs, values are all 1
 7246: 
 7247: =cut
 7248: 
 7249: sub get_codes {
 7250:     my ($old_name, $cdom, $cnum) = @_;
 7251:     if (!$old_name) {
 7252: 	$old_name=$env{'form.scantron_CODElist'};
 7253:     }
 7254:     if (!$cdom) {
 7255: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7256:     }
 7257:     if (!$cnum) {
 7258: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7259:     }
 7260:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7261: 				    $cdom,$cnum);
 7262:     my %allcodes;
 7263:     if ($result{"type\0$old_name"} eq 'number') {
 7264: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7265:     } else {
 7266: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7267:     }
 7268:     return %allcodes;
 7269: }
 7270: 
 7271: =pod
 7272: 
 7273: =item scantron_validate_CODE
 7274: 
 7275:    Validates all scanlines in the selected file to not have any
 7276:    invalid or underspecified CODEs and that none of the codes are
 7277:    duplicated if this was requested.
 7278: 
 7279: =cut
 7280: 
 7281: sub scantron_validate_CODE {
 7282:     my ($r,$currentphase) = @_;
 7283:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7284:     if ($scantron_config{'CODElocation'} &&
 7285: 	$scantron_config{'CODEstart'} &&
 7286: 	$scantron_config{'CODElength'}) {
 7287: 	if (!defined($env{'form.scantron_CODElist'})) {
 7288: 	    &FIXME_blow_up()
 7289: 	}
 7290:     } else {
 7291: 	return (0,$currentphase+1);
 7292:     }
 7293:     
 7294:     my %usedCODEs;
 7295: 
 7296:     my %allcodes=&get_codes();
 7297: 
 7298:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7299: 
 7300:     my ($scanlines,$scan_data)=&scantron_getfile();
 7301:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7302: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7303: 	if ($line=~/^[\s\cz]*$/) { next; }
 7304: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7305: 						 $scan_data);
 7306: 	my $CODE=$$scan_record{'scantron.CODE'};
 7307: 	my $error=0;
 7308: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7309: 	    &scantron_get_correction($r,$i,$scan_record,
 7310: 				     \%scantron_config,
 7311: 				     $line,'incorrectCODE',\%allcodes);
 7312: 	    return(1,$currentphase);
 7313: 	}
 7314: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7315: 	    && !$$scan_record{'scantron.useCODE'}) {
 7316: 	    &scantron_get_correction($r,$i,$scan_record,
 7317: 				     \%scantron_config,
 7318: 				     $line,'incorrectCODE',\%allcodes);
 7319: 	    return(1,$currentphase);
 7320: 	}
 7321: 	if (exists($usedCODEs{$CODE}) 
 7322: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7323: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7324: 	    &scantron_get_correction($r,$i,$scan_record,
 7325: 				     \%scantron_config,
 7326: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7327: 	    return(1,$currentphase);
 7328: 	}
 7329: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7330:     }
 7331:     return (0,$currentphase+1);
 7332: }
 7333: 
 7334: =pod
 7335: 
 7336: =item scantron_validate_doublebubble
 7337: 
 7338:    Validates all scanlines in the selected file to not have any
 7339:    bubble lines with multiple bubbles marked.
 7340: 
 7341: =cut
 7342: 
 7343: sub scantron_validate_doublebubble {
 7344:     my ($r,$currentphase) = @_;
 7345:     #get student info
 7346:     my $classlist=&Apache::loncoursedata::get_classlist();
 7347:     my %idmap=&username_to_idmap($classlist);
 7348: 
 7349:     #get scantron line setup
 7350:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7351:     my ($scanlines,$scan_data)=&scantron_getfile();
 7352:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7353: 
 7354:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7355: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7356: 	if ($line=~/^[\s\cz]*$/) { next; }
 7357: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7358: 						 $scan_data);
 7359: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7360: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7361: 				 'doublebubble',
 7362: 				 $$scan_record{'scantron.doubleerror'});
 7363:     	return (1,$currentphase);
 7364:     }
 7365:     return (0,$currentphase+1);
 7366: }
 7367: 
 7368: 
 7369: sub scantron_get_maxbubble {
 7370:     if (defined($env{'form.scantron_maxbubble'}) &&
 7371: 	$env{'form.scantron_maxbubble'}) {
 7372: 	&restore_bubble_lines();
 7373: 	return $env{'form.scantron_maxbubble'};
 7374:     }
 7375: 
 7376:     my (undef, undef, $sequence) =
 7377: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7378: 
 7379:     my $navmap=Apache::lonnavmaps::navmap->new();
 7380:     my $map=$navmap->getResourceByUrl($sequence);
 7381:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7382: 
 7383:     &Apache::lonxml::clear_problem_counter();
 7384: 
 7385:     my $uname       = $env{'form.student'};
 7386:     my $udom        = $env{'form.userdom'};
 7387:     my $cid         = $env{'request.course.id'};
 7388:     my $total_lines = 0;
 7389:     %bubble_lines_per_response = ();
 7390:     %first_bubble_line         = ();
 7391:     %subdivided_bubble_lines   = ();
 7392:     %responsetype_per_response = ();
 7393:   
 7394:     my $response_number = 0;
 7395:     my $bubble_line     = 0;
 7396:     foreach my $resource (@resources) {
 7397:         my $symb = $resource->symb();
 7398: 
 7399:         my (@parts,@allparts,@possible_parts);
 7400: 
 7401:         # Need to retrieve part IDs and response IDs because essayresponse,
 7402:         # reactionresponse and organicresponse items are not included in 
 7403:         # $analysis{'parts'} from lonnet::ssi.  
 7404:         if (ref($resource->parts()) eq 'ARRAY') {
 7405:             foreach my $part (@{$resource->parts()}) {
 7406:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
 7407:                     my @resp_ids = $resource->responseIds($part);
 7408:                     foreach my $id (@resp_ids) {
 7409:                         my $part_id = $part.'.'.$id;
 7410:                         push(@possible_parts,$part_id);
 7411:                     }
 7412:                 }
 7413:             }
 7414:         }
 7415: 
 7416:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7417:                                         ('symb' => $symb,
 7418:                                          'grade_target' => 'analyze',
 7419:                                          'grade_courseid' => $cid,
 7420:                                          'grade_domain' => $udom,
 7421:                                          'grade_username' => $uname));
 7422:         my (undef, $an) =
 7423:             split(/_HASH_REF__/,$result, 2);
 7424: 
 7425: 	my %analysis = &Apache::lonnet::str2hash($an);
 7426: 
 7427:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7428:             foreach my $part (@{$analysis{'parts'}}) {
 7429:                 my ($id,$respid) = split(/\./,$part);
 7430:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7431:                     push(@parts,$part);
 7432:                 }
 7433:             }
 7434:         }
 7435:         # Add part_ids for any essayresponse, reactionresponse or 
 7436:         # organicresponse items. 
 7437:         foreach my $part_id (@possible_parts) {
 7438:             if (grep(/^\Q$part_id\E$/,@parts)) {
 7439:                 push(@allparts,$part_id);
 7440:             } else {
 7441:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
 7442:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
 7443:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
 7444:                     push(@allparts,$part_id);
 7445:                 }
 7446:             }
 7447:         }
 7448: 
 7449: 	foreach my $part_id (@allparts) {
 7450:             my $lines;
 7451: 
 7452: 	    # TODO - make this a persistent hash not an array.
 7453: 
 7454:             # optionresponse, matchresponse and rankresponse type items 
 7455:             # render as separate sub-questions in exam mode.
 7456:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
 7457:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
 7458:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
 7459:                 my ($numbub,$numshown);
 7460:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
 7461:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
 7462:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
 7463:                     }
 7464:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
 7465:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
 7466:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
 7467:                     }
 7468:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
 7469:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
 7470:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
 7471:                     }
 7472:                 }
 7473:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
 7474:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
 7475:                 }
 7476:                 my $bubbles_per_line = 10;
 7477:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7478:                 if (($numbub % $bubbles_per_line) != 0) {
 7479:                     $inner_bubble_lines++;
 7480:                 }
 7481:                 for (my $i=0; $i<$numshown; $i++) {
 7482:                     $subdivided_bubble_lines{$response_number} .= 
 7483:                         $inner_bubble_lines.',';
 7484:                 }
 7485:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7486:                 $lines = $numshown * $inner_bubble_lines;
 7487:             } else {
 7488:                 $lines = $analysis{"$part_id.bubble_lines"};
 7489:             } 
 7490: 
 7491:             $first_bubble_line{$response_number} = $bubble_line;
 7492: 	    $bubble_lines_per_response{$response_number} = $lines;
 7493:             $responsetype_per_response{$response_number} = 
 7494:                 $analysis{$part_id.'.type'};
 7495: 	    $response_number++;
 7496: 
 7497: 	    $bubble_line +=  $lines;
 7498: 	    $total_lines +=  $lines;
 7499: 	}
 7500: 
 7501:     }
 7502:     &Apache::lonnet::delenv('scantron\.');
 7503: 
 7504:     &save_bubble_lines();
 7505:     $env{'form.scantron_maxbubble'} =
 7506: 	$total_lines;
 7507:     return $env{'form.scantron_maxbubble'};
 7508: }
 7509: 
 7510: 
 7511: sub scantron_validate_missingbubbles {
 7512:     my ($r,$currentphase) = @_;
 7513:     #get student info
 7514:     my $classlist=&Apache::loncoursedata::get_classlist();
 7515:     my %idmap=&username_to_idmap($classlist);
 7516: 
 7517:     #get scantron line setup
 7518:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7519:     my ($scanlines,$scan_data)=&scantron_getfile();
 7520:     my $max_bubble=&scantron_get_maxbubble();
 7521:     if (!$max_bubble) { $max_bubble=2**31; }
 7522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7524: 	if ($line=~/^[\s\cz]*$/) { next; }
 7525: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7526: 						 $scan_data);
 7527: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7528: 	my @to_correct;
 7529: 	
 7530: 	# Probably here's where the error is...
 7531: 
 7532: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7533:             my $lastbubble;
 7534:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7535:                my $question = $1;
 7536:                my $subquestion = $2;
 7537:                if (!defined($first_bubble_line{$question -1})) { next; }
 7538:                my $first = $first_bubble_line{$question-1};
 7539:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7540:                my $subcount = 1;
 7541:                while ($subcount<$subquestion) {
 7542:                    $first += $subans[$subcount-1];
 7543:                    $subcount ++;
 7544:                }
 7545:                my $count = $subans[$subquestion-1];
 7546:                $lastbubble = $first + $count;
 7547:             } else {
 7548:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7549:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7550:             }
 7551:             if ($lastbubble > $max_bubble) { next; }
 7552: 	    push(@to_correct,$missing);
 7553: 	}
 7554: 	if (@to_correct) {
 7555: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7556: 				     $line,'missingbubble',\@to_correct);
 7557: 	    return (1,$currentphase);
 7558: 	}
 7559: 
 7560:     }
 7561:     return (0,$currentphase+1);
 7562: }
 7563: 
 7564: 
 7565: sub scantron_process_students {
 7566:     my ($r) = @_;
 7567: 
 7568:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7569:     my ($symb)=&get_symb($r);
 7570:     if (!$symb) {
 7571: 	return '';
 7572:     }
 7573:     my $default_form_data=&defaultFormData($symb);
 7574: 
 7575:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7576:     my ($scanlines,$scan_data)=&scantron_getfile();
 7577:     my $classlist=&Apache::loncoursedata::get_classlist();
 7578:     my %idmap=&username_to_idmap($classlist);
 7579:     my $navmap=Apache::lonnavmaps::navmap->new();
 7580:     my $map=$navmap->getResourceByUrl($sequence);
 7581:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7582: #    $r->print("geto ".scalar(@resources)."<br />");
 7583:     my $result= <<SCANTRONFORM;
 7584: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7585:   <input type="hidden" name="command" value="scantron_configphase" />
 7586:   $default_form_data
 7587: SCANTRONFORM
 7588:     $r->print($result);
 7589: 
 7590:     my @delayqueue;
 7591:     my %completedstudents;
 7592:     
 7593:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7594:     my $count=&get_todo_count($scanlines,$scan_data);
 7595:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7596:  				    'Scantron Progress',$count,
 7597: 				    'inline',undef,'scantronupload');
 7598:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7599: 					  'Processing first student');
 7600:     my $start=&Time::HiRes::time();
 7601:     my $i=-1;
 7602:     my ($uname,$udom,$started);
 7603: 
 7604:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7605:     
 7606: 
 7607:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7608:     # the user and return.
 7609: 
 7610:     if ($ssi_error) {
 7611: 	$r->print("</form>");
 7612: 	&ssi_print_error($r);
 7613: 	$r->print(&show_grading_menu_form($symb));
 7614:         &Apache::lonnet::remove_lock($lock);
 7615: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7616:     }
 7617: 
 7618:     while ($i<$scanlines->{'count'}) {
 7619:  	($uname,$udom)=('','');
 7620:  	$i++;
 7621:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7622:  	if ($line=~/^[\s\cz]*$/) { next; }
 7623: 	if ($started) {
 7624: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7625: 						     'last student');
 7626: 	}
 7627: 	$started=1;
 7628:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7629:  						 $scan_data);
 7630:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7631:  					      \%idmap,$i)) {
 7632:   	    &scantron_add_delay(\@delayqueue,$line,
 7633:  				'Unable to find a student that matches',1);
 7634:  	    next;
 7635:   	}
 7636:  	if (exists $completedstudents{$uname}) {
 7637:  	    &scantron_add_delay(\@delayqueue,$line,
 7638:  				'Student '.$uname.' has multiple sheets',2);
 7639:  	    next;
 7640:  	}
 7641:   	($uname,$udom)=split(/:/,$uname);
 7642: 
 7643: 	&Apache::lonxml::clear_problem_counter();
 7644:   	&Apache::lonnet::appenv($scan_record);
 7645: 
 7646: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7647: 	    &scantron_putfile($scanlines,$scan_data);
 7648: 	}
 7649: 	
 7650: 	my $i=0;
 7651: 	foreach my $resource (@resources) {
 7652: 	    $i++;
 7653: 	    my %form=('submitted'     =>'scantron',
 7654: 		      'grade_target'  =>'grade',
 7655: 		      'grade_username'=>$uname,
 7656: 		      'grade_domain'  =>$udom,
 7657: 		      'grade_courseid'=>$env{'request.course.id'},
 7658: 		      'grade_symb'    =>$resource->symb());
 7659: 	    if (exists($scan_record->{'scantron.CODE'})
 7660: 		&& 
 7661: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 7662: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 7663: 	    } else {
 7664: 		$form{'CODE'}='';
 7665: 	    } 
 7666: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
 7667: 	    if ($ssi_error) {
 7668: 		$ssi_error = 0;	# So end of handler error message does not trigger.
 7669: 		$r->print("</form>");
 7670: 		&ssi_print_error($r);
 7671: 		$r->print(&show_grading_menu_form($symb));
 7672:                 &Apache::lonnet::remove_lock($lock);
 7673: 		return '';	# Why return ''?  Beats me.
 7674: 	    }
 7675: 
 7676: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 7677: 	}
 7678: 	$completedstudents{$uname}={'line'=>$line};
 7679: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7680:     } continue {
 7681: 	&Apache::lonxml::clear_problem_counter();
 7682: 	&Apache::lonnet::delenv('scantron\.');
 7683:     }
 7684:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7685:     &Apache::lonnet::remove_lock($lock);
 7686: #    my $lasttime = &Time::HiRes::time()-$start;
 7687: #    $r->print("<p>took $lasttime</p>");
 7688: 
 7689:     $r->print("</form>");
 7690:     $r->print(&show_grading_menu_form($symb));
 7691:     return '';
 7692: }
 7693: 
 7694: sub scantron_upload_scantron_data {
 7695:     my ($r)=@_;
 7696:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7697:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7698: 							  'domainid',
 7699: 							  'coursename');
 7700:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7701: 						   'domainid');
 7702:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7703:     $r->print('
 7704: <script type="text/javascript" language="javascript">
 7705:     function checkUpload(formname) {
 7706: 	if (formname.upfile.value == "") {
 7707: 	    alert("Please use the browse button to select a file from your local directory.");
 7708: 	    return false;
 7709: 	}
 7710: 	formname.submit();
 7711:     }
 7712: </script>
 7713: 
 7714: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7715: '.$default_form_data.'
 7716: <table>
 7717: <tr><td>'.$select_link.'                             </td></tr>
 7718: <tr><td>'.&mt('Course ID:').'     </td>
 7719:     <td><input name="courseid"   type="text" />      </td></tr>
 7720: <tr><td>'.&mt('Course Name:').'   </td>
 7721:     <td><input name="coursename" type="text" />      </td></tr>
 7722: <tr><td>'.&mt('Domain:').'        </td>
 7723:     <td>'.$domsel.'                                  </td></tr>
 7724: <tr><td>'.&mt('File to upload:').'</td>
 7725:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7726: </table>
 7727: <input name="command" value="scantronupload_save" type="hidden" />
 7728: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7729: </form>
 7730: ');
 7731:     return '';
 7732: }
 7733: 
 7734: 
 7735: sub scantron_upload_scantron_data_save {
 7736:     my($r)=@_;
 7737:     my ($symb)=&get_symb($r,1);
 7738:     my $doanotherupload=
 7739: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7740: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7741: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7742: 	'</form>'."\n";
 7743:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7744: 	!&Apache::lonnet::allowed('usc',
 7745: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7746: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7747: 	if ($symb) {
 7748: 	    $r->print(&show_grading_menu_form($symb));
 7749: 	} else {
 7750: 	    $r->print($doanotherupload);
 7751: 	}
 7752: 	return '';
 7753:     }
 7754:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7755:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7756:     my $fname=$env{'form.upfile.filename'};
 7757:     #FIXME
 7758:     #copied from lonnet::userfileupload()
 7759:     #make that function able to target a specified course
 7760:     # Replace Windows backslashes by forward slashes
 7761:     $fname=~s/\\/\//g;
 7762:     # Get rid of everything but the actual filename
 7763:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7764:     # Replace spaces by underscores
 7765:     $fname=~s/\s+/\_/g;
 7766:     # Replace all other weird characters by nothing
 7767:     $fname=~s/[^\w\.\-]//g;
 7768:     # See if there is anything left
 7769:     unless ($fname) { return 'error: no uploaded file'; }
 7770:     my $uploadedfile=$fname;
 7771:     $fname='scantron_orig_'.$fname;
 7772:     if (length($env{'form.upfile'}) < 2) {
 7773: 	$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>"));
 7774:     } else {
 7775: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7776: 	if ($result =~ m|^/uploaded/|) {
 7777: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7778: 			  (length($env{'form.upfile'})-1),
 7779: 			  '<span class="LC_filename">'.$result."</span>"));
 7780: 	} else {
 7781: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7782: 			  $result,
 7783: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7784: 
 7785: 	}
 7786:     }
 7787:     if ($symb) {
 7788: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7789:     } else {
 7790: 	$r->print($doanotherupload);
 7791:     }
 7792:     return '';
 7793: }
 7794: 
 7795: sub valid_file {
 7796:     my ($requested_file)=@_;
 7797:     foreach my $filename (sort(&scantron_filenames())) {
 7798: 	if ($requested_file eq $filename) { return 1; }
 7799:     }
 7800:     return 0;
 7801: }
 7802: 
 7803: sub scantron_download_scantron_data {
 7804:     my ($r)=@_;
 7805:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7806:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7807:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7808:     my $file=$env{'form.scantron_selectfile'};
 7809:     if (! &valid_file($file)) {
 7810: 	$r->print('
 7811: 	<p>
 7812: 	    '.&mt('The requested file name was invalid.').'
 7813:         </p>
 7814: ');
 7815: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7816: 	return;
 7817:     }
 7818:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7819:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7820:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7821:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7822:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7823:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7824:     $r->print('
 7825:     <p>
 7826: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7827: 	      '<a href="'.$orig.'">','</a>').'
 7828:     </p>
 7829:     <p>
 7830: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7831: 	      '<a href="'.$corrected.'">','</a>').'
 7832:     </p>
 7833:     <p>
 7834: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7835: 	      '<a href="'.$skipped.'">','</a>').'
 7836:     </p>
 7837: ');
 7838:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7839:     return '';
 7840: }
 7841: 
 7842: sub checkscantron_results {
 7843:     my ($r) = @_;
 7844:     my ($symb)=&get_symb($r);
 7845:     if (!$symb) {return '';}
 7846:     my $grading_menu_button=&show_grading_menu_form($symb);
 7847:     my $cid = $env{'request.course.id'};
 7848:     my %lettdig = (
 7849:                     A => 1,
 7850:                     B => 2,
 7851:                     C => 3,
 7852:                     D => 4,
 7853:                     E => 5,
 7854:                     F => 6,
 7855:                     G => 7,
 7856:                     H => 8,
 7857:                     I => 9,
 7858:                     J => 0,
 7859:                   );
 7860:     my $numletts = scalar(keys(%lettdig));
 7861:     my $cnum = $env{'course.'.$cid.'.num'};
 7862:     my $cdom = $env{'course.'.$cid.'.domain'};
 7863:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7864:     my %record;
 7865:     my %scantron_config =
 7866:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7867:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7868:     my $classlist=&Apache::loncoursedata::get_classlist();
 7869:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7870:     my $navmap=Apache::lonnavmaps::navmap->new();
 7871:     my $map=$navmap->getResourceByUrl($sequence);
 7872:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7873:     my (%scandata,%lastname,%bylast);
 7874:     $r->print('
 7875: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7876: 
 7877:     my @delayqueue;
 7878:     my %completedstudents;
 7879: 
 7880:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7881:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7882:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7883:                                     'inline',undef,'checkscantron');
 7884:     my ($username,$domain,$uname,$started);
 7885: 
 7886:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7887: 
 7888:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7889:                                           'Processing first student');
 7890:     my $start=&Time::HiRes::time();
 7891:     my $i=-1;
 7892: 
 7893:     while ($i<$scanlines->{'count'}) {
 7894:         ($username,$domain,$uname)=('','','');
 7895:         $i++;
 7896:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7897:         if ($line=~/^[\s\cz]*$/) { next; }
 7898:         if ($started) {
 7899:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7900:                                                      'last student');
 7901:         }
 7902:         $started=1;
 7903:         my $scan_record=
 7904:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7905:                                                      $scan_data);
 7906:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7907:                                                               \%idmap,$i)) {
 7908:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7909:                                 'Unable to find a student that matches',1);
 7910:             next;
 7911:         }
 7912:         if (exists $completedstudents{$uname}) {
 7913:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7914:                                 'Student '.$uname.' has multiple sheets',2);
 7915:             next;
 7916:         }
 7917:         my $pid = $scan_record->{'scantron.ID'};
 7918:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7919:         push(@{$bylast{$lastname{$pid}}},$pid);
 7920:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7921:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7922:         chomp($scandata{$pid});
 7923:         $scandata{$pid} =~ s/\r$//;
 7924:         ($username,$domain)=split(/:/,$uname);
 7925:         my $counter = -1;
 7926:         my (%expected,%startpos);
 7927:         foreach my $resource (@resources) {
 7928:             next if (!$resource->is_problem());
 7929:             my $symb = $resource->symb();
 7930:             my $partsref = $resource->parts();
 7931:             my @parts;
 7932:             my @part_ids = ();
 7933:             if (ref($partsref) eq 'ARRAY') {
 7934:                @parts = @{$partsref};
 7935:                foreach my $part (@parts) {
 7936:                    my @resp_ids = $resource->responseIds($part);
 7937:                    foreach my $resp (@resp_ids) {
 7938:                        $counter ++;
 7939:                        my $part_id = $part.'.'.$resp;
 7940:                        $expected{$part_id} = 0;
 7941:                        push(@part_ids,$part_id);
 7942:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7943:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7944:                            foreach my $item (@sub_lines) {
 7945:                                $expected{$part_id} += $item;
 7946:                            }
 7947:                        } else {
 7948:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7949:                        }
 7950:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7951:                    }
 7952:                 }
 7953:             }
 7954:             if ($symb) {
 7955:                 my %recorded;
 7956:                 my (%returnhash) =
 7957:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7958:                 if ($returnhash{'version'}) {
 7959:                     my %lasthash=();
 7960:                     my $version;
 7961:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
 7962:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7963:                             $lasthash{$key}=$returnhash{$version.':'.$key};
 7964:                         }
 7965:                     }
 7966:                     foreach my $key (keys(%lasthash)) {
 7967:                         if ($key =~ /\.scantron$/) {
 7968:                             my $value = &unescape($lasthash{$key});
 7969:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7970:                             if ($value eq '') {
 7971:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 7972:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
 7973:                                         $recorded{$part_id} .= $;
 7974:                                     }
 7975:                                 }
 7976:                             } else {
 7977:                                 my @tocheck;
 7978:                                 my @items = split(//,$value);
 7979:                                 if (($scantron_config{'Qon'} eq 'letter') ||
 7980:                                     ($scantron_config{'Qon'} eq 'number')) {
 7981:                                     if (@items < $expected{$part_id}) {
 7982:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
 7983:                                         my @singles = split(//,$fragment);
 7984:                                         foreach my $pos (@singles) {
 7985:                                             if ($pos eq ' ') {
 7986:                                                 push(@tocheck,$pos);
 7987:                                             } else {
 7988:                                                 my $next = shift(@items);
 7989:                                                 push(@tocheck,$next);
 7990:                                             }
 7991:                                         }
 7992:                                     } else {
 7993:                                         @tocheck = @items;
 7994:                                     }
 7995:                                     foreach my $letter (@tocheck) {
 7996:                                         if ($scantron_config{'Qon'} eq 'letter') {
 7997:                                             if ($letter !~ /^[A-J]$/) {
 7998:                                                 $letter = $scantron_config{'Qoff'};
 7999:                                             }
 8000:                                             $recorded{$part_id} .= $letter;
 8001:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
 8002:                                             my $digit;
 8003:                                             if ($letter !~ /^[A-J]$/) {
 8004:                                                 $digit = $scantron_config{'Qoff'};
 8005:                                             } else {
 8006:                                                 $digit = $lettdig{$letter};
 8007:                                             }
 8008:                                             $recorded{$part_id} .= $digit;
 8009:                                         }
 8010:                                     }
 8011:                                 } else {
 8012:                                     @tocheck = @items;
 8013:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
 8014:                                         my $curr_sub = shift(@tocheck);
 8015:                                         my $digit;
 8016:                                         if ($curr_sub =~ /^[A-J]$/) {
 8017:                                             $digit = $lettdig{$curr_sub}-1;
 8018:                                         }
 8019:                                         if ($curr_sub eq 'J') {
 8020:                                             $digit += scalar($numletts);
 8021:                                         }
 8022:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8023:                                             if ($j == $digit) {
 8024:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
 8025:                                             } else {
 8026:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8027:                                             }
 8028:                                         }
 8029:                                     }
 8030:                                 }
 8031:                             }
 8032:                         }
 8033:                     }
 8034:                 }
 8035:                 foreach my $part_id (@part_ids) {
 8036:                     if ($recorded{$part_id} eq '') {
 8037:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8038:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8039:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8040:                             }
 8041:                         }
 8042:                     }
 8043:                     $record{$pid} .= $recorded{$part_id};
 8044:                 }
 8045:             }
 8046:         }
 8047:     }
 8048:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8049:     $r->print('<br />');
 8050:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8051:     $passed = 0;
 8052:     $failed = 0;
 8053:     $numstudents = 0;
 8054:     foreach my $last (sort(keys(%bylast))) {
 8055:         if (ref($bylast{$last}) eq 'ARRAY') {
 8056:             foreach my $pid (sort(@{$bylast{$last}})) {
 8057:                 my $showscandata = $scandata{$pid};
 8058:                 my $showrecord = $record{$pid};
 8059:                 $showscandata =~ s/\s/&nbsp;/g;
 8060:                 $showrecord =~ s/\s/&nbsp;/g;
 8061:                 if ($scandata{$pid} eq $record{$pid}) {
 8062:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8063:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8064: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8065: '</tr>'."\n".
 8066: '<tr class="'.$css_class.'">'."\n".
 8067: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8068:                     $passed ++;
 8069:                 } else {
 8070:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8071:                     $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".
 8072: '</tr>'."\n".
 8073: '<tr class="'.$css_class.'">'."\n".
 8074: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8075: '</tr>'."\n";
 8076:                     $failed ++;
 8077:                 }
 8078:                 $numstudents ++;
 8079:             }
 8080:         }
 8081:     }
 8082:     $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>');
 8083:     $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>');
 8084:     if ($passed) {
 8085:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8086:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8087:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8088:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8089:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8090:                  $okstudents."\n".
 8091:                  &Apache::loncommon::end_data_table().'<br />');
 8092:     }
 8093:     if ($failed) {
 8094:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8095:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8096:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8097:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8098:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8099:                  $badstudents."\n".
 8100:                  &Apache::loncommon::end_data_table()).'<br />'.
 8101:                  &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.');  
 8102:     }
 8103:     $r->print('</form><br />'.$grading_menu_button);
 8104:     return;
 8105: }
 8106: 
 8107: 
 8108: #-------- end of section for handling grading scantron forms -------
 8109: #
 8110: #-------------------------------------------------------------------
 8111: 
 8112: #-------------------------- Menu interface -------------------------
 8113: #
 8114: #--- Show a Grading Menu button - Calls the next routine ---
 8115: sub show_grading_menu_form {
 8116:     my ($symb)=@_;
 8117:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8118: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8119: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8120: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8121: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8122: 	'</form>'."\n";
 8123:     return $result;
 8124: }
 8125: 
 8126: # -- Retrieve choices for grading form
 8127: sub savedState {
 8128:     my %savedState = ();
 8129:     if ($env{'form.saveState'}) {
 8130: 	foreach (split(/:/,$env{'form.saveState'})) {
 8131: 	    my ($key,$value) = split(/=/,$_,2);
 8132: 	    $savedState{$key} = $value;
 8133: 	}
 8134:     }
 8135:     return \%savedState;
 8136: }
 8137: 
 8138: sub grading_menu {
 8139:     my ($request) = @_;
 8140:     my ($symb)=&get_symb($request);
 8141:     if (!$symb) {return '';}
 8142:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8143:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8144: 
 8145:     $request->print($table);
 8146:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8147:                   'handgrade'=>$hdgrade,
 8148:                   'probTitle'=>$probTitle,
 8149:                   'command'=>'submit_options',
 8150:                   'saveState'=>"",
 8151:                   'gradingMenu'=>1,
 8152:                   'showgrading'=>"yes");
 8153:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8154:     my @menu = ({ url => $url,
 8155:                      name => &mt('Manual Grading/View Submissions'),
 8156:                      short_description => 
 8157:     &mt('Start the process of hand grading submissions.'),
 8158:                  });
 8159:     $fields{'command'} = 'csvform';
 8160:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8161:     push(@menu, { url => $url,
 8162:                    name => &mt('Upload Scores'),
 8163:                    short_description => 
 8164:             &mt('Specify a file containing the class scores for current resource.')});
 8165:     $fields{'command'} = 'processclicker';
 8166:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8167:     push(@menu, { url => $url,
 8168:                    name => &mt('Process Clicker'),
 8169:                    short_description => 
 8170:             &mt('Specify a file containing the clicker information for this resource.')});
 8171:     $fields{'command'} = 'scantron_selectphase';
 8172:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8173:     push(@menu, { url => $url,
 8174:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8175:                    short_description => 
 8176:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8177:     $fields{'command'} = 'verify';
 8178:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8179:     push(@menu, { url => "",
 8180:                    name => &mt('Verify Receipt'),
 8181:                    short_description => 
 8182:             &mt('')});
 8183:     #
 8184:     # Create the menu
 8185:     my $Str;
 8186:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8187:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8188:     $Str .= '<input type="hidden" name="command" value="" />'.
 8189:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8190: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8191: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8192: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8193: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8194: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8195: 
 8196:     foreach my $menudata (@menu) {
 8197:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8198:             $Str .='    <h3><a '.
 8199:                 $menudata->{'jscript'}.
 8200:                 ' href="'.
 8201:                 $menudata->{'url'}.'" >'.
 8202:                 $menudata->{'name'}."</a></h3>\n";
 8203:         } else {
 8204:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8205:                 $menudata->{'jscript'}.
 8206:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8207:                 ' /> '.
 8208: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8209:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8210:         }
 8211:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8212:             "\n";
 8213:     }
 8214:     $Str .="</form>\n";
 8215:     $request->print(<<GRADINGMENUJS);
 8216: <script type="text/javascript" language="javascript">
 8217:     function checkChoice(formname,val,cmdx) {
 8218: 	if (val <= 2) {
 8219: 	    var cmd = radioSelection(formname.radioChoice);
 8220: 	    var cmdsave = cmd;
 8221: 	} else {
 8222: 	    cmd = cmdx;
 8223: 	    cmdsave = 'submission';
 8224: 	}
 8225: 	formname.command.value = cmd;
 8226: 	if (val < 5) formname.submit();
 8227: 	if (val == 5) {
 8228: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8229: 	        return false;
 8230: 	    } else {
 8231: 	        formname.submit();
 8232: 	    }
 8233: 	}
 8234:     }
 8235: 
 8236:     function checkReceiptNo(formname,nospace) {
 8237: 	var receiptNo = formname.receipt.value;
 8238: 	var checkOpt = false;
 8239: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8240: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8241: 	if (checkOpt) {
 8242: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8243: 	    formname.receipt.value = "";
 8244: 	    formname.receipt.focus();
 8245: 	    return false;
 8246: 	}
 8247: 	return true;
 8248:     }
 8249: </script>
 8250: GRADINGMENUJS
 8251:     &commonJSfunctions($request);
 8252:     return $Str;    
 8253: }
 8254: 
 8255: 
 8256: #--- Displays the submissions first page -------
 8257: sub submit_options {
 8258:     my ($request) = @_;
 8259:     my ($symb)=&get_symb($request);
 8260:     if (!$symb) {return '';}
 8261:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8262: 
 8263:     $request->print(<<GRADINGMENUJS);
 8264: <script type="text/javascript" language="javascript">
 8265:     function checkChoice(formname,val,cmdx) {
 8266: 	if (val <= 2) {
 8267: 	    var cmd = radioSelection(formname.radioChoice);
 8268: 	    var cmdsave = cmd;
 8269: 	} else {
 8270: 	    cmd = cmdx;
 8271: 	    cmdsave = 'submission';
 8272: 	}
 8273: 	formname.command.value = cmd;
 8274: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8275: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8276: 	if (val < 5) formname.submit();
 8277: 	if (val == 5) {
 8278: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8279: 	    formname.submit();
 8280: 	}
 8281: 	if (val < 7) formname.submit();
 8282:     }
 8283: 
 8284:     function checkReceiptNo(formname,nospace) {
 8285: 	var receiptNo = formname.receipt.value;
 8286: 	var checkOpt = false;
 8287: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8288: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8289: 	if (checkOpt) {
 8290: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8291: 	    formname.receipt.value = "";
 8292: 	    formname.receipt.focus();
 8293: 	    return false;
 8294: 	}
 8295: 	return true;
 8296:     }
 8297: </script>
 8298: GRADINGMENUJS
 8299:     &commonJSfunctions($request);
 8300:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8301:     my $result;
 8302:     my (undef,$sections) = &getclasslist('all','0');
 8303:     my $savedState = &savedState();
 8304:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8305:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8306:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8307:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8308: 
 8309:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8310: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8311: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8312: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8313: 	'<input type="hidden" name="command"     value="" />'."\n".
 8314: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8315: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8316: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8317: 
 8318:     $result.='
 8319:     <div class="LC_grade_select_mode">
 8320:       <div class="LC_grade_select_mode_current">
 8321:         <h2>
 8322:           '.&mt('Grade Current Resource').'
 8323:         </h2>
 8324:         <div class="LC_grade_select_mode_body">
 8325:           <div class="LC_grades_resource_info">
 8326:            '.$table.'
 8327:           </div>
 8328:           <div class="LC_grade_select_mode_selector">
 8329:              <div class="LC_grade_select_mode_selector_header">
 8330:                 '.&mt('Sections').'
 8331:              </div>
 8332:              <div class="LC_grade_select_mode_selector_body">
 8333: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8334:     if (ref($sections)) {
 8335: 	foreach my $section (sort(@$sections)) {
 8336: 	    $result.='<option value="'.$section.'" '.
 8337: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8338: 	}
 8339:     }
 8340:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8341:     $result.='
 8342:              </div>
 8343:           </div>
 8344:           <div class="LC_grade_select_mode_selector">
 8345:              <div class="LC_grade_select_mode_selector_header">
 8346:                 '.&mt('Groups').'
 8347:              </div>
 8348:              <div class="LC_grade_select_mode_selector_body">
 8349:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8350:              </div>
 8351:           </div>
 8352:           <div class="LC_grade_select_mode_selector">
 8353:              <div class="LC_grade_select_mode_selector_header">
 8354:                 '.&mt('Access Status').'
 8355:              </div>
 8356:              <div class="LC_grade_select_mode_selector_body">
 8357:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8358:              </div>
 8359:           </div>
 8360:           <div class="LC_grade_select_mode_selector">
 8361:              <div class="LC_grade_select_mode_selector_header">
 8362:                 '.&mt('Submission Status').'
 8363:              </div>
 8364:              <div class="LC_grade_select_mode_selector_body">
 8365:                <select name="submitonly" size="5">
 8366: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8367: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8368: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8369: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8370:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8371:                </select>
 8372:              </div>
 8373:           </div>
 8374:           <div class="LC_grade_select_mode_type_body">
 8375:             <div class="LC_grade_select_mode_type">
 8376:               <label>
 8377:                 <input type="radio" name="radioChoice" value="submission" '.
 8378:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8379:              &mt('Select individual students to grade and view submissions.').'
 8380: 	      </label> 
 8381:             </div>
 8382:             <div class="LC_grade_select_mode_type">
 8383: 	      <label>
 8384:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8385:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8386:                     &mt('Grade all selected students in a grading table.').'
 8387:               </label>
 8388:             </div>
 8389:             <div class="LC_grade_select_mode_type">
 8390: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8391:             </div>
 8392:           </div>
 8393:         </div>
 8394:       </div>
 8395:       <div class="LC_grade_select_mode_page">
 8396:         <h2>
 8397:          '.&mt('Grade Complete Folder for One Student').'
 8398:         </h2>
 8399:         <div class="LC_grades_select_mode_body">
 8400:           <div class="LC_grade_select_mode_type_body">
 8401:             <div class="LC_grade_select_mode_type">
 8402:               <label>
 8403:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8404: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8405:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8406:               </label>
 8407:             </div>
 8408:             <div class="LC_grade_select_mode_type">
 8409: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8410:             </div>
 8411:           </div>
 8412:         </div>
 8413:       </div>
 8414:     </div>
 8415:   </form>';
 8416:     $result .= &show_grading_menu_form($symb);
 8417:     return $result;
 8418: }
 8419: 
 8420: sub reset_perm {
 8421:     undef(%perm);
 8422: }
 8423: 
 8424: sub init_perm {
 8425:     &reset_perm();
 8426:     foreach my $test_perm ('vgr','mgr','opa') {
 8427: 
 8428: 	my $scope = $env{'request.course.id'};
 8429: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8430: 
 8431: 	    $scope .= '/'.$env{'request.course.sec'};
 8432: 	    if ( $perm{$test_perm}=
 8433: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8434: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8435: 	    } else {
 8436: 		delete($perm{$test_perm});
 8437: 	    }
 8438: 	}
 8439:     }
 8440: }
 8441: 
 8442: sub gather_clicker_ids {
 8443:     my %clicker_ids;
 8444: 
 8445:     my $classlist = &Apache::loncoursedata::get_classlist();
 8446: 
 8447:     # Set up a couple variables.
 8448:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8449:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8450:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8451: 
 8452:     foreach my $student (keys(%$classlist)) {
 8453:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8454:         my $username = $classlist->{$student}->[$username_idx];
 8455:         my $domain   = $classlist->{$student}->[$domain_idx];
 8456:         my $clickers =
 8457: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8458:         foreach my $id (split(/\,/,$clickers)) {
 8459:             $id=~s/^[\#0]+//;
 8460:             $id=~s/[\-\:]//g;
 8461:             if (exists($clicker_ids{$id})) {
 8462: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8463:             } else {
 8464: 		$clicker_ids{$id}=$username.':'.$domain;
 8465:             }
 8466:         }
 8467:     }
 8468:     return %clicker_ids;
 8469: }
 8470: 
 8471: sub gather_adv_clicker_ids {
 8472:     my %clicker_ids;
 8473:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8474:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8475:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8476:     foreach my $element (sort(keys(%coursepersonnel))) {
 8477:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8478:             my ($puname,$pudom)=split(/\:/,$person);
 8479:             my $clickers =
 8480: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8481:             foreach my $id (split(/\,/,$clickers)) {
 8482: 		$id=~s/^[\#0]+//;
 8483:                 $id=~s/[\-\:]//g;
 8484: 		if (exists($clicker_ids{$id})) {
 8485: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8486: 		} else {
 8487: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8488: 		}
 8489:             }
 8490:         }
 8491:     }
 8492:     return %clicker_ids;
 8493: }
 8494: 
 8495: sub clicker_grading_parameters {
 8496:     return ('gradingmechanism' => 'scalar',
 8497:             'upfiletype' => 'scalar',
 8498:             'specificid' => 'scalar',
 8499:             'pcorrect' => 'scalar',
 8500:             'pincorrect' => 'scalar');
 8501: }
 8502: 
 8503: sub process_clicker {
 8504:     my ($r)=@_;
 8505:     my ($symb)=&get_symb($r);
 8506:     if (!$symb) {return '';}
 8507:     my $result=&checkforfile_js();
 8508:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8509:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8510:     $result.=$table;
 8511:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8512:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8513:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8514:         '.</b></td></tr>'."\n";
 8515:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8516: # Attempt to restore parameters from last session, set defaults if not present
 8517:     my %Saveable_Parameters=&clicker_grading_parameters();
 8518:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8519:                                                  \%Saveable_Parameters);
 8520:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8521:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8522:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8523:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8524: 
 8525:     my %checked;
 8526:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8527:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8528:           $checked{$gradingmechanism}="checked='checked'";
 8529:        }
 8530:     }
 8531: 
 8532:     my $upload=&mt("Upload File");
 8533:     my $type=&mt("Type");
 8534:     my $attendance=&mt("Award points just for participation");
 8535:     my $personnel=&mt("Correctness determined from response by course personnel");
 8536:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8537:     my $given=&mt("Correctness determined from given list of answers").' '.
 8538:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8539:     my $pcorrect=&mt("Percentage points for correct solution");
 8540:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8541:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8542: 						   ('iclicker' => 'i>clicker',
 8543:                                                     'interwrite' => 'interwrite PRS'));
 8544:     $symb = &Apache::lonenc::check_encrypt($symb);
 8545:     $result.=<<ENDUPFORM;
 8546: <script type="text/javascript">
 8547: function sanitycheck() {
 8548: // Accept only integer percentages
 8549:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8550:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8551: // Find out grading choice
 8552:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8553:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8554:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8555:       }
 8556:    }
 8557: // By default, new choice equals user selection
 8558:    newgradingchoice=gradingchoice;
 8559: // Not good to give more points for false answers than correct ones
 8560:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8561:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8562:    }
 8563: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8564:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8565:       document.forms.gradesupload.pcorrect.value=100;
 8566:       document.forms.gradesupload.pincorrect.value=100;
 8567:    }
 8568: // If the values are different, cannot be attendance only
 8569:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8570:        (gradingchoice=='attendance')) {
 8571:        newgradingchoice='personnel';
 8572:    }
 8573: // Change grading choice to new one
 8574:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8575:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8576:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8577:       } else {
 8578:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8579:       }
 8580:    }
 8581: // Remember the old state
 8582:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8583: }
 8584: </script>
 8585: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8586: <input type="hidden" name="symb" value="$symb" />
 8587: <input type="hidden" name="command" value="processclickerfile" />
 8588: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8589: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8590: <input type="file" name="upfile" size="50" />
 8591: <br /><label>$type: $selectform</label>
 8592: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8593: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8594: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8595: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8596: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8597: <br />&nbsp;&nbsp;&nbsp;
 8598: <input type="text" name="givenanswer" size="50" />
 8599: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8600: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8601: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8602: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8603: </form>
 8604: ENDUPFORM
 8605:     $result.='</td></tr></table>'."\n".
 8606:              '</td></tr></table><br /><br />'."\n";
 8607:     $result.=&show_grading_menu_form($symb);
 8608:     return $result;
 8609: }
 8610: 
 8611: sub process_clicker_file {
 8612:     my ($r)=@_;
 8613:     my ($symb)=&get_symb($r);
 8614:     if (!$symb) {return '';}
 8615: 
 8616:     my %Saveable_Parameters=&clicker_grading_parameters();
 8617:     &Apache::loncommon::store_course_settings('grades_clicker',
 8618:                                               \%Saveable_Parameters);
 8619: 
 8620:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8621:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8622: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8623: 	return $result.&show_grading_menu_form($symb);
 8624:     }
 8625:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8626:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8627:         return $result.&show_grading_menu_form($symb);
 8628:     }
 8629:     my $foundgiven=0;
 8630:     if ($env{'form.gradingmechanism'} eq 'given') {
 8631:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8632:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8633:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8634:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8635:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8636:         $foundgiven=$#answers+1;
 8637:     }
 8638:     my %clicker_ids=&gather_clicker_ids();
 8639:     my %correct_ids;
 8640:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8641: 	%correct_ids=&gather_adv_clicker_ids();
 8642:     }
 8643:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8644: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8645: 	   $correct_id=~tr/a-z/A-Z/;
 8646: 	   $correct_id=~s/\s//gs;
 8647: 	   $correct_id=~s/^[\#0]+//;
 8648:            $correct_id=~s/[\-\:]//g;
 8649:            if ($correct_id) {
 8650: 	      $correct_ids{$correct_id}='specified';
 8651:            }
 8652:         }
 8653:     }
 8654:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8655: 	$result.=&mt('Score based on attendance only');
 8656:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8657:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8658:     } else {
 8659: 	my $number=0;
 8660: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8661: 	foreach my $id (sort(keys(%correct_ids))) {
 8662: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8663: 	    if ($correct_ids{$id} eq 'specified') {
 8664: 		$result.=&mt('specified');
 8665: 	    } else {
 8666: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8667: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8668: 	    }
 8669: 	    $number++;
 8670: 	}
 8671:         $result.="</p>\n";
 8672: 	if ($number==0) {
 8673: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8674: 	    return $result.&show_grading_menu_form($symb);
 8675: 	}
 8676:     }
 8677:     if (length($env{'form.upfile'}) < 2) {
 8678:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8679: 		     '<span class="LC_error">',
 8680: 		     '</span>',
 8681: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8682:         return $result.&show_grading_menu_form($symb);
 8683:     }
 8684: 
 8685: # Were able to get all the info needed, now analyze the file
 8686: 
 8687:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8688:     $symb = &Apache::lonenc::check_encrypt($symb);
 8689:     my $heading=&mt('Scanning clicker file');
 8690:     $result.=(<<ENDHEADER);
 8691: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8692: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8693: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8694: <form method="post" action="/adm/grades" name="clickeranalysis">
 8695: <input type="hidden" name="symb" value="$symb" />
 8696: <input type="hidden" name="command" value="assignclickergrades" />
 8697: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8698: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8699: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8700: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8701: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8702: ENDHEADER
 8703:     if ($env{'form.gradingmechanism'} eq 'given') {
 8704:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8705:     } 
 8706:     my %responses;
 8707:     my @questiontitles;
 8708:     my $errormsg='';
 8709:     my $number=0;
 8710:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8711: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8712:     }
 8713:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8714:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8715:     }
 8716:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8717:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8718:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8719:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8720:              '<br />';
 8721:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8722:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8723:        return $result.&show_grading_menu_form($symb);
 8724:     } 
 8725: # Remember Question Titles
 8726: # FIXME: Possibly need delimiter other than ":"
 8727:     for (my $i=0;$i<$number;$i++) {
 8728:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8729:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8730:     }
 8731:     my $correct_count=0;
 8732:     my $student_count=0;
 8733:     my $unknown_count=0;
 8734: # Match answers with usernames
 8735: # FIXME: Possibly need delimiter other than ":"
 8736:     foreach my $id (keys(%responses)) {
 8737:        if ($correct_ids{$id}) {
 8738:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8739:           $correct_count++;
 8740:        } elsif ($clicker_ids{$id}) {
 8741:           if ($clicker_ids{$id}=~/\,/) {
 8742: # More than one user with the same clicker!
 8743:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8744:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8745:                            "<select name='multi".$id."'>";
 8746:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8747:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8748:              }
 8749:              $result.='</select>';
 8750:              $unknown_count++;
 8751:           } else {
 8752: # Good: found one and only one user with the right clicker
 8753:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8754:              $student_count++;
 8755:           }
 8756:        } else {
 8757:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8758:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8759:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8760:                    "\n".&mt("Domain").": ".
 8761:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8762:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8763:           $unknown_count++;
 8764:        }
 8765:     }
 8766:     $result.='<hr />'.
 8767:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8768:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8769:        if ($correct_count==0) {
 8770:           $errormsg.="Found no correct answers answers for grading!";
 8771:        } elsif ($correct_count>1) {
 8772:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8773:        }
 8774:     }
 8775:     if ($number<1) {
 8776:        $errormsg.="Found no questions.";
 8777:     }
 8778:     if ($errormsg) {
 8779:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8780:     } else {
 8781:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8782:     }
 8783:     $result.='</form></td></tr></table>'."\n".
 8784:              '</td></tr></table><br /><br />'."\n";
 8785:     return $result.&show_grading_menu_form($symb);
 8786: }
 8787: 
 8788: sub iclicker_eval {
 8789:     my ($questiontitles,$responses)=@_;
 8790:     my $number=0;
 8791:     my $errormsg='';
 8792:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8793:         my %components=&Apache::loncommon::record_sep($line);
 8794:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8795: 	if ($entries[0] eq 'Question') {
 8796: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8797: 		$$questiontitles[$number]=$entries[$i];
 8798: 		$number++;
 8799: 	    }
 8800: 	}
 8801: 	if ($entries[0]=~/^\#/) {
 8802: 	    my $id=$entries[0];
 8803: 	    my @idresponses;
 8804: 	    $id=~s/^[\#0]+//;
 8805: 	    for (my $i=0;$i<$number;$i++) {
 8806: 		my $idx=3+$i*6;
 8807: 		push(@idresponses,$entries[$idx]);
 8808: 	    }
 8809: 	    $$responses{$id}=join(',',@idresponses);
 8810: 	}
 8811:     }
 8812:     return ($errormsg,$number);
 8813: }
 8814: 
 8815: sub interwrite_eval {
 8816:     my ($questiontitles,$responses)=@_;
 8817:     my $number=0;
 8818:     my $errormsg='';
 8819:     my $skipline=1;
 8820:     my $questionnumber=0;
 8821:     my %idresponses=();
 8822:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8823:         my %components=&Apache::loncommon::record_sep($line);
 8824:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8825:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8826:         if ($entries[1] eq 'Response') { $skipline=1; }
 8827:         next if $skipline;
 8828:         if ($entries[0]!=$questionnumber) {
 8829:            $questionnumber=$entries[0];
 8830:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8831:            $number++;
 8832:         }
 8833:         my $id=$entries[4];
 8834:         $id=~s/^[\#0]+//;
 8835:         $id=~s/^v\d*\://i;
 8836:         $id=~s/[\-\:]//g;
 8837:         $idresponses{$id}[$number]=$entries[6];
 8838:     }
 8839:     foreach my $id (keys(%idresponses)) {
 8840:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8841:        $$responses{$id}=~s/^\s*\,//;
 8842:     }
 8843:     return ($errormsg,$number);
 8844: }
 8845: 
 8846: sub assign_clicker_grades {
 8847:     my ($r)=@_;
 8848:     my ($symb)=&get_symb($r);
 8849:     if (!$symb) {return '';}
 8850: # See which part we are saving to
 8851:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8852: # FIXME: This should probably look for the first handgradeable part
 8853:     my $part=$$partlist[0];
 8854: # Start screen output
 8855:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8856: 
 8857:     my $heading=&mt('Assigning grades based on clicker file');
 8858:     $result.=(<<ENDHEADER);
 8859: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8860: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8861: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8862: ENDHEADER
 8863: # Get correct result
 8864: # FIXME: Possibly need delimiter other than ":"
 8865:     my @correct=();
 8866:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8867:     my $number=$env{'form.number'};
 8868:     if ($gradingmechanism ne 'attendance') {
 8869:        foreach my $key (keys(%env)) {
 8870:           if ($key=~/^form\.correct\:/) {
 8871:              my @input=split(/\,/,$env{$key});
 8872:              for (my $i=0;$i<=$#input;$i++) {
 8873:                  if (($correct[$i]) && ($input[$i]) &&
 8874:                      ($correct[$i] ne $input[$i])) {
 8875:                     $result.='<br /><span class="LC_warning">'.
 8876:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8877:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8878:                  } elsif ($input[$i]) {
 8879:                     $correct[$i]=$input[$i];
 8880:                  }
 8881:              }
 8882:           }
 8883:        }
 8884:        for (my $i=0;$i<$number;$i++) {
 8885:           if (!$correct[$i]) {
 8886:              $result.='<br /><span class="LC_error">'.
 8887:                       &mt('No correct result given for question "[_1]"!',
 8888:                           $env{'form.question:'.$i}).'</span>';
 8889:           }
 8890:        }
 8891:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8892:     }
 8893: # Start grading
 8894:     my $pcorrect=$env{'form.pcorrect'};
 8895:     my $pincorrect=$env{'form.pincorrect'};
 8896:     my $storecount=0;
 8897:     foreach my $key (keys(%env)) {
 8898:        my $user='';
 8899:        if ($key=~/^form\.student\:(.*)$/) {
 8900:           $user=$1;
 8901:        }
 8902:        if ($key=~/^form\.unknown\:(.*)$/) {
 8903:           my $id=$1;
 8904:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8905:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8906:           } elsif ($env{'form.multi'.$id}) {
 8907:              $user=$env{'form.multi'.$id};
 8908:           }
 8909:        }
 8910:        if ($user) { 
 8911:           my @answer=split(/\,/,$env{$key});
 8912:           my $sum=0;
 8913:           my $realnumber=$number;
 8914:           for (my $i=0;$i<$number;$i++) {
 8915:              if ($answer[$i]) {
 8916:                 if ($gradingmechanism eq 'attendance') {
 8917:                    $sum+=$pcorrect;
 8918:                 } elsif ($answer[$i] eq '*') {
 8919:                    $sum+=$pcorrect;
 8920:                 } elsif ($answer[$i] eq '-') {
 8921:                    $realnumber--;
 8922:                 } else {
 8923:                    if ($answer[$i] eq $correct[$i]) {
 8924:                       $sum+=$pcorrect;
 8925:                    } else {
 8926:                       $sum+=$pincorrect;
 8927:                    }
 8928:                 }
 8929:              }
 8930:           }
 8931:           my $ave=$sum/(100*$realnumber);
 8932: # Store
 8933:           my ($username,$domain)=split(/\:/,$user);
 8934:           my %grades=();
 8935:           $grades{"resource.$part.solved"}='correct_by_override';
 8936:           $grades{"resource.$part.awarded"}=$ave;
 8937:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8938:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8939:                                                  $env{'request.course.id'},
 8940:                                                  $domain,$username);
 8941:           if ($returncode ne 'ok') {
 8942:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8943:           } else {
 8944:              $storecount++;
 8945:           }
 8946:        }
 8947:     }
 8948: # We are done
 8949:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8950:              '</td></tr></table>'."\n".
 8951:              '</td></tr></table><br /><br />'."\n";
 8952:     return $result.&show_grading_menu_form($symb);
 8953: }
 8954: 
 8955: sub handler {
 8956:     my $request=$_[0];
 8957:     &reset_caches();
 8958:     if ($env{'browser.mathml'}) {
 8959: 	&Apache::loncommon::content_type($request,'text/xml');
 8960:     } else {
 8961: 	&Apache::loncommon::content_type($request,'text/html');
 8962:     }
 8963:     $request->send_http_header;
 8964:     return '' if $request->header_only;
 8965:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8966:     my $symb=&get_symb($request,1);
 8967:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8968:     my $command=$commands[0];
 8969: 
 8970:     if ($#commands > 0) {
 8971: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8972:     }
 8973: 
 8974:     $ssi_error = 0;
 8975:     $request->print(&Apache::loncommon::start_page('Grading'));
 8976:     if ($symb eq '' && $command eq '') {
 8977: 	if ($env{'user.adv'}) {
 8978: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8979: 		($env{'form.codethree'})) {
 8980: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8981: 		    $env{'form.codethree'};
 8982: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8983: 		    &Apache::lonnet::checkin($token);
 8984: 		if ($tsymb) {
 8985: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8986: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8987: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 8988: 					  ('grade_username' => $tuname,
 8989: 					   'grade_domain' => $tudom,
 8990: 					   'grade_courseid' => $tcrsid,
 8991: 					   'grade_symb' => $tsymb)));
 8992: 		    } else {
 8993: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8994: 		    }
 8995: 		} else {
 8996: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8997: 		}
 8998: 	    } else {
 8999: 		$request->print(&Apache::lonxml::tokeninputfield());
 9000: 	    }
 9001: 	}
 9002:     } else {
 9003: 	&init_perm();
 9004: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9005: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9006: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9007: 	    &pickStudentPage($request);
 9008: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9009: 	    &displayPage($request);
 9010: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9011: 	    &updateGradeByPage($request);
 9012: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9013: 	    &processGroup($request);
 9014: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9015: 	    $request->print(&grading_menu($request));
 9016: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9017: 	    $request->print(&submit_options($request));
 9018: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9019: 	    $request->print(&viewgrades($request));
 9020: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9021: 	    $request->print(&processHandGrade($request));
 9022: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9023: 	    $request->print(&editgrades($request));
 9024: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9025: 	    $request->print(&verifyreceipt($request));
 9026:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9027:             $request->print(&process_clicker($request));
 9028:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9029:             $request->print(&process_clicker_file($request));
 9030:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9031:             $request->print(&assign_clicker_grades($request));
 9032: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9033: 	    $request->print(&upcsvScores_form($request));
 9034: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9035: 	    $request->print(&csvupload($request));
 9036: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9037: 	    $request->print(&csvuploadmap($request));
 9038: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9039: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9040: 		$request->print(&csvuploadoptions($request));
 9041: 	    } else {
 9042: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9043: 		    $env{'form.upfile_associate'} = 'reverse';
 9044: 		} else {
 9045: 		    $env{'form.upfile_associate'} = 'forward';
 9046: 		}
 9047: 		$request->print(&csvuploadmap($request));
 9048: 	    }
 9049: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9050: 	    $request->print(&csvuploadassign($request));
 9051: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9052: 	    $request->print(&scantron_selectphase($request));
 9053:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9054:  	    $request->print(&scantron_do_warning($request));
 9055: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9056: 	    $request->print(&scantron_validate_file($request));
 9057: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9058: 	    $request->print(&scantron_process_students($request));
 9059:  	} elsif ($command eq 'scantronupload' && 
 9060:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9061: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9062:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9063:  	} elsif ($command eq 'scantronupload_save' &&
 9064:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9065: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9066:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9067:  	} elsif ($command eq 'scantron_download' &&
 9068: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9069:  	    $request->print(&scantron_download_scantron_data($request));
 9070:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9071:             $request->print(&checkscantron_results($request));     
 9072: 	} elsif ($command) {
 9073: 	    $request->print("Access Denied ($command)");
 9074: 	}
 9075:     }
 9076:     if ($ssi_error) {
 9077: 	&ssi_print_error($request);
 9078:     }
 9079:     $request->print(&Apache::loncommon::end_page());
 9080:     &reset_caches();
 9081:     return '';
 9082: }
 9083: 
 9084: 1;
 9085: 
 9086: __END__;

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