File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.529: download - view: text, annotated - select for diffs
Tue Nov 11 16:40:47 2008 UTC (15 years, 6 months ago) by jms
Branches: MAIN
CVS tags: HEAD
Added/modified POD comments

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.529 2008/11/11 16:40:47 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 OTHER SUBROUTINES
   87: 
   88: =over
   89: 
   90: =item *
   91: 
   92: 
   93: scantron_get_correction() : 
   94: 
   95:    Builds the interface screen to interact with the operator to fix a
   96:    specific error condition in a specific scanline
   97: 
   98:  Arguments:
   99:     $r           - Apache request object
  100:     $i           - number of the current scanline
  101:     $scan_record - hash ref as returned from &scantron_parse_scanline()
  102:     $scan_config - hash ref as returned from &get_scantron_config()
  103:     $line        - full contents of the current scanline
  104:     $error       - error condition, valid values are
  105:                    'incorrectCODE', 'duplicateCODE',
  106:                    'doublebubble', 'missingbubble',
  107:                    'duplicateID', 'incorrectID'
  108:     $arg         - extra information needed
  109:        For errors:
  110:          - duplicateID   - paper number that this studentID was seen before on
  111:          - duplicateCODE - array ref of the paper numbers this CODE was
  112:                            seen on before
  113:          - incorrectCODE - current incorrect CODE 
  114:          - doublebubble  - array ref of the bubble lines that have double
  115:                            bubble errors
  116:          - missingbubble - array ref of the bubble lines that have missing
  117:                            bubble errors
  118: 
  119: =item *
  120: 
  121: scantron_get_maxbubble() : 
  122: 
  123:    Returns the maximum number of bubble lines that are expected to
  124:    occur. Does this by walking the selected sequence rendering the
  125:    resource and then checking &Apache::lonxml::get_problem_counter()
  126:    for what the current value of the problem counter is.
  127: 
  128:    Caches the results to $env{'form.scantron_maxbubble'},
  129:    $env{'form.scantron.bubble_lines.n'}, 
  130:    $env{'form.scantron.first_bubble_line.n'} and
  131:    $env{"form.scantron.sub_bubblelines.n"}
  132:    which are the total number of bubble, lines, the number of bubble
  133:    lines for response n and number of the first bubble line for response n,
  134:    and a comma separated list of numbers of bubble lines for sub-questions
  135:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
  136: 
  137: 
  138: =item *
  139: 
  140: scantron_validate_missingbubbles() : 
  141: 
  142:    Validates all scanlines in the selected file to not have any
  143:     answers that don't have bubbles that have not been verified
  144:     to be bubble free.
  145: 
  146: =item *
  147: 
  148: scantron_process_students() : 
  149: 
  150:    Routine that does the actual grading of the bubble sheet information.
  151: 
  152:    The parsed scanline hash is added to %env 
  153: 
  154:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
  155:    foreach resource , with the form data of
  156: 
  157: 	'submitted'     =>'scantron' 
  158: 	'grade_target'  =>'grade',
  159: 	'grade_username'=> username of student
  160: 	'grade_domain'  => domain of student
  161: 	'grade_courseid'=> of course
  162: 	'grade_symb'    => symb of resource to grade
  163: 
  164:     This triggers a grading pass. The problem grading code takes care
  165:     of converting the bubbled letter information (now in %env) into a
  166:     valid submission.
  167: 
  168: =item *
  169: 
  170: scantron_upload_scantron_data() :
  171: 
  172:     Creates the screen for adding a new bubble sheet data file to a course.
  173: 
  174: =item *
  175: 
  176: scantron_upload_scantron_data_save() : 
  177: 
  178:    Adds a provided bubble information data file to the course if user
  179:    has the correct privileges to do so. 
  180: 
  181: =item *
  182: 
  183: valid_file() :
  184: 
  185:    Validates that the requested bubble data file exists in the course.
  186: 
  187: =item *
  188: 
  189: scantron_download_scantron_data() : 
  190: 
  191:    Shows a list of the three internal files (original, corrected,
  192:    skipped) for a specific bubble sheet data file that exists in the
  193:    course.
  194: 
  195: =item *
  196: 
  197: scantron_validate_ID() : 
  198: 
  199:    Validates all scanlines in the selected file to not have any
  200:    invalid or underspecified student IDs
  201: 
  202: =back
  203: 
  204: =cut
  205: 
  206: package Apache::grades;
  207: use strict;
  208: use Apache::style;
  209: use Apache::lonxml;
  210: use Apache::lonnet;
  211: use Apache::loncommon;
  212: use Apache::lonhtmlcommon;
  213: use Apache::lonnavmaps;
  214: use Apache::lonhomework;
  215: use Apache::lonpickcode;
  216: use Apache::loncoursedata;
  217: use Apache::lonmsg();
  218: use Apache::Constants qw(:common);
  219: use Apache::lonlocal;
  220: use Apache::lonenc;
  221: use String::Similarity;
  222: use LONCAPA;
  223: 
  224: use POSIX qw(floor);
  225: 
  226: 
  227: 
  228: my %perm=();
  229: 
  230: #  These variables are used to recover from ssi errors
  231: 
  232: my $ssi_retries = 5;
  233: my $ssi_error;
  234: my $ssi_error_resource;
  235: my $ssi_error_message;
  236: 
  237: 
  238: sub ssi_with_retries {
  239:     my ($resource, $retries, %form) = @_;
  240:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  241:     if ($response->is_error) {
  242: 	$ssi_error          = 1;
  243: 	$ssi_error_resource = $resource;
  244: 	$ssi_error_message  = $response->code . " " . $response->message;
  245:     }
  246: 
  247:     return $content;
  248: 
  249: }
  250: #
  251: #  Prodcuces an ssi retry failure error message to the user:
  252: #
  253: 
  254: sub ssi_print_error {
  255:     my ($r) = @_;
  256:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
  257:     $r->print('
  258: <br />
  259: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
  260: <p>
  261: '.&mt('Unable to retrieve a resource from a server:').'<br />
  262: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
  263: '.&mt('Error:').' '.$ssi_error_message.'
  264: </p>
  265: <p>'.
  266: &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 />'.
  267: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
  268: '</p>');
  269:     return;
  270: }
  271: 
  272: #
  273: # --- Retrieve the parts from the metadata file.---
  274: sub getpartlist {
  275:     my ($symb) = @_;
  276: 
  277:     my $navmap   = Apache::lonnavmaps::navmap->new();
  278:     my $res      = $navmap->getBySymb($symb);
  279:     my $partlist = $res->parts();
  280:     my $url      = $res->src();
  281:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  282: 
  283:     my @stores;
  284:     foreach my $part (@{ $partlist }) {
  285: 	foreach my $key (@metakeys) {
  286: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  287: 	}
  288:     }
  289:     return @stores;
  290: }
  291: 
  292: # --- Get the symbolic name of a problem and the url
  293: sub get_symb {
  294:     my ($request,$silent) = @_;
  295:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  296:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  297:     if ($symb eq '') { 
  298: 	if (!$silent) {
  299: 	    $request->print("Unable to handle ambiguous references:$url:.");
  300: 	    return ();
  301: 	}
  302:     }
  303:     &Apache::lonenc::check_decrypt(\$symb);
  304:     return ($symb);
  305: }
  306: 
  307: #--- Format fullname, username:domain if different for display
  308: #--- Use anywhere where the student names are listed
  309: sub nameUserString {
  310:     my ($type,$fullname,$uname,$udom) = @_;
  311:     if ($type eq 'header') {
  312: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
  313:     } else {
  314: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  315: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  316:     }
  317: }
  318: 
  319: #--- Get the partlist and the response type for a given problem. ---
  320: #--- Indicate if a response type is coded handgraded or not. ---
  321: sub response_type {
  322:     my ($symb) = shift;
  323: 
  324:     my $navmap = Apache::lonnavmaps::navmap->new();
  325:     my $res = $navmap->getBySymb($symb);
  326:     my $partlist = $res->parts();
  327:     my %vPart = 
  328: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  329:     my (%response_types,%handgrade);
  330:     foreach my $part (@{ $partlist }) {
  331: 	next if (%vPart && !exists($vPart{$part}));
  332: 
  333: 	my @types = $res->responseType($part);
  334: 	my @ids = $res->responseIds($part);
  335: 	for (my $i=0; $i < scalar(@ids); $i++) {
  336: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  337: 	    $handgrade{$part.'_'.$ids[$i]} = 
  338: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  339: 				     '.handgrade',$symb);
  340: 	}
  341:     }
  342:     return ($partlist,\%handgrade,\%response_types);
  343: }
  344: 
  345: sub flatten_responseType {
  346:     my ($responseType) = @_;
  347:     my @part_response_id =
  348: 	map { 
  349: 	    my $part = $_;
  350: 	    map {
  351: 		[$part,$_]
  352: 		} sort(keys(%{ $responseType->{$part} }));
  353: 	} sort(keys(%$responseType));
  354:     return @part_response_id;
  355: }
  356: 
  357: sub get_display_part {
  358:     my ($partID,$symb)=@_;
  359:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  360:     if (defined($display) and $display ne '') {
  361: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  362:     } else {
  363: 	$display=$partID;
  364:     }
  365:     return $display;
  366: }
  367: 
  368: #--- Show resource title
  369: #--- and parts and response type
  370: sub showResourceInfo {
  371:     my ($symb,$probTitle,$checkboxes) = @_;
  372:     my $col=3;
  373:     if ($checkboxes) { $col=4; }
  374:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  375:     $result .='<table border="0">';
  376:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  377:     my %resptype = ();
  378:     my $hdgrade='no';
  379:     my %partsseen;
  380:     foreach my $partID (sort(keys(%$responseType))) {
  381: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
  382: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  383: 	    my $responsetype = $responseType->{$partID}->{$resID};
  384: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  385: 	    $result.='<tr>';
  386: 	    if ($checkboxes) {
  387: 		if (exists($partsseen{$partID})) {
  388: 		    $result.="<td>&nbsp;</td>";
  389: 		} else {
  390: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  391: 		}
  392: 		$partsseen{$partID}=1;
  393: 	    }
  394: 	    my $display_part=&get_display_part($partID,$symb);
  395: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
  396: 		$resID.'</span></td>'.
  397: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
  398: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
  399: 	}
  400:     }
  401:     $result.='</table>'."\n";
  402:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  403: }
  404: 
  405: sub reset_caches {
  406:     &reset_analyze_cache();
  407:     &reset_perm();
  408: }
  409: 
  410: {
  411:     my %analyze_cache;
  412: 
  413:     sub reset_analyze_cache {
  414: 	undef(%analyze_cache);
  415:     }
  416: 
  417:     sub get_analyze {
  418: 	my ($symb,$uname,$udom,$no_increment)=@_;
  419: 	my $key = "$symb\0$uname\0$udom";
  420: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  421: 
  422: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  423: 	$url=&Apache::lonnet::clutter($url);
  424: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
  425: 					   ('grade_target' => 'analyze',
  426: 					    'grade_domain' => $udom,
  427: 					    'grade_symb' => $symb,
  428: 					    'grade_courseid' => 
  429: 					    $env{'request.course.id'},
  430: 					    'grade_username' => $uname,
  431:                                             'grade_noincrement' => $no_increment));
  432: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  433: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  434: 	return $analyze_cache{$key} = \%analyze;
  435:     }
  436: 
  437:     sub get_order {
  438: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
  439: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
  440: 	return $analyze->{"$partid.$respid.shown"};
  441:     }
  442: 
  443:     sub get_radiobutton_correct_foil {
  444: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  445: 	my $analyze = &get_analyze($symb,$uname,$udom);
  446: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  447: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  448: 		return $foil;
  449: 	    }
  450: 	}
  451:     }
  452: }
  453: 
  454: #--- Clean response type for display
  455: #--- Currently filters option/rank/radiobutton/match/essay/Task
  456: #        response types only.
  457: sub cleanRecord {
  458:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  459: 	$uname,$udom) = @_;
  460:     my $grayFont = '<span class="LC_internal_info">';
  461:     if ($response =~ /^(option|rank)$/) {
  462: 	my %answer=&Apache::lonnet::str2hash($answer);
  463: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  464: 	my ($toprow,$bottomrow);
  465: 	foreach my $foil (@$order) {
  466: 	    if ($grading{$foil} == 1) {
  467: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  468: 	    } else {
  469: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  470: 	    }
  471: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  472: 	}
  473: 	return '<blockquote><table border="1">'.
  474: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  475: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  476: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  477:     } elsif ($response eq 'match') {
  478: 	my %answer=&Apache::lonnet::str2hash($answer);
  479: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  480: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  481: 	my ($toprow,$middlerow,$bottomrow);
  482: 	foreach my $foil (@$order) {
  483: 	    my $item=shift(@items);
  484: 	    if ($grading{$foil} == 1) {
  485: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  486: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  487: 	    } else {
  488: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  489: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  490: 	    }
  491: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  492: 	}
  493: 	return '<blockquote><table border="1">'.
  494: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  495: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
  496: 	    $middlerow.'</tr>'.
  497: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  498: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  499:     } elsif ($response eq 'radiobutton') {
  500: 	my %answer=&Apache::lonnet::str2hash($answer);
  501: 	my ($toprow,$bottomrow);
  502: 	my $correct = 
  503: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  504: 	foreach my $foil (@$order) {
  505: 	    if (exists($answer{$foil})) {
  506: 		if ($foil eq $correct) {
  507: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
  508: 		} else {
  509: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
  510: 		}
  511: 	    } else {
  512: 		$toprow.='<td>'.&mt('false').'</td>';
  513: 	    }
  514: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  515: 	}
  516: 	return '<blockquote><table border="1">'.
  517: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
  518: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
  519: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  520:     } elsif ($response eq 'essay') {
  521: 	if (! exists ($env{'form.'.$symb})) {
  522: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  523: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  524: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  525: 
  526: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  527: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  528: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  529: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  530: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  531: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  532: 	}
  533: 	$answer =~ s-\n-<br />-g;
  534: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  535:     } elsif ( $response eq 'organic') {
  536: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  537: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  538: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  539: 	return $result;
  540:     } elsif ( $response eq 'Task') {
  541: 	if ( $answer eq 'SUBMITTED') {
  542: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  543: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  544: 	    return $result;
  545: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  546: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  547: 			       keys(%{$record}));
  548: 	    return join('<br />',($version,@matches));
  549: 			       
  550: 			       
  551: 	} else {
  552: 	    my $result =
  553: 		'<p>'
  554: 		.&mt('Overall result: [_1]',
  555: 		     $record->{$version."resource.$respid.$partid.status"})
  556: 		.'</p>';
  557: 	    
  558: 	    $result .= '<ul>';
  559: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  560: 			     keys(%{$record}));
  561: 	    foreach my $grade (sort(@grade)) {
  562: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  563: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  564: 				     $dim, $record->{$grade}).
  565: 			  '</li>';
  566: 	    }
  567: 	    $result.='</ul>';
  568: 	    return $result;
  569: 	}
  570:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  571: 	$answer = 
  572: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  573: 							      $answer);
  574:     }
  575:     return $answer;
  576: }
  577: 
  578: #-- A couple of common js functions
  579: sub commonJSfunctions {
  580:     my $request = shift;
  581:     $request->print(<<COMMONJSFUNCTIONS);
  582: <script type="text/javascript" language="javascript">
  583:     function radioSelection(radioButton) {
  584: 	var selection=null;
  585: 	if (radioButton.length > 1) {
  586: 	    for (var i=0; i<radioButton.length; i++) {
  587: 		if (radioButton[i].checked) {
  588: 		    return radioButton[i].value;
  589: 		}
  590: 	    }
  591: 	} else {
  592: 	    if (radioButton.checked) return radioButton.value;
  593: 	}
  594: 	return selection;
  595:     }
  596: 
  597:     function pullDownSelection(selectOne) {
  598: 	var selection="";
  599: 	if (selectOne.length > 1) {
  600: 	    for (var i=0; i<selectOne.length; i++) {
  601: 		if (selectOne[i].selected) {
  602: 		    return selectOne[i].value;
  603: 		}
  604: 	    }
  605: 	} else {
  606:             // only one value it must be the selected one
  607: 	    return selectOne.value;
  608: 	}
  609:     }
  610: </script>
  611: COMMONJSFUNCTIONS
  612: }
  613: 
  614: #--- Dumps the class list with usernames,list of sections,
  615: #--- section, ids and fullnames for each user.
  616: sub getclasslist {
  617:     my ($getsec,$filterlist,$getgroup) = @_;
  618:     my @getsec;
  619:     my @getgroup;
  620:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  621:     if (!ref($getsec)) {
  622: 	if ($getsec ne '' && $getsec ne 'all') {
  623: 	    @getsec=($getsec);
  624: 	}
  625:     } else {
  626: 	@getsec=@{$getsec};
  627:     }
  628:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  629:     if (!ref($getgroup)) {
  630: 	if ($getgroup ne '' && $getgroup ne 'all') {
  631: 	    @getgroup=($getgroup);
  632: 	}
  633:     } else {
  634: 	@getgroup=@{$getgroup};
  635:     }
  636:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  637: 
  638:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  639:     # Bail out if we were unable to get the classlist
  640:     return if (! defined($classlist));
  641:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  642:     #
  643:     my %sections;
  644:     my %fullnames;
  645:     foreach my $student (keys(%$classlist)) {
  646:         my $end      = 
  647:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  648:         my $start    = 
  649:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  650:         my $id       = 
  651:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  652:         my $section  = 
  653:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  654:         my $fullname = 
  655:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  656:         my $status   = 
  657:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  658:         my $group   = 
  659:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  660: 	# filter students according to status selected
  661: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  662: 	    if (!($stu_status =~ $status)) {
  663: 		delete($classlist->{$student});
  664: 		next;
  665: 	    }
  666: 	}
  667: 	# filter students according to groups selected
  668: 	my @stu_groups = split(/,/,$group);
  669: 	if (@getgroup) {
  670: 	    my $exclude = 1;
  671: 	    foreach my $grp (@getgroup) {
  672: 	        foreach my $stu_group (@stu_groups) {
  673: 	            if ($stu_group eq $grp) {
  674: 	                $exclude = 0;
  675:     	            } 
  676: 	        }
  677:     	        if (($grp eq 'none') && !$group) {
  678:         	        $exclude = 0;
  679:         	}
  680: 	    }
  681: 	    if ($exclude) {
  682: 	        delete($classlist->{$student});
  683: 	    }
  684: 	}
  685: 	$section = ($section ne '' ? $section : 'none');
  686: 	if (&canview($section)) {
  687: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  688: 		$sections{$section}++;
  689: 		if ($classlist->{$student}) {
  690: 		    $fullnames{$student}=$fullname;
  691: 		}
  692: 	    } else {
  693: 		delete($classlist->{$student});
  694: 	    }
  695: 	} else {
  696: 	    delete($classlist->{$student});
  697: 	}
  698:     }
  699:     my %seen = ();
  700:     my @sections = sort(keys(%sections));
  701:     return ($classlist,\@sections,\%fullnames);
  702: }
  703: 
  704: sub canmodify {
  705:     my ($sec)=@_;
  706:     if ($perm{'mgr'}) {
  707: 	if (!defined($perm{'mgr_section'})) {
  708: 	    # can modify whole class
  709: 	    return 1;
  710: 	} else {
  711: 	    if ($sec eq $perm{'mgr_section'}) {
  712: 		#can modify the requested section
  713: 		return 1;
  714: 	    } else {
  715: 		# can't modify the request section
  716: 		return 0;
  717: 	    }
  718: 	}
  719:     }
  720:     #can't modify
  721:     return 0;
  722: }
  723: 
  724: sub canview {
  725:     my ($sec)=@_;
  726:     if ($perm{'vgr'}) {
  727: 	if (!defined($perm{'vgr_section'})) {
  728: 	    # can modify whole class
  729: 	    return 1;
  730: 	} else {
  731: 	    if ($sec eq $perm{'vgr_section'}) {
  732: 		#can modify the requested section
  733: 		return 1;
  734: 	    } else {
  735: 		# can't modify the request section
  736: 		return 0;
  737: 	    }
  738: 	}
  739:     }
  740:     #can't modify
  741:     return 0;
  742: }
  743: 
  744: #--- Retrieve the grade status of a student for all the parts
  745: sub student_gradeStatus {
  746:     my ($symb,$udom,$uname,$partlist) = @_;
  747:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  748:     my %partstatus = ();
  749:     foreach (@$partlist) {
  750: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  751: 	$status              = 'nothing' if ($status eq '');
  752: 	$partstatus{$_}      = $status;
  753: 	my $subkey           = "resource.$_.submitted_by";
  754: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  755:     }
  756:     return %partstatus;
  757: }
  758: 
  759: # hidden form and javascript that calls the form
  760: # Use by verifyscript and viewgrades
  761: # Shows a student's view of problem and submission
  762: sub jscriptNform {
  763:     my ($symb) = @_;
  764:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  765:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  766: 	'    function viewOneStudent(user,domain) {'."\n".
  767: 	'	document.onestudent.student.value = user;'."\n".
  768: 	'	document.onestudent.userdom.value = domain;'."\n".
  769: 	'	document.onestudent.submit();'."\n".
  770: 	'    }'."\n".
  771: 	'</script>'."\n";
  772:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  773: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  774: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  775: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  776: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  777: 	'<input type="hidden" name="command" value="submission" />'."\n".
  778: 	'<input type="hidden" name="student" value="" />'."\n".
  779: 	'<input type="hidden" name="userdom" value="" />'."\n".
  780: 	'</form>'."\n";
  781:     return $jscript;
  782: }
  783: 
  784: 
  785: 
  786: # Given the score (as a number [0-1] and the weight) what is the final
  787: # point value? This function will round to the nearest tenth, third,
  788: # or quarter if one of those is within the tolerance of .00001.
  789: sub compute_points {
  790:     my ($score, $weight) = @_;
  791:     
  792:     my $tolerance = .00001;
  793:     my $points = $score * $weight;
  794: 
  795:     # Check for nearness to 1/x.
  796:     my $check_for_nearness = sub {
  797:         my ($factor) = @_;
  798:         my $num = ($points * $factor) + $tolerance;
  799:         my $floored_num = floor($num);
  800:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  801:             return $floored_num / $factor;
  802:         }
  803:         return $points;
  804:     };
  805: 
  806:     $points = $check_for_nearness->(10);
  807:     $points = $check_for_nearness->(3);
  808:     $points = $check_for_nearness->(4);
  809:     
  810:     return $points;
  811: }
  812: 
  813: #------------------ End of general use routines --------------------
  814: 
  815: #
  816: # Find most similar essay
  817: #
  818: 
  819: sub most_similar {
  820:     my ($uname,$udom,$uessay,$old_essays)=@_;
  821: 
  822: # ignore spaces and punctuation
  823: 
  824:     $uessay=~s/\W+/ /gs;
  825: 
  826: # ignore empty submissions (occuring when only files are sent)
  827: 
  828:     unless ($uessay=~/\w+/) { return ''; }
  829: 
  830: # these will be returned. Do not care if not at least 50 percent similar
  831:     my $limit=0.6;
  832:     my $sname='';
  833:     my $sdom='';
  834:     my $scrsid='';
  835:     my $sessay='';
  836: # go through all essays ...
  837:     foreach my $tkey (keys(%$old_essays)) {
  838: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  839: # ... except the same student
  840:         next if (($tname eq $uname) && ($tdom eq $udom));
  841: 	my $tessay=$old_essays->{$tkey};
  842: 	$tessay=~s/\W+/ /gs;
  843: # String similarity gives up if not even limit
  844: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  845: # Found one
  846: 	if ($tsimilar>$limit) {
  847: 	    $limit=$tsimilar;
  848: 	    $sname=$tname;
  849: 	    $sdom=$tdom;
  850: 	    $scrsid=$tcrsid;
  851: 	    $sessay=$old_essays->{$tkey};
  852: 	}
  853:     }
  854:     if ($limit>0.6) {
  855:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  856:     } else {
  857:        return ('','','','',0);
  858:     }
  859: }
  860: 
  861: #-------------------------------------------------------------------
  862: 
  863: #------------------------------------ Receipt Verification Routines
  864: #
  865: #--- Check whether a receipt number is valid.---
  866: sub verifyreceipt {
  867:     my $request  = shift;
  868: 
  869:     my $courseid = $env{'request.course.id'};
  870:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  871: 	$env{'form.receipt'};
  872:     $receipt     =~ s/[^\-\d]//g;
  873:     my ($symb)   = &get_symb($request);
  874: 
  875:     my $title.=
  876: 	'<h3><span class="LC_info">'.
  877: 	&mt('Verifying Submission Receipt [_1]',$receipt).
  878: 	'</span></h3>'."\n".
  879: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
  880: 	'</h4>'."\n";
  881: 
  882:     my ($string,$contents,$matches) = ('','',0);
  883:     my (undef,undef,$fullname) = &getclasslist('all','0');
  884:     
  885:     my $receiptparts=0;
  886:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  887: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  888:     my $parts=['0'];
  889:     if ($receiptparts) { ($parts)=&response_type($symb); }
  890:     
  891:     my $header = 
  892: 	&Apache::loncommon::start_data_table().
  893: 	&Apache::loncommon::start_data_table_header_row().
  894: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
  895: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
  896: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
  897:     if ($receiptparts) {
  898: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
  899:     }
  900:     $header.=
  901: 	&Apache::loncommon::end_data_table_header_row();
  902: 
  903:     foreach (sort 
  904: 	     {
  905: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  906: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  907: 		 }
  908: 		 return $a cmp $b;
  909: 	     } (keys(%$fullname))) {
  910: 	my ($uname,$udom)=split(/\:/);
  911: 	foreach my $part (@$parts) {
  912: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  913: 		$contents.=
  914: 		    &Apache::loncommon::start_data_table_row().
  915: 		    '<td>&nbsp;'."\n".
  916: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  917: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  918: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  919: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  920: 		if ($receiptparts) {
  921: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  922: 		}
  923: 		$contents.= 
  924: 		    &Apache::loncommon::end_data_table_row()."\n";
  925: 		
  926: 		$matches++;
  927: 	    }
  928: 	}
  929:     }
  930:     if ($matches == 0) {
  931: 	$string = $title.&mt('No match found for the above receipt.');
  932:     } else {
  933: 	$string = &jscriptNform($symb).$title.
  934: 	    '<p>'.
  935: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
  936: 	    '</p>'.
  937: 	    $header.
  938: 	    $contents.
  939: 	    &Apache::loncommon::end_data_table()."\n";
  940:     }
  941:     return $string.&show_grading_menu_form($symb);
  942: }
  943: 
  944: #--- This is called by a number of programs.
  945: #--- Called from the Grading Menu - View/Grade an individual student
  946: #--- Also called directly when one clicks on the subm button 
  947: #    on the problem page.
  948: sub listStudents {
  949:     my ($request) = shift;
  950: 
  951:     my ($symb) = &get_symb($request);
  952:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  953:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  954:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  955:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  956:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  957:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  958:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  959: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  960: 
  961:     my $result='<h3><span class="LC_info">&nbsp;'.
  962: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
  963: 	.'</span></h3>';
  964: 
  965:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  966: 
  967:     my %lt = ( 'multiple' =>
  968: 	       "Please select a student or group of students before clicking on the Next button.",
  969: 	       'single'   =>
  970: 	       "Please select the student before clicking on the Next button.",
  971: 	       );
  972:     %lt = &Apache::lonlocal::texthash(%lt);
  973:     $request->print(<<LISTJAVASCRIPT);
  974: <script type="text/javascript" language="javascript">
  975:     function checkSelect(checkBox) {
  976: 	var ctr=0;
  977: 	var sense="";
  978: 	if (checkBox.length > 1) {
  979: 	    for (var i=0; i<checkBox.length; i++) {
  980: 		if (checkBox[i].checked) {
  981: 		    ctr++;
  982: 		}
  983: 	    }
  984: 	    sense = '$lt{'multiple'}';
  985: 	} else {
  986: 	    if (checkBox.checked) {
  987: 		ctr = 1;
  988: 	    }
  989: 	    sense = '$lt{'single'}';
  990: 	}
  991: 	if (ctr == 0) {
  992: 	    alert(sense);
  993: 	    return false;
  994: 	}
  995: 	document.gradesub.submit();
  996:     }
  997: 
  998:     function reLoadList(formname) {
  999: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
 1000: 	formname.command.value = 'submission';
 1001: 	formname.submit();
 1002:     }
 1003: </script>
 1004: LISTJAVASCRIPT
 1005: 
 1006:     &commonJSfunctions($request);
 1007:     $request->print($result);
 1008: 
 1009:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
 1010:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
 1011:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
 1012: 	"\n".$table;
 1013: 	
 1014:     $gradeTable .= 
 1015: 	'&nbsp;'.
 1016: 	&mt('<b>View Problem Text: </b>[_1]',
 1017: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 1018: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
 1019: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
 1020:     $gradeTable .= 
 1021: 	'&nbsp;'.
 1022: 	&mt('<b>View Answer: </b>[_1]',
 1023: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
 1024: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
 1025: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
 1026: 
 1027:     my $submission_options;
 1028:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
 1029: 	$submission_options.=
 1030: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
 1031:     }
 1032:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1033:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
 1034:     $env{'form.Status'} = $saveStatus;
 1035:     $submission_options.=
 1036: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
 1037: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
 1038: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
 1039: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
 1040:     $gradeTable .= 
 1041: 	'&nbsp;'.
 1042: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
 1043: 
 1044:     $gradeTable .= 
 1045:         '&nbsp;'.
 1046: 	&mt('<b>Grading Increments:</b> [_1]',
 1047: 	    '<select name="increment">'.
 1048: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
 1049: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
 1050: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
 1051: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
 1052: 	    '</select>');
 1053:     
 1054:     $gradeTable .= 
 1055:         &build_section_inputs().
 1056: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
 1057: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
 1058: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
 1059: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
 1060: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
 1061: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1062: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
 1063: 
 1064:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
 1065: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
 1066:     } else {
 1067: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
 1068: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
 1069:     }
 1070: 
 1071:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
 1072: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
 1073: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
 1074: 
 1075: # checkall buttons
 1076:     $gradeTable.=&check_script('gradesub', 'stuinfo');
 1077:     $gradeTable.='<input type="button" '."\n".
 1078: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 1079: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
 1080:     $gradeTable.=&check_buttons();
 1081:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
 1082:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
 1083:     $gradeTable.= &Apache::loncommon::start_data_table().
 1084: 	&Apache::loncommon::start_data_table_header_row();
 1085:     my $loop = 0;
 1086:     while ($loop < 2) {
 1087: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
 1088: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
 1089: 	if ($env{'form.showgrading'} eq 'yes' 
 1090: 	    && $submitonly ne 'queued'
 1091: 	    && $submitonly ne 'all') {
 1092: 	    foreach my $part (sort(@$partlist)) {
 1093: 		my $display_part=
 1094: 		    &get_display_part((split(/_/,$part))[0],$symb);
 1095: 		$gradeTable.=
 1096: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
 1097: 	    }
 1098: 	} elsif ($submitonly eq 'queued') {
 1099: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
 1100: 	}
 1101: 	$loop++;
 1102: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
 1103:     }
 1104:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
 1105: 
 1106:     my $ctr = 0;
 1107:     foreach my $student (sort 
 1108: 			 {
 1109: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 1110: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 1111: 			     }
 1112: 			     return $a cmp $b;
 1113: 			 }
 1114: 			 (keys(%$fullname))) {
 1115: 	my ($uname,$udom) = split(/:/,$student);
 1116: 
 1117: 	my %status = ();
 1118: 
 1119: 	if ($submitonly eq 'queued') {
 1120: 	    my %queue_status = 
 1121: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 1122: 							$udom,$uname);
 1123: 	    next if (!defined($queue_status{'gradingqueue'}));
 1124: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
 1125: 	}
 1126: 
 1127: 	if ($env{'form.showgrading'} eq 'yes' 
 1128: 	    && $submitonly ne 'queued'
 1129: 	    && $submitonly ne 'all') {
 1130: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
 1131: 	    my $submitted = 0;
 1132: 	    my $graded = 0;
 1133: 	    my $incorrect = 0;
 1134: 	    foreach (keys(%status)) {
 1135: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1136: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
 1137: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 1138: 		
 1139: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1140: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1141: 		    $submitted = 0;
 1142: 		    my ($part)=split(/\./,$partid);
 1143: 		    $gradeTable.='<input type="hidden" name="'.
 1144: 			$student.':'.$part.':submitted_by" value="'.
 1145: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
 1146: 		}
 1147: 	    }
 1148: 	    
 1149: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 1150: 				     $submitonly eq 'incorrect' ||
 1151: 				     $submitonly eq 'graded'));
 1152: 	    next if (!$graded && ($submitonly eq 'graded'));
 1153: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 1154: 	}
 1155: 
 1156: 	$ctr++;
 1157: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
 1158:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
 1159: 	if ( $perm{'vgr'} eq 'F' ) {
 1160: 	    if ($ctr%2 ==1) {
 1161: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
 1162: 	    }
 1163: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
 1164:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
 1165:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
 1166: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
 1167: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
 1168: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
 1169: 
 1170: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
 1171: 		foreach (sort(keys(%status))) {
 1172: 		    next if ($_ =~ /^resource.*?submitted_by$/);
 1173: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
 1174: 		}
 1175: 	    }
 1176: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
 1177: 	    if ($ctr%2 ==0) {
 1178: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
 1179: 	    }
 1180: 	}
 1181:     }
 1182:     if ($ctr%2 ==1) {
 1183: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1184: 	    if ($env{'form.showgrading'} eq 'yes' 
 1185: 		&& $submitonly ne 'queued'
 1186: 		&& $submitonly ne 'all') {
 1187: 		foreach (@$partlist) {
 1188: 		    $gradeTable.='<td>&nbsp;</td>';
 1189: 		}
 1190: 	    } elsif ($submitonly eq 'queued') {
 1191: 		$gradeTable.='<td>&nbsp;</td>';
 1192: 	    }
 1193: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
 1194:     }
 1195: 
 1196:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
 1197: 	'<input type="button" '.
 1198: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1199: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
 1200:     if ($ctr == 0) {
 1201: 	my $num_students=(scalar(keys(%$fullname)));
 1202: 	if ($num_students eq 0) {
 1203: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
 1204: 	} else {
 1205: 	    my $submissions='submissions';
 1206: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1207: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1208: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1209: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1210: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
 1211: 		    $num_students).
 1212: 		'</span><br />';
 1213: 	}
 1214:     } elsif ($ctr == 1) {
 1215: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
 1216:     }
 1217:     $gradeTable.=&show_grading_menu_form($symb);
 1218:     $request->print($gradeTable);
 1219:     return '';
 1220: }
 1221: 
 1222: #---- Called from the listStudents routine
 1223: 
 1224: sub check_script {
 1225:     my ($form, $type)=@_;
 1226:     my $chkallscript='<script type="text/javascript">
 1227:     function checkall() {
 1228:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1229:             ele = document.forms.'.$form.'.elements[i];
 1230:             if (ele.name == "'.$type.'") {
 1231:             document.forms.'.$form.'.elements[i].checked=true;
 1232:                                        }
 1233:         }
 1234:     }
 1235: 
 1236:     function checksec() {
 1237:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1238:             ele = document.forms.'.$form.'.elements[i];
 1239:            string = document.forms.'.$form.'.chksec.value;
 1240:            if
 1241:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1242:               document.forms.'.$form.'.elements[i].checked=true;
 1243:             }
 1244:         }
 1245:     }
 1246: 
 1247: 
 1248:     function uncheckall() {
 1249:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1250:             ele = document.forms.'.$form.'.elements[i];
 1251:             if (ele.name == "'.$type.'") {
 1252:             document.forms.'.$form.'.elements[i].checked=false;
 1253:                                        }
 1254:         }
 1255:     }
 1256: 
 1257: </script>'."\n";
 1258:     return $chkallscript;
 1259: }
 1260: 
 1261: sub check_buttons {
 1262:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
 1263:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
 1264:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
 1265:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1266:     return $buttons;
 1267: }
 1268: 
 1269: #     Displays the submissions for one student or a group of students
 1270: sub processGroup {
 1271:     my ($request)  = shift;
 1272:     my $ctr        = 0;
 1273:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1274:     my $total      = scalar(@stuchecked)-1;
 1275: 
 1276:     foreach my $student (@stuchecked) {
 1277: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1278: 	$env{'form.student'}        = $uname;
 1279: 	$env{'form.userdom'}        = $udom;
 1280: 	$env{'form.fullname'}       = $fullname;
 1281: 	&submission($request,$ctr,$total);
 1282: 	$ctr++;
 1283:     }
 1284:     return '';
 1285: }
 1286: 
 1287: #------------------------------------------------------------------------------------
 1288: #
 1289: #-------------------------- Next few routines handles grading by student, essentially
 1290: #                           handles essay response type problem/part
 1291: #
 1292: #--- Javascript to handle the submission page functionality ---
 1293: sub sub_page_js {
 1294:     my $request = shift;
 1295:     $request->print(<<SUBJAVASCRIPT);
 1296: <script type="text/javascript" language="javascript">
 1297:     function updateRadio(formname,id,weight) {
 1298: 	var gradeBox = formname["GD_BOX"+id];
 1299: 	var radioButton = formname["RADVAL"+id];
 1300: 	var oldpts = formname["oldpts"+id].value;
 1301: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1302: 	gradeBox.value = pts;
 1303: 	var resetbox = false;
 1304: 	if (isNaN(pts) || pts < 0) {
 1305: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1306: 	    for (var i=0; i<radioButton.length; i++) {
 1307: 		if (radioButton[i].checked) {
 1308: 		    gradeBox.value = i;
 1309: 		    resetbox = true;
 1310: 		}
 1311: 	    }
 1312: 	    if (!resetbox) {
 1313: 		formtextbox.value = "";
 1314: 	    }
 1315: 	    return;
 1316: 	}
 1317: 
 1318: 	if (pts > weight) {
 1319: 	    var resp = confirm("You entered a value ("+pts+
 1320: 			       ") greater than the weight for the part. Accept?");
 1321: 	    if (resp == false) {
 1322: 		gradeBox.value = oldpts;
 1323: 		return;
 1324: 	    }
 1325: 	}
 1326: 
 1327: 	for (var i=0; i<radioButton.length; i++) {
 1328: 	    radioButton[i].checked=false;
 1329: 	    if (pts == i && pts != "") {
 1330: 		radioButton[i].checked=true;
 1331: 	    }
 1332: 	}
 1333: 	updateSelect(formname,id);
 1334: 	formname["stores"+id].value = "0";
 1335:     }
 1336: 
 1337:     function writeBox(formname,id,pts) {
 1338: 	var gradeBox = formname["GD_BOX"+id];
 1339: 	if (checkSolved(formname,id) == 'update') {
 1340: 	    gradeBox.value = pts;
 1341: 	} else {
 1342: 	    var oldpts = formname["oldpts"+id].value;
 1343: 	    gradeBox.value = oldpts;
 1344: 	    var radioButton = formname["RADVAL"+id];
 1345: 	    for (var i=0; i<radioButton.length; i++) {
 1346: 		radioButton[i].checked=false;
 1347: 		if (i == oldpts) {
 1348: 		    radioButton[i].checked=true;
 1349: 		}
 1350: 	    }
 1351: 	}
 1352: 	formname["stores"+id].value = "0";
 1353: 	updateSelect(formname,id);
 1354: 	return;
 1355:     }
 1356: 
 1357:     function clearRadBox(formname,id) {
 1358: 	if (checkSolved(formname,id) == 'noupdate') {
 1359: 	    updateSelect(formname,id);
 1360: 	    return;
 1361: 	}
 1362: 	gradeSelect = formname["GD_SEL"+id];
 1363: 	for (var i=0; i<gradeSelect.length; i++) {
 1364: 	    if (gradeSelect[i].selected) {
 1365: 		var selectx=i;
 1366: 	    }
 1367: 	}
 1368: 	var stores = formname["stores"+id];
 1369: 	if (selectx == stores.value) { return };
 1370: 	var gradeBox = formname["GD_BOX"+id];
 1371: 	gradeBox.value = "";
 1372: 	var radioButton = formname["RADVAL"+id];
 1373: 	for (var i=0; i<radioButton.length; i++) {
 1374: 	    radioButton[i].checked=false;
 1375: 	}
 1376: 	stores.value = selectx;
 1377:     }
 1378: 
 1379:     function checkSolved(formname,id) {
 1380: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1381: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1382: 	    if (!reply) {return "noupdate";}
 1383: 	    formname.overRideScore.value = 'yes';
 1384: 	}
 1385: 	return "update";
 1386:     }
 1387: 
 1388:     function updateSelect(formname,id) {
 1389: 	formname["GD_SEL"+id][0].selected = true;
 1390: 	return;
 1391:     }
 1392: 
 1393: //=========== Check that a point is assigned for all the parts  ============
 1394:     function checksubmit(formname,val,total,parttot) {
 1395: 	formname.gradeOpt.value = val;
 1396: 	if (val == "Save & Next") {
 1397: 	    for (i=0;i<=total;i++) {
 1398: 		for (j=0;j<parttot;j++) {
 1399: 		    var partid = formname["partid"+i+"_"+j].value;
 1400: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1401: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1402: 			if (points == "") {
 1403: 			    var name = formname["name"+i].value;
 1404: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1405: 			    var resp = confirm("You did not assign a score for "+studentID+
 1406: 					       ", part "+partid+". Continue?");
 1407: 			    if (resp == false) {
 1408: 				formname["GD_BOX"+i+"_"+partid].focus();
 1409: 				return false;
 1410: 			    }
 1411: 			}
 1412: 		    }
 1413: 		    
 1414: 		}
 1415: 	    }
 1416: 	    
 1417: 	}
 1418: 	if (val == "Grade Student") {
 1419: 	    formname.showgrading.value = "yes";
 1420: 	    if (formname.Status.value == "") {
 1421: 		formname.Status.value = "Active";
 1422: 	    }
 1423: 	    formname.studentNo.value = total;
 1424: 	}
 1425: 	formname.submit();
 1426:     }
 1427: 
 1428: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1429:     function checkSubmitPage(formname,total) {
 1430: 	noscore = new Array(100);
 1431: 	var ptr = 0;
 1432: 	for (i=1;i<total;i++) {
 1433: 	    var partid = formname["q_"+i].value;
 1434: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1435: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1436: 		var status = formname["solved"+i+"_"+partid].value;
 1437: 		if (points == "" && status != "correct_by_student") {
 1438: 		    noscore[ptr] = i;
 1439: 		    ptr++;
 1440: 		}
 1441: 	    }
 1442: 	}
 1443: 	if (ptr != 0) {
 1444: 	    var sense = ptr == 1 ? ": " : "s: ";
 1445: 	    var prolist = "";
 1446: 	    if (ptr == 1) {
 1447: 		prolist = noscore[0];
 1448: 	    } else {
 1449: 		var i = 0;
 1450: 		while (i < ptr-1) {
 1451: 		    prolist += noscore[i]+", ";
 1452: 		    i++;
 1453: 		}
 1454: 		prolist += "and "+noscore[i];
 1455: 	    }
 1456: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1457: 	    if (resp == false) {
 1458: 		return false;
 1459: 	    }
 1460: 	}
 1461: 
 1462: 	formname.submit();
 1463:     }
 1464: </script>
 1465: SUBJAVASCRIPT
 1466: }
 1467: 
 1468: #--- javascript for essay type problem --
 1469: sub sub_page_kw_js {
 1470:     my $request = shift;
 1471:     my $iconpath = $request->dir_config('lonIconsURL');
 1472:     &commonJSfunctions($request);
 1473: 
 1474:     my $inner_js_msg_central=<<INNERJS;
 1475:     <script text="text/javascript">
 1476:     function checkInput() {
 1477:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1478:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1479:       var usrctr = document.msgcenter.usrctr.value;
 1480:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1481:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1482: 
 1483:       var msgchk = "";
 1484:       if (document.msgcenter.subchk.checked) {
 1485:          msgchk = "msgsub,";
 1486:       }
 1487:       var includemsg = 0;
 1488:       for (var i=1; i<=nmsg; i++) {
 1489:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1490:           var frmmsg = document.msgcenter["msg"+i];
 1491:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1492:           var showflg = opener.document.SCORE["shownOnce"+i];
 1493:           showflg.value = "1";
 1494:           var chkbox = document.msgcenter["msgn"+i];
 1495:           if (chkbox.checked) {
 1496:              msgchk += "savemsg"+i+",";
 1497:              includemsg = 1;
 1498:           }
 1499:       }
 1500:       if (document.msgcenter.newmsgchk.checked) {
 1501:          msgchk += "newmsg"+usrctr;
 1502:          includemsg = 1;
 1503:       }
 1504:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1505:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1506:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1507:       includemsg.value = msgchk;
 1508: 
 1509:       self.close()
 1510: 
 1511:     }
 1512:     </script>
 1513: INNERJS
 1514: 
 1515:     my $inner_js_highlight_central=<<INNERJS;
 1516:  <script type="text/javascript">
 1517:     function updateChoice(flag) {
 1518:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1519:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1520:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1521:       opener.document.SCORE.refresh.value = "on";
 1522:       if (opener.document.SCORE.keywords.value!=""){
 1523:          opener.document.SCORE.submit();
 1524:       }
 1525:       self.close()
 1526:     }
 1527: </script>
 1528: INNERJS
 1529: 
 1530:     my $start_page_msg_central = 
 1531:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1532: 				       {'js_ready'  => 1,
 1533: 					'only_body' => 1,
 1534: 					'bgcolor'   =>'#FFFFFF',});
 1535:     my $end_page_msg_central = 
 1536: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1537: 
 1538: 
 1539:     my $start_page_highlight_central = 
 1540:         &Apache::loncommon::start_page('Highlight Central',
 1541: 				       $inner_js_highlight_central,
 1542: 				       {'js_ready'  => 1,
 1543: 					'only_body' => 1,
 1544: 					'bgcolor'   =>'#FFFFFF',});
 1545:     my $end_page_highlight_central = 
 1546: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1547: 
 1548:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1549:     $docopen=~s/^document\.//;
 1550:     $request->print(<<SUBJAVASCRIPT);
 1551: <script type="text/javascript" language="javascript">
 1552: 
 1553: //===================== Show list of keywords ====================
 1554:   function keywords(formname) {
 1555:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1556:     if (nret==null) return;
 1557:     formname.keywords.value = nret;
 1558: 
 1559:     if (formname.keywords.value != "") {
 1560: 	formname.refresh.value = "on";
 1561: 	formname.submit();
 1562:     }
 1563:     return;
 1564:   }
 1565: 
 1566: //===================== Script to view submitted by ==================
 1567:   function viewSubmitter(submitter) {
 1568:     document.SCORE.refresh.value = "on";
 1569:     document.SCORE.NCT.value = "1";
 1570:     document.SCORE.unamedom0.value = submitter;
 1571:     document.SCORE.submit();
 1572:     return;
 1573:   }
 1574: 
 1575: //===================== Script to add keyword(s) ==================
 1576:   function getSel() {
 1577:     if (document.getSelection) txt = document.getSelection();
 1578:     else if (document.selection) txt = document.selection.createRange().text;
 1579:     else return;
 1580:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1581:     if (cleantxt=="") {
 1582: 	alert("Please select a word or group of words from document and then click this link.");
 1583: 	return;
 1584:     }
 1585:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1586:     if (nret==null) return;
 1587:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1588:     if (document.SCORE.keywords.value != "") {
 1589: 	document.SCORE.refresh.value = "on";
 1590: 	document.SCORE.submit();
 1591:     }
 1592:     return;
 1593:   }
 1594: 
 1595: //====================== Script for composing message ==============
 1596:    // preload images
 1597:    img1 = new Image();
 1598:    img1.src = "$iconpath/mailbkgrd.gif";
 1599:    img2 = new Image();
 1600:    img2.src = "$iconpath/mailto.gif";
 1601: 
 1602:   function msgCenter(msgform,usrctr,fullname) {
 1603:     var Nmsg  = msgform.savemsgN.value;
 1604:     savedMsgHeader(Nmsg,usrctr,fullname);
 1605:     var subject = msgform.msgsub.value;
 1606:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1607:     re = /msgsub/;
 1608:     var shwsel = "";
 1609:     if (re.test(msgchk)) { shwsel = "checked" }
 1610:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1611:     displaySubject(checkEntities(subject),shwsel);
 1612:     for (var i=1; i<=Nmsg; i++) {
 1613: 	var testmsg = "savemsg"+i+",";
 1614: 	re = new RegExp(testmsg,"g");
 1615: 	shwsel = "";
 1616: 	if (re.test(msgchk)) { shwsel = "checked" }
 1617: 	var message = document.SCORE["savemsg"+i].value;
 1618: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1619: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1620: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1621:     }
 1622:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1623:     shwsel = "";
 1624:     re = /newmsg/;
 1625:     if (re.test(msgchk)) { shwsel = "checked" }
 1626:     newMsg(newmsg,shwsel);
 1627:     msgTail(); 
 1628:     return;
 1629:   }
 1630: 
 1631:   function checkEntities(strx) {
 1632:     if (strx.length == 0) return strx;
 1633:     var orgStr = ["&", "<", ">", '"']; 
 1634:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1635:     var counter = 0;
 1636:     while (counter < 4) {
 1637: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1638: 	counter++;
 1639:     }
 1640:     return strx;
 1641:   }
 1642: 
 1643:   function strReplace(strx, orgStr, newStr) {
 1644:     return strx.split(orgStr).join(newStr);
 1645:   }
 1646: 
 1647:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1648:     var height = 70*Nmsg+250;
 1649:     var scrollbar = "no";
 1650:     if (height > 600) {
 1651: 	height = 600;
 1652: 	scrollbar = "yes";
 1653:     }
 1654:     var xpos = (screen.width-600)/2;
 1655:     xpos = (xpos < 0) ? '0' : xpos;
 1656:     var ypos = (screen.height-height)/2-30;
 1657:     ypos = (ypos < 0) ? '0' : ypos;
 1658: 
 1659:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1660:     pWin.focus();
 1661:     pDoc = pWin.document;
 1662:     pDoc.$docopen;
 1663:     pDoc.write('$start_page_msg_central');
 1664: 
 1665:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1666:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1667:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
 1668: 
 1669:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1670:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1671:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
 1672: }
 1673:     function displaySubject(msg,shwsel) {
 1674:     pDoc = pWin.document;
 1675:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1676:     pDoc.write("<td>Subject<\\/td>");
 1677:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1678:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
 1679: }
 1680: 
 1681:   function displaySavedMsg(ctr,msg,shwsel) {
 1682:     pDoc = pWin.document;
 1683:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1684:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
 1685:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1686:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
 1687: }
 1688: 
 1689:   function newMsg(newmsg,shwsel) {
 1690:     pDoc = pWin.document;
 1691:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1692:     pDoc.write("<td align=\\"center\\">New<\\/td>");
 1693:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
 1694:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
 1695: }
 1696: 
 1697:   function msgTail() {
 1698:     pDoc = pWin.document;
 1699:     pDoc.write("<\\/table>");
 1700:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1701:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1702:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1703:     pDoc.write("<\\/form>");
 1704:     pDoc.write('$end_page_msg_central');
 1705:     pDoc.close();
 1706: }
 1707: 
 1708: //====================== Script for keyword highlight options ==============
 1709:   function kwhighlight() {
 1710:     var kwclr    = document.SCORE.kwclr.value;
 1711:     var kwsize   = document.SCORE.kwsize.value;
 1712:     var kwstyle  = document.SCORE.kwstyle.value;
 1713:     var redsel = "";
 1714:     var grnsel = "";
 1715:     var blusel = "";
 1716:     if (kwclr=="red")   {var redsel="checked"};
 1717:     if (kwclr=="green") {var grnsel="checked"};
 1718:     if (kwclr=="blue")  {var blusel="checked"};
 1719:     var sznsel = "";
 1720:     var sz1sel = "";
 1721:     var sz2sel = "";
 1722:     if (kwsize=="0")  {var sznsel="checked"};
 1723:     if (kwsize=="+1") {var sz1sel="checked"};
 1724:     if (kwsize=="+2") {var sz2sel="checked"};
 1725:     var synsel = "";
 1726:     var syisel = "";
 1727:     var sybsel = "";
 1728:     if (kwstyle=="")    {var synsel="checked"};
 1729:     if (kwstyle=="<i>") {var syisel="checked"};
 1730:     if (kwstyle=="<b>") {var sybsel="checked"};
 1731:     highlightCentral();
 1732:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1733:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1734:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1735:     highlightend();
 1736:     return;
 1737:   }
 1738: 
 1739:   function highlightCentral() {
 1740: //    if (window.hwdWin) window.hwdWin.close();
 1741:     var xpos = (screen.width-400)/2;
 1742:     xpos = (xpos < 0) ? '0' : xpos;
 1743:     var ypos = (screen.height-330)/2-30;
 1744:     ypos = (ypos < 0) ? '0' : ypos;
 1745: 
 1746:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1747:     hwdWin.focus();
 1748:     var hDoc = hwdWin.document;
 1749:     hDoc.$docopen;
 1750:     hDoc.write('$start_page_highlight_central');
 1751:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1752:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
 1753: 
 1754:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1755:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1756:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
 1757:   }
 1758: 
 1759:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1760:     var hDoc = hwdWin.document;
 1761:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1762:     hDoc.write("<td align=\\"left\\">");
 1763:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
 1764:     hDoc.write("<td align=\\"left\\">");
 1765:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
 1766:     hDoc.write("<td align=\\"left\\">");
 1767:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
 1768:     hDoc.write("<\\/tr>");
 1769:   }
 1770: 
 1771:   function highlightend() { 
 1772:     var hDoc = hwdWin.document;
 1773:     hDoc.write("<\\/table>");
 1774:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
 1775:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1776:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1777:     hDoc.write("<\\/form>");
 1778:     hDoc.write('$end_page_highlight_central');
 1779:     hDoc.close();
 1780:   }
 1781: 
 1782: </script>
 1783: SUBJAVASCRIPT
 1784: }
 1785: 
 1786: sub get_increment {
 1787:     my $increment = $env{'form.increment'};
 1788:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1789:         $increment != .1) {
 1790:         $increment = 1;
 1791:     }
 1792:     return $increment;
 1793: }
 1794: 
 1795: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1796: sub gradeBox {
 1797:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1798:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1799: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 1800:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1801:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
 1802:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
 1803:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1804:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1805: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1806:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1807:     my $display_part= &get_display_part($partid,$symb);
 1808:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1809: 				       [$partid]);
 1810:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1811:     if ($last_resets{$partid}) {
 1812:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1813:     }
 1814:     $result.='<table border="0"><tr>';
 1815:     my $ctr = 0;
 1816:     my $thisweight = 0;
 1817:     my $increment = &get_increment();
 1818: 
 1819:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1820:     while ($thisweight<=$wgt) {
 1821: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1822: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1823: 	    $thisweight.')" value="'.$thisweight.'" '.
 1824: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1825: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1826:         $thisweight += $increment;
 1827: 	$ctr++;
 1828:     }
 1829:     $radio.='</tr></table>';
 1830: 
 1831:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1832: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1833: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1834: 	$wgt.')" /></td>'."\n";
 1835:     $line.='<td>/'.$wgt.' '.$wgtmsg.
 1836: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1837: 	' </td><td>'."\n";
 1838:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1839: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1840:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1841: 	$line.='<option></option>'.
 1842: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
 1843:     } else {
 1844: 	$line.='<option selected="selected"></option>'.
 1845: 	    '<option value="excused" >'.&mt('excused').'</option>';
 1846:     }
 1847:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
 1848: 
 1849: 
 1850:     $result .= 
 1851: 	&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);
 1852: 
 1853:     
 1854:     $result.='</tr></table>'."\n";
 1855:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1856: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1857: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1858: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1859:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1860:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1861:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1862:         $aggtries.'" />'."\n";
 1863:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1864:     return $result;
 1865: }
 1866: 
 1867: sub handback_box {
 1868:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1869:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1870:     my (@respids);
 1871:      my @part_response_id = &flatten_responseType($responseType);
 1872:     foreach my $part_response_id (@part_response_id) {
 1873:     	my ($part,$resp) = @{ $part_response_id };
 1874:         if ($part eq $partid) {
 1875:             push(@respids,$resp);
 1876:         }
 1877:     }
 1878:     my $result;
 1879:     foreach my $respid (@respids) {
 1880: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1881: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1882: 	next if (!@$files);
 1883: 	my $file_counter = 1;
 1884: 	foreach my $file (@$files) {
 1885: 	    if ($file =~ /\/portfolio\//) {
 1886:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1887:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1888:     	        $file_disp = "$name.$ext";
 1889:     	        $file = $file_path.$file_disp;
 1890:     	        $result.=&mt('Return commented version of [_1] to student.',
 1891:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1892:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1893:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1894:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
 1895:     	        $file_counter++;
 1896: 	    }
 1897: 	}
 1898:     }
 1899:     return $result;    
 1900: }
 1901: 
 1902: sub show_problem {
 1903:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1904:     my $rendered;
 1905:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1906:     &Apache::lonxml::remember_problem_counter();
 1907:     if ($mode eq 'both' or $mode eq 'text') {
 1908: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1909: 						       $env{'request.course.id'},
 1910: 						       undef,\%form);
 1911:     }
 1912:     if ($removeform) {
 1913: 	$rendered=~s|<form(.*?)>||g;
 1914: 	$rendered=~s|</form>||g;
 1915: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1916:     }
 1917:     my $companswer;
 1918:     if ($mode eq 'both' or $mode eq 'answer') {
 1919: 	&Apache::lonxml::restore_problem_counter();
 1920: 	$companswer=
 1921: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1922: 						    $env{'request.course.id'},
 1923: 						    %form);
 1924:     }
 1925:     if ($removeform) {
 1926: 	$companswer=~s|<form(.*?)>||g;
 1927: 	$companswer=~s|</form>||g;
 1928: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1929:     }
 1930:     $rendered=
 1931: 	'<div class="LC_grade_show_problem_header">'.
 1932: 	&mt('View of the problem').
 1933: 	'</div><div class="LC_grade_show_problem_problem">'.
 1934: 	$rendered.
 1935: 	'</div>';
 1936:     $companswer=
 1937: 	'<div class="LC_grade_show_problem_header">'.
 1938: 	&mt('Correct answer').
 1939: 	'</div><div class="LC_grade_show_problem_problem">'.
 1940: 	$companswer.
 1941: 	'</div>';
 1942:     my $result;
 1943:     if ($mode eq 'both') {
 1944: 	$result=$rendered.$companswer;
 1945:     } elsif ($mode eq 'text') {
 1946: 	$result=$rendered;
 1947:     } elsif ($mode eq 'answer') {
 1948: 	$result=$companswer;
 1949:     }
 1950:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
 1951:     return $result;
 1952: }
 1953: 
 1954: sub files_exist {
 1955:     my ($r, $symb) = @_;
 1956:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1957: 
 1958:     foreach my $student (@students) {
 1959:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1960:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1961: 					      $udom,$uname);
 1962:         my ($string,$timestamp)= &get_last_submission(\%record);
 1963:         foreach my $submission (@$string) {
 1964:             my ($partid,$respid) =
 1965: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1966:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1967: 					   \%record);
 1968:             return 1 if (@$files);
 1969:         }
 1970:     }
 1971:     return 0;
 1972: }
 1973: 
 1974: sub download_all_link {
 1975:     my ($r,$symb) = @_;
 1976:     my $all_students = 
 1977: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1978: 
 1979:     my $parts =
 1980: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1981: 
 1982:     my $identifier = &Apache::loncommon::get_cgi_id();
 1983:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
 1984:                              'cgi.'.$identifier.'.symb' => $symb,
 1985:                              'cgi.'.$identifier.'.parts' => $parts,});
 1986:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1987: 	      &mt('Download All Submitted Documents').'</a>');
 1988:     return
 1989: }
 1990: 
 1991: sub build_section_inputs {
 1992:     my $section_inputs;
 1993:     if ($env{'form.section'} eq '') {
 1994:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1995:     } else {
 1996:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1997:         foreach my $section (@sections) {
 1998:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1999:         }
 2000:     }
 2001:     return $section_inputs;
 2002: }
 2003: 
 2004: # --------------------------- show submissions of a student, option to grade 
 2005: sub submission {
 2006:     my ($request,$counter,$total) = @_;
 2007:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 2008:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 2009:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 2010:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 2011:     my $symb = &get_symb($request); 
 2012:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 2013: 
 2014:     if (!&canview($usec)) {
 2015: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 2016: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 2017: 			$env{'request.course.id'}.')</span>');
 2018: 	$request->print(&show_grading_menu_form($symb));
 2019: 	return;
 2020:     }
 2021: 
 2022:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 2023:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 2024:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 2025:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 2026:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 2027: 	'" src="'.$request->dir_config('lonIconsURL').
 2028: 	'/check.gif" height="16" border="0" />';
 2029: 
 2030:     my %old_essays;
 2031:     # header info
 2032:     if ($counter == 0) {
 2033: 	&sub_page_js($request);
 2034: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 2035: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 2036: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 2037: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 2038: 	    &download_all_link($request, $symb);
 2039: 	}
 2040: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
 2041: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
 2042: 
 2043: 	# option to display problem, only once else it cause problems 
 2044:         # with the form later since the problem has a form.
 2045: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 2046: 	    my $mode;
 2047: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 2048: 		$mode='both';
 2049: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 2050: 		$mode='text';
 2051: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 2052: 		$mode='answer';
 2053: 	    }
 2054: 	    &Apache::lonxml::clear_problem_counter();
 2055: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 2056: 	}
 2057: 
 2058: 	# kwclr is the only variable that is guaranteed to be non blank 
 2059:         # if this subroutine has been called once.
 2060: 	my %keyhash = ();
 2061: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 2062: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 2063: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 2064: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 2065: 
 2066: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2067: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 2068: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 2069: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 2070: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 2071: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 2072: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 2073: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 2074: 	}
 2075: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 2076: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 2077: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 2078: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 2079: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 2080: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 2081: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 2082: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 2083: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 2084: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 2085: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 2086: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 2087: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 2088: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 2089: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 2090: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 2091: 			&build_section_inputs().
 2092: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 2093: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 2094: 			'<input type="hidden" name="NCT"'.
 2095: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 2096: 	if ($env{'form.handgrade'} eq 'yes') {
 2097: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 2098: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 2099: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 2100: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 2101: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 2102: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 2103: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 2104: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 2105: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 2106: 	    }
 2107: 	}
 2108: 	
 2109: 	my ($cts,$prnmsg) = (1,'');
 2110: 	while ($cts <= $env{'form.savemsgN'}) {
 2111: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 2112: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 2113: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 2114: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 2115: 		'" />'."\n".
 2116: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 2117: 	    $cts++;
 2118: 	}
 2119: 	$request->print($prnmsg);
 2120: 
 2121: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 2122: #
 2123: # Print out the keyword options line
 2124: #
 2125: 	    $request->print(<<KEYWORDS);
 2126: &nbsp;<b>Keyword Options:</b>&nbsp;
 2127: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 2128: <a href="#" onMouseDown="javascript:getSel(); return false"
 2129:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 2130: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 2131: KEYWORDS
 2132: #
 2133: # Load the other essays for similarity check
 2134: #
 2135:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 2136: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 2137: 	    $apath=&escape($apath);
 2138: 	    $apath=~s/\W/\_/gs;
 2139: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 2140:         }
 2141:     }
 2142: 
 2143: # This is where output for one specific student would start
 2144:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
 2145:     $request->print("\n\n".
 2146:                     '<div class="LC_grade_show_user '.$add_class.'">'.
 2147: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
 2148: 		    '<div class="LC_grade_show_user_body">'."\n");
 2149: 
 2150:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 2151: 	my $mode;
 2152: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 2153: 	    $mode='both';
 2154: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 2155: 	    $mode='text';
 2156: 	} elsif ($env{'form.vAns'} eq 'all') {
 2157: 	    $mode='answer';
 2158: 	}
 2159: 	&Apache::lonxml::clear_problem_counter();
 2160: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
 2161:     }
 2162: 
 2163:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2164:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2165: 
 2166:     # Display student info
 2167:     $request->print(($counter == 0 ? '' : '<br />'));
 2168:     my $result='<div class="LC_grade_submissions">';
 2169:     
 2170:     $result.='<div class="LC_grade_submissions_header">';
 2171:     $result.= &mt('Submissions');
 2172:     $result.='<input type="hidden" name="name'.$counter.
 2173: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 2174:     if ($env{'form.handgrade'} eq 'no') {
 2175: 	$result.='<span class="LC_grade_check_note">'.
 2176: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
 2177: 
 2178:     }
 2179: 
 2180: 
 2181: 
 2182:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 2183:     my $fullname;
 2184:     my $col_fullnames = [];
 2185:     if ($env{'form.handgrade'} eq 'yes') {
 2186: 	(my $sub_result,$fullname,$col_fullnames)=
 2187: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
 2188: 				 $counter);
 2189: 	$result.=$sub_result;
 2190:     }
 2191:     $request->print($result."\n");
 2192:     $request->print('</div>'."\n");
 2193:     # print student answer/submission
 2194:     # Options are (1) Handgaded submission only
 2195:     #             (2) Last submission, includes submission that is not handgraded 
 2196:     #                  (for multi-response type part)
 2197:     #             (3) Last submission plus the parts info
 2198:     #             (4) The whole record for this student
 2199:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2200: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2201: 	
 2202: 	my $lastsubonly;
 2203: 
 2204: 	if ($$timestamp eq '') {
 2205: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
 2206: 	} else {
 2207: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
 2208: 
 2209: 	    my %seenparts;
 2210: 	    my @part_response_id = &flatten_responseType($responseType);
 2211: 	    foreach my $part (@part_response_id) {
 2212: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2213: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2214: 
 2215: 		my ($partid,$respid) = @{ $part };
 2216: 		my $display_part=&get_display_part($partid,$symb);
 2217: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2218: 		    if (exists($seenparts{$partid})) { next; }
 2219: 		    $seenparts{$partid}=1;
 2220: 		    my $submitby='<b>Part:</b> '.$display_part.
 2221: 			' <b>Collaborative submission by:</b> '.
 2222: 			'<a href="javascript:viewSubmitter(\''.
 2223: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2224: 			'\');" target="_self">'.
 2225: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2226: 		    $request->print($submitby);
 2227: 		    next;
 2228: 		}
 2229: 		my $responsetype = $responseType->{$partid}->{$respid};
 2230: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2231: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
 2232: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2233: 			' )</span>&nbsp; &nbsp;'.
 2234: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
 2235: 		    next;
 2236: 		}
 2237: 		foreach my $submission (@$string) {
 2238: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 2239: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2240: 		    my ($ressub,$subval) = split(/:/,$submission,2);
 2241: 		    # Similarity check
 2242: 		    my $similar='';
 2243: 		    if($env{'form.checkPlag'}){
 2244: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2245: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2246: 			if ($osim) {
 2247: 			    $osim=int($osim*100.0);
 2248: 			    my %old_course_desc = 
 2249: 				&Apache::lonnet::coursedescription($ocrsid,
 2250: 								   {'one_time' => 1});
 2251: 
 2252: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2253: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2254: 				    $osim,
 2255: 				    &Apache::loncommon::plainname($oname,$odom),
 2256: 				    $oname,$odom,
 2257: 				    $old_course_desc{'description'},
 2258: 				    $old_course_desc{'num'},
 2259: 				    $old_course_desc{'domain'}).
 2260: 				'</span></h3><blockquote><i>'.
 2261: 				&keywords_highlight($oessay).
 2262: 				'</i></blockquote><hr />';
 2263: 			}
 2264: 		    }
 2265: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2266: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2267: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2268: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2269: 			my $display_part=&get_display_part($partid,$symb);
 2270: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
 2271: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2272: 			    ' )</span>&nbsp; &nbsp;';
 2273: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2274: 			if (@$files) {
 2275: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
 2276: 			    my $file_counter = 0;
 2277: 			    foreach my $file (@$files) {
 2278: 			        $file_counter++;
 2279: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2280: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2281: 			    }
 2282: 			    $lastsubonly.='<br />';
 2283: 			}
 2284: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
 2285: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2286: 					 $respid,\%record,$order);
 2287: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2288: 			$lastsubonly.='</div>';
 2289: 		    }
 2290: 		}
 2291: 	    }
 2292: 	    $lastsubonly.='</div>'."\n";
 2293: 	}
 2294: 	$request->print($lastsubonly);
 2295:    } elsif ($env{'form.lastSub'} eq 'datesub') {
 2296: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2297: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2298:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2299: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2300: 								 $env{'request.course.id'},
 2301: 								 $last,'.submission',
 2302: 								 'Apache::grades::keywords_highlight'));
 2303:     }
 2304: 
 2305:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2306: 	.$udom.'" />'."\n");
 2307:     # return if view submission with no grading option
 2308:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2309: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2310: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2311: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2312: 	$toGrade.='</div>'."\n";
 2313: 	if (($env{'form.command'} eq 'submission') || 
 2314: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2315: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2316: 	}
 2317: 	$request->print($toGrade);
 2318: 	return;
 2319:     } else {
 2320: 	$request->print('</div>'."\n");
 2321:     }
 2322: 
 2323:     # essay grading message center
 2324:     if ($env{'form.handgrade'} eq 'yes') {
 2325: 	my $result='<div class="LC_grade_message_center">';
 2326:     
 2327: 	$result.='<div class="LC_grade_message_center_header">'.
 2328: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
 2329: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2330: 	my $msgfor = $givenn.' '.$lastname;
 2331: 	if (scalar(@$col_fullnames) > 0) {
 2332: 	    my $lastone = pop(@$col_fullnames);
 2333: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
 2334: 	}
 2335: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2336: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2337: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2338: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2339: 	    ',\''.$msgfor.'\');" target="_self">'.
 2340: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2341: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2342: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2343: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2344: 	    '<br />&nbsp;('.
 2345: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
 2346: 	$result.='</div></div>';
 2347: 	$request->print($result);
 2348:     }
 2349: 
 2350:     my %seen = ();
 2351:     my @partlist;
 2352:     my @gradePartRespid;
 2353:     my @part_response_id = &flatten_responseType($responseType);
 2354:     $request->print('<div class="LC_grade_assign">'.
 2355: 		    
 2356: 		    '<div class="LC_grade_assign_header">'.
 2357: 		    &mt('Assign Grades').'</div>'.
 2358: 		    '<div class="LC_grade_assign_body">');
 2359:     foreach my $part_response_id (@part_response_id) {
 2360:     	my ($partid,$respid) = @{ $part_response_id };
 2361: 	my $part_resp = join('_',@{ $part_response_id });
 2362: 	next if ($seen{$partid} > 0);
 2363: 	$seen{$partid}++;
 2364: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2365: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2366: 	push(@partlist,$partid);
 2367: 	push(@gradePartRespid,$partid.'.'.$respid);
 2368: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2369:     }
 2370:     $request->print('</div></div>');
 2371: 
 2372:     $request->print('<div class="LC_grade_info_links">');
 2373:     if ($perm{'vgr'}) {
 2374: 	$request->print(
 2375: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2376: 						   $uname,$udom,'check'));
 2377:     }
 2378:     if ($perm{'opa'}) {
 2379: 	$request->print(
 2380: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2381: 					 $uname,$udom,$symb,'check'));
 2382:     }
 2383:     $request->print('</div>');
 2384: 
 2385:     $result='<input type="hidden" name="partlist'.$counter.
 2386: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2387:     $result.='<input type="hidden" name="gradePartRespid'.
 2388: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2389:     my $ctr = 0;
 2390:     while ($ctr < scalar(@partlist)) {
 2391: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2392: 	    $partlist[$ctr].'" />'."\n";
 2393: 	$ctr++;
 2394:     }
 2395:     $request->print($result.''."\n");
 2396: 
 2397: # Done with printing info for one student
 2398: 
 2399:     $request->print('</div>');#LC_grade_show_user_body
 2400:     $request->print('</div>');#LC_grade_show_user
 2401: 
 2402: 
 2403:     # print end of form
 2404:     if ($counter == $total) {
 2405: 	my $endform='<table border="0"><tr><td>'."\n";
 2406: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
 2407: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2408: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2409: 	my $ntstu ='<select name="NTSTU">'.
 2410: 	    '<option>1</option><option>2</option>'.
 2411: 	    '<option>3</option><option>5</option>'.
 2412: 	    '<option>7</option><option>10</option></select>'."\n";
 2413: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2414: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2415: 	$endform.=&mt('[_1]student(s)',$ntstu);
 2416: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
 2417: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2418: 	    '<input type="button" value="'.&mt('Next').'" '.
 2419: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2420: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
 2421:         $endform.="<input type='hidden' value='".&get_increment().
 2422:             "' name='increment' />";
 2423: 	$endform.='</td></tr></table></form>';
 2424: 	$endform.=&show_grading_menu_form($symb);
 2425: 	$request->print($endform);
 2426:     }
 2427:     return '';
 2428: }
 2429: 
 2430: sub check_collaborators {
 2431:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
 2432:     my ($result,@col_fullnames);
 2433:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
 2434:     foreach my $part (keys(%$handgrade)) {
 2435: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
 2436: 					'.maxcollaborators',
 2437: 					$symb,$udom,$uname);
 2438: 	next if ($ncol <= 0);
 2439: 	$part =~ s/\_/\./g;
 2440: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
 2441: 	my (@good_collaborators, @bad_collaborators);
 2442: 	foreach my $possible_collaborator
 2443: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
 2444: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
 2445: 	    next if ($possible_collaborator eq '');
 2446: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
 2447: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2448: 	    next if ($co_name eq $uname && $co_dom eq $udom);
 2449: 	    # Doing this grep allows 'fuzzy' specification
 2450: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
 2451: 			       keys(%$classlist));
 2452: 	    if (! scalar(@matches)) {
 2453: 		push(@bad_collaborators, $possible_collaborator);
 2454: 	    } else {
 2455: 		push(@good_collaborators, @matches);
 2456: 	    }
 2457: 	}
 2458: 	if (scalar(@good_collaborators) != 0) {
 2459: 	    $result.='<br />'.&mt('Collaborators: ');
 2460: 	    foreach my $name (@good_collaborators) {
 2461: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
 2462: 		push(@col_fullnames, $givenn.' '.$lastname);
 2463: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
 2464: 	    }
 2465: 	    $result.='<br />'."\n";
 2466: 	    my ($part)=split(/\./,$part);
 2467: 	    $result.='<input type="hidden" name="collaborator'.$counter.
 2468: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
 2469: 		"\n";
 2470: 	}
 2471: 	if (scalar(@bad_collaborators) > 0) {
 2472: 	    $result.='<div class="LC_warning">';
 2473: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
 2474: 	    $result .= '</div>';
 2475: 	}         
 2476: 	if (scalar(@bad_collaborators > $ncol)) {
 2477: 	    $result .= '<div class="LC_warning">';
 2478: 	    $result .= &mt('This student has submitted too many '.
 2479: 		'collaborators.  Maximum is [_1].',$ncol);
 2480: 	    $result .= '</div>';
 2481: 	}
 2482:     }
 2483:     return ($result,$fullname,\@col_fullnames);
 2484: }
 2485: 
 2486: #--- Retrieve the last submission for all the parts
 2487: sub get_last_submission {
 2488:     my ($returnhash)=@_;
 2489:     my (@string,$timestamp);
 2490:     if ($$returnhash{'version'}) {
 2491: 	my %lasthash=();
 2492: 	my ($version);
 2493: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2494: 	    foreach my $key (sort(split(/\:/,
 2495: 					$$returnhash{$version.':keys'}))) {
 2496: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2497: 		$timestamp = 
 2498: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2499: 	    }
 2500: 	}
 2501: 	foreach my $key (keys(%lasthash)) {
 2502: 	    next if ($key !~ /\.submission$/);
 2503: 
 2504: 	    my ($partid,$foo) = split(/submission$/,$key);
 2505: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2506: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2507: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2508: 	}
 2509:     }
 2510:     if (!@string) {
 2511: 	$string[0] =
 2512: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2513:     }
 2514:     return (\@string,\$timestamp);
 2515: }
 2516: 
 2517: #--- High light keywords, with style choosen by user.
 2518: sub keywords_highlight {
 2519:     my $string    = shift;
 2520:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2521:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2522:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2523:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2524:     foreach my $keyword (@keylist) {
 2525: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2526:     }
 2527:     return $string;
 2528: }
 2529: 
 2530: #--- Called from submission routine
 2531: sub processHandGrade {
 2532:     my ($request) = shift;
 2533:     my $symb   = &get_symb($request);
 2534:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2535:     my $button = $env{'form.gradeOpt'};
 2536:     my $ngrade = $env{'form.NCT'};
 2537:     my $ntstu  = $env{'form.NTSTU'};
 2538:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2539:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2540: 
 2541:     if ($button eq 'Save & Next') {
 2542: 	my $ctr = 0;
 2543: 	while ($ctr < $ngrade) {
 2544: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2545: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2546: 	    if ($errorflag eq 'no_score') {
 2547: 		$ctr++;
 2548: 		next;
 2549: 	    }
 2550: 	    if ($errorflag eq 'not_allowed') {
 2551: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2552: 		$ctr++;
 2553: 		next;
 2554: 	    }
 2555: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2556: 	    my ($subject,$message,$msgstatus) = ('','','');
 2557: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2558:             my ($feedurl,$showsymb) =
 2559: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2560: 	    my $messagetail;
 2561: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2562: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2563: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2564: 		$subject.=' ['.$restitle.']';
 2565: 		my (@msgnum) = split(/,/,$includemsg);
 2566: 		foreach (@msgnum) {
 2567: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2568: 		}
 2569: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2570: 		if ($env{'form.withgrades'.$ctr}) {
 2571: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2572: 		    $messagetail = " for <a href=\"".
 2573: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2574: 		}
 2575: 		$msgstatus = 
 2576:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2577: 						     $message.$messagetail,
 2578:                                                      undef,$feedurl,undef,
 2579:                                                      undef,undef,$showsymb,
 2580:                                                      $restitle);
 2581: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2582: 				$msgstatus);
 2583: 	    }
 2584: 	    if ($env{'form.collaborator'.$ctr}) {
 2585: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2586: 		foreach my $collabstr (@collabstrs) {
 2587: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2588: 		    foreach my $collaborator (@collaborators) {
 2589: 			my ($errorflag,$pts,$wgt) = 
 2590: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2591: 					   $env{'form.unamedom'.$ctr},$part);
 2592: 			if ($errorflag eq 'not_allowed') {
 2593: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2594: 			    next;
 2595: 			} elsif ($message ne '') {
 2596: 			    my ($baseurl,$showsymb) = 
 2597: 				&get_feedurl_and_symb($symb,$collaborator,
 2598: 						      $udom);
 2599: 			    if ($env{'form.withgrades'.$ctr}) {
 2600: 				$messagetail = " for <a href=\"".
 2601:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2602: 			    }
 2603: 			    $msgstatus = 
 2604: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2605: 			}
 2606: 		    }
 2607: 		}
 2608: 	    }
 2609: 	    $ctr++;
 2610: 	}
 2611:     }
 2612: 
 2613:     if ($env{'form.handgrade'} eq 'yes') {
 2614: 	# Keywords sorted in alphabatical order
 2615: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2616: 	my %keyhash = ();
 2617: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2618: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2619: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2620: 	$env{'form.keywords'} = join(' ',@keywords);
 2621: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2622: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2623: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2624: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2625: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2626: 
 2627: 	# message center - Order of message gets changed. Blank line is eliminated.
 2628: 	# New messages are saved in env for the next student.
 2629: 	# All messages are saved in nohist_handgrade.db
 2630: 	my ($ctr,$idx) = (1,1);
 2631: 	while ($ctr <= $env{'form.savemsgN'}) {
 2632: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2633: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2634: 		$idx++;
 2635: 	    }
 2636: 	    $ctr++;
 2637: 	}
 2638: 	$ctr = 0;
 2639: 	while ($ctr < $ngrade) {
 2640: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2641: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2642: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2643: 		$idx++;
 2644: 	    }
 2645: 	    $ctr++;
 2646: 	}
 2647: 	$env{'form.savemsgN'} = --$idx;
 2648: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2649: 	my $putresult = &Apache::lonnet::put
 2650: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2651:     }
 2652:     # Called by Save & Refresh from Highlight Attribute Window
 2653:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2654:     if ($env{'form.refresh'} eq 'on') {
 2655: 	my ($ctr,$total) = (0,0);
 2656: 	while ($ctr < $ngrade) {
 2657: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2658: 	    $ctr++;
 2659: 	}
 2660: 	$env{'form.NTSTU'}=$ngrade;
 2661: 	$ctr = 0;
 2662: 	while ($ctr < $total) {
 2663: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2664: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2665: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2666: 	    &submission($request,$ctr,$total-1);
 2667: 	    $ctr++;
 2668: 	}
 2669: 	return '';
 2670:     }
 2671: 
 2672: # Go directly to grade student - from submission or link from chart page
 2673:     if ($button eq 'Grade Student') {
 2674: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2675: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2676: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2677: 	$env{'form.fullname'} = $$fullname{$processUser};
 2678: 	&submission($request,0,0);
 2679: 	return '';
 2680:     }
 2681: 
 2682:     # Get the next/previous one or group of students
 2683:     my $firststu = $env{'form.unamedom0'};
 2684:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2685:     my $ctr = 2;
 2686:     while ($laststu eq '') {
 2687: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2688: 	$ctr++;
 2689: 	$laststu = $firststu if ($ctr > $ngrade);
 2690:     }
 2691: 
 2692:     my (@parsedlist,@nextlist);
 2693:     my ($nextflg) = 0;
 2694:     foreach my $item (sort 
 2695: 	     {
 2696: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2697: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2698: 		 }
 2699: 		 return $a cmp $b;
 2700: 	     } (keys(%$fullname))) {
 2701: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2702: 	    push(@parsedlist,$item);
 2703: 	}
 2704: 	$nextflg = 1 if ($item eq $laststu);
 2705: 	if ($button eq 'Previous') {
 2706: 	    last if ($item eq $firststu);
 2707: 	    push(@parsedlist,$item);
 2708: 	}
 2709:     }
 2710:     $ctr = 0;
 2711:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2712:     my ($partlist) = &response_type($symb);
 2713:     foreach my $student (@parsedlist) {
 2714: 	my $submitonly=$env{'form.submitonly'};
 2715: 	my ($uname,$udom) = split(/:/,$student);
 2716: 	
 2717: 	if ($submitonly eq 'queued') {
 2718: 	    my %queue_status = 
 2719: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2720: 							$udom,$uname);
 2721: 	    next if (!defined($queue_status{'gradingqueue'}));
 2722: 	}
 2723: 
 2724: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2725: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2726: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2727: 	    my $submitted = 0;
 2728: 	    my $ungraded = 0;
 2729: 	    my $incorrect = 0;
 2730: 	    foreach my $item (keys(%status)) {
 2731: 		$submitted = 1 if ($status{$item} ne 'nothing');
 2732: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
 2733: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
 2734: 		my ($foo,$partid,$foo1) = split(/\./,$item);
 2735: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2736: 		    $submitted = 0;
 2737: 		}
 2738: 	    }
 2739: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2740: 				     $submitonly eq 'incorrect' ||
 2741: 				     $submitonly eq 'graded'));
 2742: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2743: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2744: 	}
 2745: 	push(@nextlist,$student) if ($ctr < $ntstu);
 2746: 	last if ($ctr == $ntstu);
 2747: 	$ctr++;
 2748:     }
 2749: 
 2750:     $ctr = 0;
 2751:     my $total = scalar(@nextlist)-1;
 2752: 
 2753:     foreach (sort(@nextlist)) {
 2754: 	my ($uname,$udom,$submitter) = split(/:/);
 2755: 	$env{'form.student'}  = $uname;
 2756: 	$env{'form.userdom'}  = $udom;
 2757: 	$env{'form.fullname'} = $$fullname{$_};
 2758: 	&submission($request,$ctr,$total);
 2759: 	$ctr++;
 2760:     }
 2761:     if ($total < 0) {
 2762: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
 2763: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
 2764: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
 2765: 	$the_end.=&show_grading_menu_form($symb);
 2766: 	$request->print($the_end);
 2767:     }
 2768:     return '';
 2769: }
 2770: 
 2771: #---- Save the score and award for each student, if changed
 2772: sub saveHandGrade {
 2773:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2774:     my @version_parts;
 2775:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2776: 					   $env{'request.course.id'});
 2777:     if (!&canmodify($usec)) { return('not_allowed'); }
 2778:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2779:     my @parts_graded;
 2780:     my %newrecord  = ();
 2781:     my ($pts,$wgt) = ('','');
 2782:     my %aggregate = ();
 2783:     my $aggregateflag = 0;
 2784:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2785:     foreach my $new_part (@parts) {
 2786: 	#collaborator ($submi may vary for different parts
 2787: 	if ($submitter && $new_part ne $part) { next; }
 2788: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2789: 	if ($dropMenu eq 'excused') {
 2790: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2791: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2792: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2793: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2794: 		}
 2795: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2796: 	    }
 2797: 	} elsif ($dropMenu eq 'reset status'
 2798: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2799: 	    foreach my $key (keys(%record)) {
 2800: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2801: 	    }
 2802: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2803: 		"$env{'user.name'}:$env{'user.domain'}";
 2804:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2805: 
 2806:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2807: 					       [$new_part]);
 2808:             my $aggtries =$totaltries;
 2809:             if ($last_resets{$new_part}) {
 2810:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2811: 					   $new_part);
 2812:             }
 2813: 
 2814:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2815:             if ($aggtries > 0) {
 2816:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2817:                 $aggregateflag = 1;
 2818:             }
 2819: 	} elsif ($dropMenu eq '') {
 2820: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2821: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2822: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2823: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2824: 		next;
 2825: 	    }
 2826: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2827: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2828: 	    my $partial= $pts/$wgt;
 2829: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2830: 		#do not update score for part if not changed.
 2831:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2832: 		next;
 2833: 	    } else {
 2834: 	        push(@parts_graded,$new_part);
 2835: 	    }
 2836: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2837: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2838: 	    }
 2839: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2840: 	    if ($partial == 0) {
 2841: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2842: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2843: 		}
 2844: 	    } else {
 2845: 		if ($record{$reckey} ne 'correct_by_override') {
 2846: 		    $newrecord{$reckey} = 'correct_by_override';
 2847: 		}
 2848: 	    }	    
 2849: 	    if ($submitter && 
 2850: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2851: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2852: 	    }
 2853: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2854: 		"$env{'user.name'}:$env{'user.domain'}";
 2855: 	}
 2856: 	# unless problem has been graded, set flag to version the submitted files
 2857: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2858: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2859: 	        $dropMenu eq 'reset status')
 2860: 	   {
 2861: 	    push(@version_parts,$new_part);
 2862: 	}
 2863:     }
 2864:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2865:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2866: 
 2867:     if (%newrecord) {
 2868:         if (@version_parts) {
 2869:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2870:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2871: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2872: 	    foreach my $new_part (@version_parts) {
 2873: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2874: 				$new_part,\%newrecord);
 2875: 	    }
 2876:         }
 2877: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2878: 				$env{'request.course.id'},$domain,$stuname);
 2879: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2880: 				     $cdom,$cnum,$domain,$stuname);
 2881:     }
 2882:     if ($aggregateflag) {
 2883:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2884: 			      $cdom,$cnum);
 2885:     }
 2886:     return ('',$pts,$wgt);
 2887: }
 2888: 
 2889: sub check_and_remove_from_queue {
 2890:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2891:     my @ungraded_parts;
 2892:     foreach my $part (@{$parts}) {
 2893: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2894: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2895: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2896: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2897: 		) {
 2898: 	    push(@ungraded_parts, $part);
 2899: 	}
 2900:     }
 2901:     if ( !@ungraded_parts ) {
 2902: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2903: 					       $cnum,$domain,$stuname);
 2904:     }
 2905: }
 2906: 
 2907: sub handback_files {
 2908:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2909:     my $portfolio_root = '/userfiles/portfolio';
 2910:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2911: 
 2912:     my @part_response_id = &flatten_responseType($responseType);
 2913:     foreach my $part_response_id (@part_response_id) {
 2914:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2915: 	my $part_resp = join('_',@{ $part_response_id });
 2916:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2917:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2918:                 my $file_counter = 1;
 2919: 		my $file_msg;
 2920:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2921:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2922:                     my ($directory,$answer_file) = 
 2923:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2924:                     my ($answer_name,$answer_ver,$answer_ext) =
 2925: 		        &file_name_version_ext($answer_file);
 2926: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2927:                     my $getpropath = 1;
 2928: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
 2929: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2930:                     # fix file name
 2931:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2932:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2933:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2934:             	                                $save_file_name);
 2935:                     if ($result !~ m|^/uploaded/|) {
 2936:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2937:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2938:                     } else {
 2939:                         # mark the file as read only
 2940:                         my @files = ($save_file_name);
 2941:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2942:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2943: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2944: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2945: 			}
 2946:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2947: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2948: 
 2949:                     }
 2950:                     $request->print("<br />".$fname." will be the uploaded file name");
 2951:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2952:                     $file_counter++;
 2953:                 }
 2954: 		my $subject = "File Handed Back by Instructor ";
 2955: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2956: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2957: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2958: 		$message .= " and can be found in your portfolio space.";
 2959: 		my ($feedurl,$showsymb) = 
 2960: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2961:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2962: 		my $msgstatus = 
 2963:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2964: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2965:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2966:             }
 2967:         }
 2968:     return;
 2969: }
 2970: 
 2971: sub get_feedurl_and_symb {
 2972:     my ($symb,$uname,$udom) = @_;
 2973:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2974:     $url = &Apache::lonnet::clutter($url);
 2975:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2976: 					$symb,$udom,$uname);
 2977:     if ($encrypturl =~ /^yes$/i) {
 2978: 	&Apache::lonenc::encrypted(\$url,1);
 2979: 	&Apache::lonenc::encrypted(\$symb,1);
 2980:     }
 2981:     return ($url,$symb);
 2982: }
 2983: 
 2984: sub get_submitted_files {
 2985:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2986:     my @files;
 2987:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2988:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2989:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2990:     	    push(@files,$file_url.$file);
 2991:         }
 2992:     }
 2993:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2994:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2995:     }
 2996:     return (\@files);
 2997: }
 2998: 
 2999: # ----------- Provides number of tries since last reset.
 3000: sub get_num_tries {
 3001:     my ($record,$last_reset,$part) = @_;
 3002:     my $timestamp = '';
 3003:     my $num_tries = 0;
 3004:     if ($$record{'version'}) {
 3005:         for (my $version=$$record{'version'};$version>=1;$version--) {
 3006:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 3007:                 $timestamp = $$record{$version.':timestamp'};
 3008:                 if ($timestamp > $last_reset) {
 3009:                     $num_tries ++;
 3010:                 } else {
 3011:                     last;
 3012:                 }
 3013:             }
 3014:         }
 3015:     }
 3016:     return $num_tries;
 3017: }
 3018: 
 3019: # ----------- Determine decrements required in aggregate totals 
 3020: sub decrement_aggs {
 3021:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 3022:     my %decrement = (
 3023:                         attempts => 0,
 3024:                         users => 0,
 3025:                         correct => 0
 3026:                     );
 3027:     $decrement{'attempts'} = $aggtries;
 3028:     if ($solvedstatus =~ /^correct/) {
 3029:         $decrement{'correct'} = 1;
 3030:     }
 3031:     if ($aggtries == $totaltries) {
 3032:         $decrement{'users'} = 1;
 3033:     }
 3034:     foreach my $type (keys(%decrement)) {
 3035:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 3036:     }
 3037:     return;
 3038: }
 3039: 
 3040: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 3041: sub get_last_resets {
 3042:     my ($symb,$courseid,$partids) =@_;
 3043:     my %last_resets;
 3044:     my $cdom = $env{'course.'.$courseid.'.domain'};
 3045:     my $cname = $env{'course.'.$courseid.'.num'};
 3046:     my @keys;
 3047:     foreach my $part (@{$partids}) {
 3048: 	push(@keys,"$symb\0$part\0resettime");
 3049:     }
 3050:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 3051: 				     $cdom,$cname);
 3052:     foreach my $part (@{$partids}) {
 3053: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 3054:     }
 3055:     return %last_resets;
 3056: }
 3057: 
 3058: # ----------- Handles creating versions for portfolio files as answers
 3059: sub version_portfiles {
 3060:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 3061:     my $version_parts = join('|',@$v_flag);
 3062:     my @returned_keys;
 3063:     my $parts = join('|', @$parts_graded);
 3064:     my $portfolio_root = '/userfiles/portfolio';
 3065:     foreach my $key (keys(%$record)) {
 3066:         my $new_portfiles;
 3067:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 3068:             my @versioned_portfiles;
 3069:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 3070:             foreach my $file (@portfiles) {
 3071:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 3072:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 3073: 		my ($answer_name,$answer_ver,$answer_ext) =
 3074: 		    &file_name_version_ext($answer_file);
 3075:                 my $getpropath = 1;    
 3076:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
 3077:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 3078:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 3079:                 if ($new_answer ne 'problem getting file') {
 3080:                     push(@versioned_portfiles, $directory.$new_answer);
 3081:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 3082:                         [$directory.$new_answer],
 3083:                         [$symb,$env{'request.course.id'},'graded']);
 3084:                 }
 3085:             }
 3086:             $$record{$key} = join(',',@versioned_portfiles);
 3087:             push(@returned_keys,$key);
 3088:         }
 3089:     } 
 3090:     return (@returned_keys);   
 3091: }
 3092: 
 3093: sub get_next_version {
 3094:     my ($answer_name, $answer_ext, $dir_list) = @_;
 3095:     my $version;
 3096:     foreach my $row (@$dir_list) {
 3097:         my ($file) = split(/\&/,$row,2);
 3098:         my ($file_name,$file_version,$file_ext) =
 3099: 	    &file_name_version_ext($file);
 3100:         if (($file_name eq $answer_name) && 
 3101: 	    ($file_ext eq $answer_ext)) {
 3102:                 # gets here if filename and extension match, regardless of version
 3103:                 if ($file_version ne '') {
 3104:                 # a versioned file is found  so save it for later
 3105:                 if ($file_version > $version) {
 3106: 		    $version = $file_version;
 3107: 	        }
 3108:             }
 3109:         }
 3110:     } 
 3111:     $version ++;
 3112:     return($version);
 3113: }
 3114: 
 3115: sub version_selected_portfile {
 3116:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 3117:     my ($answer_name,$answer_ver,$answer_ext) =
 3118:         &file_name_version_ext($file_name);
 3119:     my $new_answer;
 3120:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 3121:     if($env{'form.copy'} eq '-1') {
 3122:         $new_answer = 'problem getting file';
 3123:     } else {
 3124:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 3125:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 3126:                             $stu_name,$domain,'copy',
 3127: 		        '/portfolio'.$directory.$new_answer);
 3128:     }    
 3129:     return ($new_answer);
 3130: }
 3131: 
 3132: sub file_name_version_ext {
 3133:     my ($file)=@_;
 3134:     my @file_parts = split(/\./, $file);
 3135:     my ($name,$version,$ext);
 3136:     if (@file_parts > 1) {
 3137: 	$ext=pop(@file_parts);
 3138: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 3139: 	    $version=pop(@file_parts);
 3140: 	}
 3141: 	$name=join('.',@file_parts);
 3142:     } else {
 3143: 	$name=join('.',@file_parts);
 3144:     }
 3145:     return($name,$version,$ext);
 3146: }
 3147: 
 3148: #--------------------------------------------------------------------------------------
 3149: #
 3150: #-------------------------- Next few routines handles grading by section or whole class
 3151: #
 3152: #--- Javascript to handle grading by section or whole class
 3153: sub viewgrades_js {
 3154:     my ($request) = shift;
 3155: 
 3156:     $request->print(<<VIEWJAVASCRIPT);
 3157: <script type="text/javascript" language="javascript">
 3158:    function writePoint(partid,weight,point) {
 3159: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3160: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3161: 	if (point == "textval") {
 3162: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 3163: 	    if (isNaN(point) || parseFloat(point) < 0) {
 3164: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3165: 		var resetbox = false;
 3166: 		for (var i=0; i<radioButton.length; i++) {
 3167: 		    if (radioButton[i].checked) {
 3168: 			textbox.value = i;
 3169: 			resetbox = true;
 3170: 		    }
 3171: 		}
 3172: 		if (!resetbox) {
 3173: 		    textbox.value = "";
 3174: 		}
 3175: 		return;
 3176: 	    }
 3177: 	    if (parseFloat(point) > parseFloat(weight)) {
 3178: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 3179: 				   ") greater than the weight for the part. Accept?");
 3180: 		if (resp == false) {
 3181: 		    textbox.value = "";
 3182: 		    return;
 3183: 		}
 3184: 	    }
 3185: 	    for (var i=0; i<radioButton.length; i++) {
 3186: 		radioButton[i].checked=false;
 3187: 		if (parseFloat(point) == i) {
 3188: 		    radioButton[i].checked=true;
 3189: 		}
 3190: 	    }
 3191: 
 3192: 	} else {
 3193: 	    textbox.value = parseFloat(point);
 3194: 	}
 3195: 	for (i=0;i<document.classgrade.total.value;i++) {
 3196: 	    var user = document.classgrade["ctr"+i].value;
 3197: 	    user = user.replace(new RegExp(':', 'g'),"_");
 3198: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3199: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3200: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3201: 	    if (saveval != "correct") {
 3202: 		scorename.value = point;
 3203: 		if (selname[0].selected != true) {
 3204: 		    selname[0].selected = true;
 3205: 		}
 3206: 	    }
 3207: 	}
 3208: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 3209:     }
 3210: 
 3211:     function writeRadText(partid,weight) {
 3212: 	var selval   = document.classgrade["SELVAL_"+partid];
 3213: 	var radioButton = document.classgrade["RADVAL_"+partid];
 3214:         var override = document.classgrade["FORCE_"+partid].checked;
 3215: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 3216: 	if (selval[1].selected || selval[2].selected) {
 3217: 	    for (var i=0; i<radioButton.length; i++) {
 3218: 		radioButton[i].checked=false;
 3219: 
 3220: 	    }
 3221: 	    textbox.value = "";
 3222: 
 3223: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3224: 		var user = document.classgrade["ctr"+i].value;
 3225: 		user = user.replace(new RegExp(':', 'g'),"_");
 3226: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3227: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3228: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3229: 		if ((saveval != "correct") || override) {
 3230: 		    scorename.value = "";
 3231: 		    if (selval[1].selected) {
 3232: 			selname[1].selected = true;
 3233: 		    } else {
 3234: 			selname[2].selected = true;
 3235: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3236: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3237: 		    }
 3238: 		}
 3239: 	    }
 3240: 	} else {
 3241: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3242: 		var user = document.classgrade["ctr"+i].value;
 3243: 		user = user.replace(new RegExp(':', 'g'),"_");
 3244: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3245: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3246: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3247: 		if ((saveval != "correct") || override) {
 3248: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3249: 		    selname[0].selected = true;
 3250: 		}
 3251: 	    }
 3252: 	}	    
 3253:     }
 3254: 
 3255:     function changeSelect(partid,user) {
 3256: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3257: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3258: 	var point  = textbox.value;
 3259: 	var weight = document.classgrade["weight_"+partid].value;
 3260: 
 3261: 	if (isNaN(point) || parseFloat(point) < 0) {
 3262: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3263: 	    textbox.value = "";
 3264: 	    return;
 3265: 	}
 3266: 	if (parseFloat(point) > parseFloat(weight)) {
 3267: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3268: 			       ") greater than the weight of the part. Accept?");
 3269: 	    if (resp == false) {
 3270: 		textbox.value = "";
 3271: 		return;
 3272: 	    }
 3273: 	}
 3274: 	selval[0].selected = true;
 3275:     }
 3276: 
 3277:     function changeOneScore(partid,user) {
 3278: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3279: 	if (selval[1].selected || selval[2].selected) {
 3280: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3281: 	    if (selval[2].selected) {
 3282: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3283: 	    }
 3284:         }
 3285:     }
 3286: 
 3287:     function resetEntry(numpart) {
 3288: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3289: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3290: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3291: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3292: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3293: 	    for (var i=0; i<radioButton.length; i++) {
 3294: 		radioButton[i].checked=false;
 3295: 
 3296: 	    }
 3297: 	    textbox.value = "";
 3298: 	    selval[0].selected = true;
 3299: 
 3300: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3301: 		var user = document.classgrade["ctr"+i].value;
 3302: 		user = user.replace(new RegExp(':', 'g'),"_");
 3303: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3304: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3305: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3306: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3307: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3308: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3309: 		if (saveselval == "excused") {
 3310: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3311: 		} else {
 3312: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3313: 		}
 3314: 	    }
 3315: 	}
 3316:     }
 3317: 
 3318: </script>
 3319: VIEWJAVASCRIPT
 3320: }
 3321: 
 3322: #--- show scores for a section or whole class w/ option to change/update a score
 3323: sub viewgrades {
 3324:     my ($request) = shift;
 3325:     &viewgrades_js($request);
 3326: 
 3327:     my ($symb) = &get_symb($request);
 3328:     #need to make sure we have the correct data for later EXT calls, 
 3329:     #thus invalidate the cache
 3330:     &Apache::lonnet::devalidatecourseresdata(
 3331:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3332:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3333:     &Apache::lonnet::clear_EXT_cache_status();
 3334: 
 3335:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3336:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3337: 
 3338:     #view individual student submission form - called using Javascript viewOneStudent
 3339:     $result.=&jscriptNform($symb);
 3340: 
 3341:     #beginning of class grading form
 3342:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3343:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3344: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3345: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3346: 	&build_section_inputs().
 3347: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3348: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3349: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3350: 
 3351:     my $sectionClass;
 3352:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3353:     if ($env{'form.section'} eq 'all') {
 3354: 	$sectionClass='Class';
 3355:     } elsif ($env{'form.section'} eq 'none') {
 3356: 	$sectionClass='Students in no Section';
 3357:     } else {
 3358: 	$sectionClass='Students in Section(s) [_1]';
 3359:     }
 3360:     $result.=
 3361: 	'<h3>'.
 3362: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
 3363:     $result.= &Apache::loncommon::start_data_table();
 3364:     #radio buttons/text box for assigning points for a section or class.
 3365:     #handles different parts of a problem
 3366:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3367:     my %weight = ();
 3368:     my $ctsparts = 0;
 3369:     my %seen = ();
 3370:     my @part_response_id = &flatten_responseType($responseType);
 3371:     foreach my $part_response_id (@part_response_id) {
 3372:     	my ($partid,$respid) = @{ $part_response_id };
 3373: 	my $part_resp = join('_',@{ $part_response_id });
 3374: 	next if $seen{$partid};
 3375: 	$seen{$partid}++;
 3376: 	my $handgrade=$$handgrade{$part_resp};
 3377: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3378: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3379: 
 3380: 	my $display_part=&get_display_part($partid,$symb);
 3381: 	my $radio.='<table border="0"><tr>';  
 3382: 	my $ctr = 0;
 3383: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3384: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3385: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3386: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3387: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3388: 	    $ctr++;
 3389: 	}
 3390: 	$radio.='</tr></table>';
 3391: 	my $line = '<input type="text" name="TEXTVAL_'.
 3392: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3393: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3394: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3395: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
 3396: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3397: 		$weight{$partid}.')"> '.
 3398: 	    '<option selected="selected"> </option>'.
 3399: 	    '<option value="excused">'.&mt('excused').'</option>'.
 3400: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
 3401: 	    '</select></td>'.
 3402:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
 3403: 	$line.='<input type="hidden" name="partid_'.
 3404: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3405: 	$line.='<input type="hidden" name="weight_'.
 3406: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3407: 
 3408: 	$result.=
 3409: 	    &Apache::loncommon::start_data_table_row()."\n".
 3410: 	    &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).
 3411: 	    &Apache::loncommon::end_data_table_row()."\n";
 3412: 	$ctsparts++;
 3413:     }
 3414:     $result.=&Apache::loncommon::end_data_table()."\n".
 3415: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3416:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
 3417: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
 3418: 
 3419:     #table listing all the students in a section/class
 3420:     #header of table
 3421:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
 3422: 			 $section_display).'</h3>';
 3423:     $result.= &Apache::loncommon::start_data_table().
 3424: 	&Apache::loncommon::start_data_table_header_row().
 3425: 	'<th>'.&mt('No.').'</th>'.
 3426: 	'<th>'.&nameUserString('header')."</th>\n";
 3427:     my (@parts) = sort(&getpartlist($symb));
 3428:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3429:     my @partids = ();
 3430:     foreach my $part (@parts) {
 3431: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3432: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3433: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3434: 	my ($partid) = &split_part_type($part);
 3435:         push(@partids,$partid);
 3436: 	my $display_part=&get_display_part($partid,$symb);
 3437: 	if ($display =~ /^Partial Credit Factor/) {
 3438: 	    $result.='<th>'.
 3439: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
 3440: 		    $display_part,$weight{$partid}).'</th>'."\n";
 3441: 	    next;
 3442: 	    
 3443: 	} else {
 3444: 	    if ($display =~ /Problem Status/) {
 3445: 		my $grade_status_mt = &mt('Grade Status');
 3446: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
 3447: 	    }
 3448: 	    my $part_mt = &mt('Part:');
 3449: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
 3450: 	}
 3451: 
 3452: 	$result.='<th>'.$display.'</th>'."\n";
 3453:     }
 3454:     $result.=&Apache::loncommon::end_data_table_header_row();
 3455: 
 3456:     my %last_resets = 
 3457: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3458: 
 3459:     #get info for each student
 3460:     #list all the students - with points and grade status
 3461:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3462:     my $ctr = 0;
 3463:     foreach (sort 
 3464: 	     {
 3465: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3466: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3467: 		 }
 3468: 		 return $a cmp $b;
 3469: 	     } (keys(%$fullname))) {
 3470: 	$ctr++;
 3471: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3472: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3473:     }
 3474:     $result.=&Apache::loncommon::end_data_table();
 3475:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3476:     $result.='<input type="button" value="'.&mt('Save').'" '.
 3477: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3478:     if (scalar(%$fullname) eq 0) {
 3479: 	my $colspan=3+scalar(@parts);
 3480: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3481:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3482: 	$result='<span class="LC_warning">'.
 3483: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
 3484: 	        $section_display, $stu_status).
 3485: 	    '</span>';
 3486:     }
 3487:     $result.=&show_grading_menu_form($symb);
 3488:     return $result;
 3489: }
 3490: 
 3491: #--- call by previous routine to display each student
 3492: sub viewstudentgrade {
 3493:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3494:     my ($uname,$udom) = split(/:/,$student);
 3495:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3496:     my %aggregates = (); 
 3497:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
 3498: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3499: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3500: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3501: 	'\');" target="_self">'.$fullname.'</a> '.
 3502: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3503:     $student=~s/:/_/; # colon doen't work in javascript for names
 3504:     foreach my $apart (@$parts) {
 3505: 	my ($part,$type) = &split_part_type($apart);
 3506: 	my $score=$record{"resource.$part.$type"};
 3507:         $result.='<td align="center">';
 3508:         my ($aggtries,$totaltries);
 3509:         unless (exists($aggregates{$part})) {
 3510: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3511: 
 3512: 	    $aggtries = $totaltries;
 3513:             if ($$last_resets{$part}) {  
 3514:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3515: 					   $part);
 3516:             }
 3517:             $result.='<input type="hidden" name="'.
 3518:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3519:             $result.='<input type="hidden" name="'.
 3520:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3521:             $aggregates{$part} = 1;
 3522:         }
 3523: 	if ($type eq 'awarded') {
 3524: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3525: 	    $result.='<input type="hidden" name="'.
 3526: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3527: 	    $result.='<input type="text" name="'.
 3528: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3529: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3530: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3531: 	} elsif ($type eq 'solved') {
 3532: 	    my ($status,$foo)=split(/_/,$score,2);
 3533: 	    $status = 'nothing' if ($status eq '');
 3534: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3535: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3536: 	    $result.='&nbsp;<select name="'.
 3537: 		'GD_'.$student.'_'.$part.'_solved" '.
 3538: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3539: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
 3540: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
 3541: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
 3542: 	    $result.="</select>&nbsp;</td>\n";
 3543: 	} else {
 3544: 	    $result.='<input type="hidden" name="'.
 3545: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3546: 		    "\n";
 3547: 	    $result.='<input type="text" name="'.
 3548: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3549: 		'value="'.$score.'" size="4" /></td>'."\n";
 3550: 	}
 3551:     }
 3552:     $result.=&Apache::loncommon::end_data_table_row();
 3553:     return $result;
 3554: }
 3555: 
 3556: #--- change scores for all the students in a section/class
 3557: #    record does not get update if unchanged
 3558: sub editgrades {
 3559:     my ($request) = @_;
 3560: 
 3561:     my $symb=&get_symb($request);
 3562:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3563:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
 3564:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
 3565:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3566: 
 3567:     my $result= &Apache::loncommon::start_data_table().
 3568: 	&Apache::loncommon::start_data_table_header_row().
 3569: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
 3570: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
 3571:     my %scoreptr = (
 3572: 		    'correct'  =>'correct_by_override',
 3573: 		    'incorrect'=>'incorrect_by_override',
 3574: 		    'excused'  =>'excused',
 3575: 		    'ungraded' =>'ungraded_attempted',
 3576: 		    'nothing'  => '',
 3577: 		    );
 3578:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3579: 
 3580:     my (@partid);
 3581:     my %weight = ();
 3582:     my %columns = ();
 3583:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3584: 
 3585:     my (@parts) = sort(&getpartlist($symb));
 3586:     my $header;
 3587:     while ($ctr < $env{'form.totalparts'}) {
 3588: 	my $partid = $env{'form.partid_'.$ctr};
 3589: 	push(@partid,$partid);
 3590: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3591: 	$ctr++;
 3592:     }
 3593:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3594:     foreach my $partid (@partid) {
 3595: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
 3596: 	    '<th align="center">'.&mt('New Score').'</th>';
 3597: 	$columns{$partid}=2;
 3598: 	foreach my $stores (@parts) {
 3599: 	    my ($part,$type) = &split_part_type($stores);
 3600: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3601: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3602: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3603: 	    $display =~ s/\[Part: (\w)+\]//;
 3604: 	    $display =~ s/Number of Attempts/Tries/;
 3605: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
 3606: 		'<th align="center">'.&mt('New '.$display).'</th>';
 3607: 	    $columns{$partid}+=2;
 3608: 	}
 3609:     }
 3610:     foreach my $partid (@partid) {
 3611: 	my $display_part=&get_display_part($partid,$symb);
 3612: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
 3613: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
 3614: 	    '</th>';
 3615: 
 3616:     }
 3617:     $result .= &Apache::loncommon::end_data_table_header_row().
 3618: 	&Apache::loncommon::start_data_table_header_row().
 3619: 	$header.
 3620: 	&Apache::loncommon::end_data_table_header_row();
 3621:     my @noupdate;
 3622:     my ($updateCtr,$noupdateCtr) = (1,1);
 3623:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3624: 	my $line;
 3625: 	my $user = $env{'form.ctr'.$i};
 3626: 	my ($uname,$udom)=split(/:/,$user);
 3627: 	my %newrecord;
 3628: 	my $updateflag = 0;
 3629: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3630: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3631: 	if (!&canmodify($usec)) {
 3632: 	    my $numcols=scalar(@partid)*4+2;
 3633: 	    push(@noupdate,
 3634: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
 3635: 		 &mt('Not allowed to modify student')."</span></td></tr>");
 3636: 	    next;
 3637: 	}
 3638:         my %aggregate = ();
 3639:         my $aggregateflag = 0;
 3640: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3641: 	foreach (@partid) {
 3642: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3643: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3644: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3645: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3646: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3647: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3648: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3649: 	    my $score;
 3650: 	    if ($partial eq '') {
 3651: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3652: 	    } elsif ($partial > 0) {
 3653: 		$score = 'correct_by_override';
 3654: 	    } elsif ($partial == 0) {
 3655: 		$score = 'incorrect_by_override';
 3656: 	    }
 3657: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3658: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3659: 
 3660: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3661: 		"$env{'user.name'}:$env{'user.domain'}";
 3662: 	    if ($dropMenu eq 'reset status' &&
 3663: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3664: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3665: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3666: 		$newrecord{'resource.'.$_.'.award'} = '';
 3667: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3668: 		$updateflag = 1;
 3669:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3670:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3671:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3672:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3673:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3674:                     $aggregateflag = 1;
 3675:                 }
 3676: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3677: 		$updateflag = 1;
 3678: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3679: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3680: 		$rec_update++;
 3681: 	    }
 3682: 
 3683: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3684: 		'<td align="center">'.$awarded.
 3685: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3686: 
 3687: 
 3688: 	    my $partid=$_;
 3689: 	    foreach my $stores (@parts) {
 3690: 		my ($part,$type) = &split_part_type($stores);
 3691: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3692: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3693: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3694: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3695: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3696: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3697: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3698: 		    $updateflag=1;
 3699: 		}
 3700: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3701: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3702: 	    }
 3703: 	}
 3704: 	$line.="\n";
 3705: 
 3706: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3707: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3708: 
 3709: 	if ($updateflag) {
 3710: 	    $count++;
 3711: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3712: 				    $udom,$uname);
 3713: 
 3714: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3715: 					      $cnum,$udom,$uname)) {
 3716: 		# need to figure out if should be in queue.
 3717: 		my %record =  
 3718: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3719: 					     $udom,$uname);
 3720: 		my $all_graded = 1;
 3721: 		my $none_graded = 1;
 3722: 		foreach my $part (@parts) {
 3723: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3724: 			$all_graded = 0;
 3725: 		    } else {
 3726: 			$none_graded = 0;
 3727: 		    }
 3728: 		}
 3729: 
 3730: 		if ($all_graded || $none_graded) {
 3731: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3732: 							   $symb,$cdom,$cnum,
 3733: 							   $udom,$uname);
 3734: 		}
 3735: 	    }
 3736: 
 3737: 	    $result.=&Apache::loncommon::start_data_table_row().
 3738: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
 3739: 		&Apache::loncommon::end_data_table_row();
 3740: 	    $updateCtr++;
 3741: 	} else {
 3742: 	    push(@noupdate,
 3743: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
 3744: 	    $noupdateCtr++;
 3745: 	}
 3746:         if ($aggregateflag) {
 3747:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3748: 				  $cdom,$cnum);
 3749:         }
 3750:     }
 3751:     if (@noupdate) {
 3752: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3753: 	my $numcols=scalar(@partid)*4+2;
 3754: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
 3755: 	    '<td align="center" colspan="'.$numcols.'">'.
 3756: 	    &mt('No Changes Occurred For the Students Below').
 3757: 	    '</td>'.
 3758: 	    &Apache::loncommon::end_data_table_row();
 3759: 	foreach my $line (@noupdate) {
 3760: 	    $result.=
 3761: 		&Apache::loncommon::start_data_table_row().
 3762: 		$line.
 3763: 		&Apache::loncommon::end_data_table_row();
 3764: 	}
 3765:     }
 3766:     $result .= &Apache::loncommon::end_data_table().
 3767: 	&show_grading_menu_form($symb);
 3768:     my $msg = '<p><b>'.
 3769: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
 3770: 	    $rec_update,$count).'</b><br />'.
 3771: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
 3772: 	'</b></p>';
 3773:     return $title.$msg.$result;
 3774: }
 3775: 
 3776: sub split_part_type {
 3777:     my ($partstr) = @_;
 3778:     my ($temp,@allparts)=split(/_/,$partstr);
 3779:     my $type=pop(@allparts);
 3780:     my $part=join('_',@allparts);
 3781:     return ($part,$type);
 3782: }
 3783: 
 3784: #------------- end of section for handling grading by section/class ---------
 3785: #
 3786: #----------------------------------------------------------------------------
 3787: 
 3788: 
 3789: #----------------------------------------------------------------------------
 3790: #
 3791: #-------------------------- Next few routines handles grading by csv upload
 3792: #
 3793: #--- Javascript to handle csv upload
 3794: sub csvupload_javascript_reverse_associate {
 3795:     my $error1=&mt('You need to specify the username or ID');
 3796:     my $error2=&mt('You need to specify at least one grading field');
 3797:   return(<<ENDPICK);
 3798:   function verify(vf) {
 3799:     var foundsomething=0;
 3800:     var founduname=0;
 3801:     var foundID=0;
 3802:     for (i=0;i<=vf.nfields.value;i++) {
 3803:       tw=eval('vf.f'+i+'.selectedIndex');
 3804:       if (i==0 && tw!=0) { foundID=1; }
 3805:       if (i==1 && tw!=0) { founduname=1; }
 3806:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3807:     }
 3808:     if (founduname==0 && foundID==0) {
 3809: 	alert('$error1');
 3810: 	return;
 3811:     }
 3812:     if (foundsomething==0) {
 3813: 	alert('$error2');
 3814: 	return;
 3815:     }
 3816:     vf.submit();
 3817:   }
 3818:   function flip(vf,tf) {
 3819:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3820:     var i;
 3821:     for (i=0;i<=vf.nfields.value;i++) {
 3822:       //can not pick the same destination field for both name and domain
 3823:       if (((i ==0)||(i ==1)) && 
 3824:           ((tf==0)||(tf==1)) && 
 3825:           (i!=tf) &&
 3826:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3827:         eval('vf.f'+i+'.selectedIndex=0;')
 3828:       }
 3829:     }
 3830:   }
 3831: ENDPICK
 3832: }
 3833: 
 3834: sub csvupload_javascript_forward_associate {
 3835:     my $error1=&mt('You need to specify the username or ID');
 3836:     my $error2=&mt('You need to specify at least one grading field');
 3837:   return(<<ENDPICK);
 3838:   function verify(vf) {
 3839:     var foundsomething=0;
 3840:     var founduname=0;
 3841:     var foundID=0;
 3842:     for (i=0;i<=vf.nfields.value;i++) {
 3843:       tw=eval('vf.f'+i+'.selectedIndex');
 3844:       if (tw==1) { foundID=1; }
 3845:       if (tw==2) { founduname=1; }
 3846:       if (tw>3) { foundsomething=1; }
 3847:     }
 3848:     if (founduname==0 && foundID==0) {
 3849: 	alert('$error1');
 3850: 	return;
 3851:     }
 3852:     if (foundsomething==0) {
 3853: 	alert('$error2');
 3854: 	return;
 3855:     }
 3856:     vf.submit();
 3857:   }
 3858:   function flip(vf,tf) {
 3859:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3860:     var i;
 3861:     //can not pick the same destination field twice
 3862:     for (i=0;i<=vf.nfields.value;i++) {
 3863:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3864:         eval('vf.f'+i+'.selectedIndex=0;')
 3865:       }
 3866:     }
 3867:   }
 3868: ENDPICK
 3869: }
 3870: 
 3871: sub csvuploadmap_header {
 3872:     my ($request,$symb,$datatoken,$distotal)= @_;
 3873:     my $javascript;
 3874:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3875: 	$javascript=&csvupload_javascript_reverse_associate();
 3876:     } else {
 3877: 	$javascript=&csvupload_javascript_forward_associate();
 3878:     }
 3879: 
 3880:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3881:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3882:     my $ignore=&mt('Ignore First Line');
 3883:     $symb = &Apache::lonenc::check_encrypt($symb);
 3884:     $request->print(<<ENDPICK);
 3885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3886: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3887: $result
 3888: <hr />
 3889: <h3>Identify fields</h3>
 3890: Total number of records found in file: $distotal <hr />
 3891: Enter as many fields as you can. The system will inform you and bring you back
 3892: to this page if the data selected is insufficient to run your class.<hr />
 3893: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3894: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3895: <input type="hidden" name="associate"  value="" />
 3896: <input type="hidden" name="phase"      value="three" />
 3897: <input type="hidden" name="datatoken"  value="$datatoken" />
 3898: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3899: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3900: <input type="hidden" name="upfile_associate" 
 3901:                                        value="$env{'form.upfile_associate'}" />
 3902: <input type="hidden" name="symb"       value="$symb" />
 3903: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3904: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3905: <input type="hidden" name="command"    value="csvuploadoptions" />
 3906: <hr />
 3907: <script type="text/javascript" language="Javascript">
 3908: $javascript
 3909: </script>
 3910: ENDPICK
 3911:     return '';
 3912: 
 3913: }
 3914: 
 3915: sub csvupload_fields {
 3916:     my ($symb) = @_;
 3917:     my (@parts) = &getpartlist($symb);
 3918:     my @fields=(['ID','Student ID'],
 3919: 		['username','Student Username'],
 3920: 		['domain','Student Domain']);
 3921:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3922:     foreach my $part (sort(@parts)) {
 3923: 	my @datum;
 3924: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3925: 	my $name=$part;
 3926: 	if  (!$display) { $display = $name; }
 3927: 	@datum=($name,$display);
 3928: 	if ($name=~/^stores_(.*)_awarded/) {
 3929: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3930: 	}
 3931: 	push(@fields,\@datum);
 3932:     }
 3933:     return (@fields);
 3934: }
 3935: 
 3936: sub csvuploadmap_footer {
 3937:     my ($request,$i,$keyfields) =@_;
 3938:     $request->print(<<ENDPICK);
 3939: </table>
 3940: <input type="hidden" name="nfields" value="$i" />
 3941: <input type="hidden" name="keyfields" value="$keyfields" />
 3942: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3943: </form>
 3944: ENDPICK
 3945: }
 3946: 
 3947: sub checkforfile_js {
 3948:     my $result =<<CSVFORMJS;
 3949: <script type="text/javascript" language="javascript">
 3950:     function checkUpload(formname) {
 3951: 	if (formname.upfile.value == "") {
 3952: 	    alert("Please use the browse button to select a file from your local directory.");
 3953: 	    return false;
 3954: 	}
 3955: 	formname.submit();
 3956:     }
 3957:     </script>
 3958: CSVFORMJS
 3959:     return $result;
 3960: }
 3961: 
 3962: sub upcsvScores_form {
 3963:     my ($request) = shift;
 3964:     my ($symb)=&get_symb($request);
 3965:     if (!$symb) {return '';}
 3966:     my $result=&checkforfile_js();
 3967:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3968:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3969:     $result.=$table;
 3970:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3971:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3972:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3973: 	'.</b></td></tr>'."\n";
 3974:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3975:     my $upload=&mt("Upload Scores");
 3976:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3977:     my $ignore=&mt('Ignore First Line');
 3978:     $symb = &Apache::lonenc::check_encrypt($symb);
 3979:     $result.=<<ENDUPFORM;
 3980: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3981: <input type="hidden" name="symb" value="$symb" />
 3982: <input type="hidden" name="command" value="csvuploadmap" />
 3983: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3984: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3985: $upfile_select
 3986: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3987: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3988: </form>
 3989: ENDUPFORM
 3990:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3991:                            &mt("How do I create a CSV file from a spreadsheet"))
 3992:     .'</td></tr></table>'."\n";
 3993:     $result.='</td></tr></table><br /><br />'."\n";
 3994:     $result.=&show_grading_menu_form($symb);
 3995:     return $result;
 3996: }
 3997: 
 3998: 
 3999: sub csvuploadmap {
 4000:     my ($request)= @_;
 4001:     my ($symb)=&get_symb($request);
 4002:     if (!$symb) {return '';}
 4003: 
 4004:     my $datatoken;
 4005:     if (!$env{'form.datatoken'}) {
 4006: 	$datatoken=&Apache::loncommon::upfile_store($request);
 4007:     } else {
 4008: 	$datatoken=$env{'form.datatoken'};
 4009: 	&Apache::loncommon::load_tmp_file($request);
 4010:     }
 4011:     my @records=&Apache::loncommon::upfile_record_sep();
 4012:     if ($env{'form.noFirstLine'}) { shift(@records); }
 4013:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 4014:     my ($i,$keyfields);
 4015:     if (@records) {
 4016: 	my @fields=&csvupload_fields($symb);
 4017: 
 4018: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 4019: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 4020: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 4021: 							  \@fields);
 4022: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 4023: 	    chop($keyfields);
 4024: 	} else {
 4025: 	    unshift(@fields,['none','']);
 4026: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 4027: 							    \@fields);
 4028:             foreach my $rec (@records) {
 4029:                 my %temp = &Apache::loncommon::record_sep($rec);
 4030:                 if (%temp) {
 4031:                     $keyfields=join(',',sort(keys(%temp)));
 4032:                     last;
 4033:                 }
 4034:             }
 4035: 	}
 4036:     }
 4037:     &csvuploadmap_footer($request,$i,$keyfields);
 4038:     $request->print(&show_grading_menu_form($symb));
 4039: 
 4040:     return '';
 4041: }
 4042: 
 4043: sub csvuploadoptions {
 4044:     my ($request)= @_;
 4045:     my ($symb)=&get_symb($request);
 4046:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 4047:     my $ignore=&mt('Ignore First Line');
 4048:     $request->print(<<ENDPICK);
 4049: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 4050: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 4051: <input type="hidden" name="command"    value="csvuploadassign" />
 4052: <!--
 4053: <p>
 4054: <label>
 4055:    <input type="checkbox" name="show_full_results" />
 4056:    Show a table of all changes
 4057: </label>
 4058: </p>
 4059: -->
 4060: <p>
 4061: <label>
 4062:    <input type="checkbox" name="overwite_scores" checked="checked" />
 4063:    Overwrite any existing score
 4064: </label>
 4065: </p>
 4066: ENDPICK
 4067:     my %fields=&get_fields();
 4068:     if (!defined($fields{'domain'})) {
 4069: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 4070: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 4071:     }
 4072:     foreach my $key (sort(keys(%env))) {
 4073: 	if ($key !~ /^form\.(.*)$/) { next; }
 4074: 	my $cleankey=$1;
 4075: 	if ($cleankey eq 'command') { next; }
 4076: 	$request->print('<input type="hidden" name="'.$cleankey.
 4077: 			'"  value="'.$env{$key}.'" />'."\n");
 4078:     }
 4079:     # FIXME do a check for any duplicated user ids...
 4080:     # FIXME do a check for any invalid user ids?...
 4081:     $request->print('<input type="submit" value="Assign Grades" /><br />
 4082: <hr /></form>'."\n");
 4083:     $request->print(&show_grading_menu_form($symb));
 4084:     return '';
 4085: }
 4086: 
 4087: sub get_fields {
 4088:     my %fields;
 4089:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4090:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4091: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 4092: 	    if ($env{'form.f'.$i} ne 'none') {
 4093: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 4094: 	    }
 4095: 	} else {
 4096: 	    if ($env{'form.f'.$i} ne 'none') {
 4097: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 4098: 	    }
 4099: 	}
 4100:     }
 4101:     return %fields;
 4102: }
 4103: 
 4104: sub csvuploadassign {
 4105:     my ($request)= @_;
 4106:     my ($symb)=&get_symb($request);
 4107:     if (!$symb) {return '';}
 4108:     my $error_msg = '';
 4109:     &Apache::loncommon::load_tmp_file($request);
 4110:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 4111:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 4112:     my %fields=&get_fields();
 4113:     $request->print('<h3>Assigning Grades</h3>');
 4114:     my $courseid=$env{'request.course.id'};
 4115:     my ($classlist) = &getclasslist('all',0);
 4116:     my @notallowed;
 4117:     my @skipped;
 4118:     my $countdone=0;
 4119:     foreach my $grade (@gradedata) {
 4120: 	my %entries=&Apache::loncommon::record_sep($grade);
 4121: 	my $domain;
 4122: 	if ($entries{$fields{'domain'}}) {
 4123: 	    $domain=$entries{$fields{'domain'}};
 4124: 	} else {
 4125: 	    $domain=$env{'form.default_domain'};
 4126: 	}
 4127: 	$domain=~s/\s//g;
 4128: 	my $username=$entries{$fields{'username'}};
 4129: 	$username=~s/\s//g;
 4130: 	if (!$username) {
 4131: 	    my $id=$entries{$fields{'ID'}};
 4132: 	    $id=~s/\s//g;
 4133: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 4134: 	    $username=$ids{$id};
 4135: 	}
 4136: 	if (!exists($$classlist{"$username:$domain"})) {
 4137: 	    my $id=$entries{$fields{'ID'}};
 4138: 	    $id=~s/\s//g;
 4139: 	    if ($id) {
 4140: 		push(@skipped,"$id:$domain");
 4141: 	    } else {
 4142: 		push(@skipped,"$username:$domain");
 4143: 	    }
 4144: 	    next;
 4145: 	}
 4146: 	my $usec=$classlist->{"$username:$domain"}[5];
 4147: 	if (!&canmodify($usec)) {
 4148: 	    push(@notallowed,"$username:$domain");
 4149: 	    next;
 4150: 	}
 4151: 	my %points;
 4152: 	my %grades;
 4153: 	foreach my $dest (keys(%fields)) {
 4154: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 4155: 		$dest eq 'domain') { next; }
 4156: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 4157: 	    if ($dest=~/stores_(.*)_points/) {
 4158: 		my $part=$1;
 4159: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 4160: 					      $symb,$domain,$username);
 4161:                 if ($wgt) {
 4162:                     $entries{$fields{$dest}}=~s/\s//g;
 4163:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 4164:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 4165:                                           : 'correct_by_override';
 4166:                     $grades{"resource.$part.awarded"}=$pcr;
 4167:                     $grades{"resource.$part.solved"}=$award;
 4168:                     $points{$part}=1;
 4169:                 } else {
 4170:                     $error_msg = "<br />" .
 4171:                         &mt("Some point values were assigned"
 4172:                             ." for problems with a weight "
 4173:                             ."of zero. These values were "
 4174:                             ."ignored.");
 4175:                 }
 4176: 	    } else {
 4177: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 4178: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 4179: 		my $store_key=$dest;
 4180: 		$store_key=~s/^stores/resource/;
 4181: 		$store_key=~s/_/\./g;
 4182: 		$grades{$store_key}=$entries{$fields{$dest}};
 4183: 	    }
 4184: 	}
 4185: 	if (! %grades) { 
 4186:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
 4187:         } else {
 4188: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 4189: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
 4190: 					   $env{'request.course.id'},
 4191: 					   $domain,$username);
 4192: 	   if ($result eq 'ok') {
 4193: 	      $request->print('.');
 4194: 	   } else {
 4195: 	      $request->print("<p><span class=\"LC_error\">".
 4196:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
 4197:                                   "$username:$domain",$result)."</span></p>");
 4198: 	   }
 4199: 	   $request->rflush();
 4200: 	   $countdone++;
 4201:         }
 4202:     }
 4203:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
 4204:     if (@skipped) {
 4205: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
 4206: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 4207:     }
 4208:     if (@notallowed) {
 4209: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
 4210: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 4211:     }
 4212:     $request->print("<br />\n");
 4213:     $request->print(&show_grading_menu_form($symb));
 4214:     return $error_msg;
 4215: }
 4216: #------------- end of section for handling csv file upload ---------
 4217: #
 4218: #-------------------------------------------------------------------
 4219: #
 4220: #-------------- Next few routines handle grading by page/sequence
 4221: #
 4222: #--- Select a page/sequence and a student to grade
 4223: sub pickStudentPage {
 4224:     my ($request) = shift;
 4225: 
 4226:     $request->print(<<LISTJAVASCRIPT);
 4227: <script type="text/javascript" language="javascript">
 4228: 
 4229: function checkPickOne(formname) {
 4230:     if (radioSelection(formname.student) == null) {
 4231: 	alert("Please select the student you wish to grade.");
 4232: 	return;
 4233:     }
 4234:     ptr = pullDownSelection(formname.selectpage);
 4235:     formname.page.value = formname["page"+ptr].value;
 4236:     formname.title.value = formname["title"+ptr].value;
 4237:     formname.submit();
 4238: }
 4239: 
 4240: </script>
 4241: LISTJAVASCRIPT
 4242:     &commonJSfunctions($request);
 4243:     my ($symb) = &get_symb($request);
 4244:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4245:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4246:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4247: 
 4248:     my $result='<h3><span class="LC_info">&nbsp;'.
 4249: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
 4250: 
 4251:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4252:     my ($titles,$symbx) = &getSymbMap();
 4253:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4254: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4255: #    my $type=($curpage =~ /\.(page|sequence)/);
 4256:     my $select = '<select name="selectpage">'."\n";
 4257:     my $ctr=0;
 4258:     foreach (@$titles) {
 4259: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4260: 	$select.='<option value="'.$ctr.'" '.
 4261: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4262: 	    '>'.$showtitle.'</option>'."\n";
 4263: 	$ctr++;
 4264:     }
 4265:     $select.= '</select>';
 4266:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
 4267: 
 4268:     $ctr=0;
 4269:     foreach (@$titles) {
 4270: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4271: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4272: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4273: 	$ctr++;
 4274:     }
 4275:     $result.='<input type="hidden" name="page" />'."\n".
 4276: 	'<input type="hidden" name="title" />'."\n";
 4277: 
 4278:     my $options =
 4279: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
 4280: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
 4281:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
 4282: 
 4283:     $options =
 4284: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
 4285: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
 4286: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
 4287:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
 4288:     
 4289:     $result.=&build_section_inputs();
 4290:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4291:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4292: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4293: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4294: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4295: 
 4296:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
 4297: 			  '<input type="text" name="CODE" value="" />').
 4298: 			      '<br />'."\n";
 4299: 
 4300:     $result.='&nbsp;<input type="button" '.
 4301: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
 4302: 
 4303:     $request->print($result);
 4304: 
 4305:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
 4306: 	&Apache::loncommon::start_data_table().
 4307: 	&Apache::loncommon::start_data_table_header_row().
 4308: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4309: 	'<th>'.&nameUserString('header').'</th>'.
 4310: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
 4311: 	'<th>'.&nameUserString('header').'</th>'.
 4312: 	&Apache::loncommon::end_data_table_header_row();
 4313:  
 4314:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4315:     my $ptr = 1;
 4316:     foreach my $student (sort 
 4317: 			 {
 4318: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4319: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4320: 			     }
 4321: 			     return $a cmp $b;
 4322: 			 } (keys(%$fullname))) {
 4323: 	my ($uname,$udom) = split(/:/,$student);
 4324: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
 4325:                                   : '</td>');
 4326: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4327: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4328: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4329: 	$studentTable.=
 4330: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
 4331:                          : '');
 4332: 	$ptr++;
 4333:     }
 4334:     if ($ptr%2 == 0) {
 4335: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
 4336: 	    &Apache::loncommon::end_data_table_row();
 4337:     }
 4338:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
 4339:     $studentTable.='<input type="button" '.
 4340: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
 4341: 
 4342:     $studentTable.=&show_grading_menu_form($symb);
 4343:     $request->print($studentTable);
 4344: 
 4345:     return '';
 4346: }
 4347: 
 4348: sub getSymbMap {
 4349:     my $navmap = Apache::lonnavmaps::navmap->new();
 4350: 
 4351:     my %symbx = ();
 4352:     my @titles = ();
 4353:     my $minder = 0;
 4354: 
 4355:     # Gather every sequence that has problems.
 4356:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4357: 					       1,0,1);
 4358:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4359: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4360: 	    my $title = $minder.'.'.
 4361: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4362: 	    push(@titles, $title); # minder in case two titles are identical
 4363: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4364: 	    $minder++;
 4365: 	}
 4366:     }
 4367:     return \@titles,\%symbx;
 4368: }
 4369: 
 4370: #
 4371: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4372: sub displayPage {
 4373:     my ($request) = shift;
 4374: 
 4375:     my ($symb) = &get_symb($request);
 4376:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4377:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4378:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4379:     my $pageTitle = $env{'form.page'};
 4380:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4381:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4382:     my $usec=$classlist->{$env{'form.student'}}[5];
 4383: 
 4384:     #need to make sure we have the correct data for later EXT calls, 
 4385:     #thus invalidate the cache
 4386:     &Apache::lonnet::devalidatecourseresdata(
 4387:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4388:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4389:     &Apache::lonnet::clear_EXT_cache_status();
 4390: 
 4391:     if (!&canview($usec)) {
 4392: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
 4393: 	$request->print(&show_grading_menu_form($symb));
 4394: 	return;
 4395:     }
 4396:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4397:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
 4398: 	'</h3>'."\n";
 4399:     $env{'form.CODE'} = uc($env{'form.CODE'});
 4400:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
 4401: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
 4402:     } else {
 4403: 	delete($env{'form.CODE'});
 4404:     }
 4405:     &sub_page_js($request);
 4406:     $request->print($result);
 4407: 
 4408:     my $navmap = Apache::lonnavmaps::navmap->new();
 4409:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4410:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4411:     if (!$map) {
 4412: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
 4413: 	$request->print(&show_grading_menu_form($symb));
 4414: 	return; 
 4415:     }
 4416:     my $iterator = $navmap->getIterator($map->map_start(),
 4417: 					$map->map_finish());
 4418: 
 4419:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4420: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4421: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4422: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4423: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4424: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4425: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4426: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4427: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4428: 
 4429:     if (defined($env{'form.CODE'})) {
 4430: 	$studentTable.=
 4431: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4432:     }
 4433:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4434: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
 4435: 
 4436:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
 4437: 	&Apache::loncommon::start_data_table().
 4438: 	&Apache::loncommon::start_data_table_header_row().
 4439: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
 4440: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
 4441: 	&Apache::loncommon::end_data_table_header_row();
 4442: 
 4443:     &Apache::lonxml::clear_problem_counter();
 4444:     my ($depth,$question,$prob) = (1,1,1);
 4445:     $iterator->next(); # skip the first BEGIN_MAP
 4446:     my $curRes = $iterator->next(); # for "current resource"
 4447:     while ($depth > 0) {
 4448:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4449:         if($curRes == $iterator->END_MAP) { $depth--; }
 4450: 
 4451:         if (ref($curRes) && $curRes->is_problem()) {
 4452: 	    my $parts = $curRes->parts();
 4453:             my $title = $curRes->compTitle();
 4454: 	    my $symbx = $curRes->symb();
 4455: 	    $studentTable.=
 4456: 		&Apache::loncommon::start_data_table_row().
 4457: 		'<td align="center" valign="top" >'.$prob.
 4458: 		(scalar(@{$parts}) == 1 ? '' 
 4459: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
 4460: 							scalar(@{$parts}))
 4461: 		 ).
 4462: 		 '</td>';
 4463: 	    $studentTable.='<td valign="top">';
 4464: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4465: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4466: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4467: 					     undef,'both',\%form);
 4468: 	    } else {
 4469: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4470: 		$companswer =~ s|<form(.*?)>||g;
 4471: 		$companswer =~ s|</form>||g;
 4472: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4473: #		    $companswer =~ s/$1/ /ms;
 4474: #		    $request->print('match='.$1."<br />\n");
 4475: #		}
 4476: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4477: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
 4478: 	    }
 4479: 
 4480: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4481: 
 4482: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4483: 		if ($record{'version'} eq '') {
 4484: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
 4485: 		} else {
 4486: 		    my %responseType = ();
 4487: 		    foreach my $partid (@{$parts}) {
 4488: 			my @responseIds =$curRes->responseIds($partid);
 4489: 			my @responseType =$curRes->responseType($partid);
 4490: 			my %responseIds;
 4491: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4492: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4493: 			}
 4494: 			$responseType{$partid} = \%responseIds;
 4495: 		    }
 4496: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4497: 
 4498: 		}
 4499: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4500: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4501: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4502: 									$env{'request.course.id'},
 4503: 									'','.submission');
 4504:  
 4505: 	    }
 4506: 	    if (&canmodify($usec)) {
 4507: 		foreach my $partid (@{$parts}) {
 4508: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4509: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4510: 		    $question++;
 4511: 		}
 4512: 		$prob++;
 4513: 	    }
 4514: 	    $studentTable.='</td></tr>';
 4515: 
 4516: 	}
 4517:         $curRes = $iterator->next();
 4518:     }
 4519: 
 4520:     $studentTable.='</table>'."\n".
 4521: 	'<input type="button" value="'.&mt('Save').'" '.
 4522: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4523: 	'</form>'."\n";
 4524:     $studentTable.=&show_grading_menu_form($symb);
 4525:     $request->print($studentTable);
 4526: 
 4527:     return '';
 4528: }
 4529: 
 4530: sub displaySubByDates {
 4531:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4532:     my $isCODE=0;
 4533:     my $isTask = ($symb =~/\.task$/);
 4534:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4535:     my $studentTable=&Apache::loncommon::start_data_table().
 4536: 	&Apache::loncommon::start_data_table_header_row().
 4537: 	'<th>'.&mt('Date/Time').'</th>'.
 4538: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
 4539: 	'<th>'.&mt('Submission').'</th>'.
 4540: 	'<th>'.&mt('Status').'</th>'.
 4541: 	&Apache::loncommon::end_data_table_header_row();
 4542:     my ($version);
 4543:     my %mark;
 4544:     my %orders;
 4545:     $mark{'correct_by_student'} = $checkIcon;
 4546:     if (!exists($$record{'1:timestamp'})) {
 4547: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
 4548:     }
 4549: 
 4550:     my $interaction;
 4551:     my $no_increment = 1;
 4552:     for ($version=1;$version<=$$record{'version'};$version++) {
 4553: 	my $timestamp = 
 4554: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
 4555: 	if (exists($$record{$version.':resource.0.version'})) {
 4556: 	    $interaction = $$record{$version.':resource.0.version'};
 4557: 	}
 4558: 
 4559: 	my $where = ($isTask ? "$version:resource.$interaction"
 4560: 		             : "$version:resource");
 4561: 	$studentTable.=&Apache::loncommon::start_data_table_row().
 4562: 	    '<td>'.$timestamp.'</td>';
 4563: 	if ($isCODE) {
 4564: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4565: 	}
 4566: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4567: 	my @displaySub = ();
 4568: 	foreach my $partid (@{$parts}) {
 4569: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4570: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4571: 	    
 4572: 
 4573: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4574: 	    my $display_part=&get_display_part($partid,$symb);
 4575: 	    foreach my $matchKey (@matchKey) {
 4576: 		if (exists($$record{$version.':'.$matchKey}) &&
 4577: 		    $$record{$version.':'.$matchKey} ne '') {
 4578: 
 4579: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4580: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4581: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
 4582: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
 4583: 			$responseId.')</span>&nbsp;<b>';
 4584: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4585: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
 4586: 		    } else {
 4587: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
 4588: 					    $$record{"$where.$partid.tries"});
 4589: 		    }
 4590: 		    my $responseType=($isTask ? 'Task'
 4591:                                               : $responseType->{$partid}->{$responseId});
 4592: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4593: 		    if (!exists($orders{$partid}->{$responseId})) {
 4594: 			$orders{$partid}->{$responseId}=
 4595: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
 4596:                                        $no_increment);
 4597: 		    }
 4598: 		    $displaySub[0].='</b>&nbsp; '.
 4599: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4600: 		}
 4601: 	    }
 4602: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4603: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
 4604: 				    $$record{"$where.$partid.checkedin"},
 4605: 				    $$record{"$where.$partid.checkedin.slot"}).
 4606: 					'<br />';
 4607: 	    }
 4608: 	    if (exists $$record{"$where.$partid.award"}) {
 4609: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
 4610: 		    lc($$record{"$where.$partid.award"}).' '.
 4611: 		    $mark{$$record{"$where.$partid.solved"}}.
 4612: 		    '<br />';
 4613: 	    }
 4614: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4615: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4616: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4617: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4618: 		$displaySub[2].=
 4619: 		    $$record{"$version:resource.$partid.regrader"}.
 4620: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4621: 	    }
 4622: 	}
 4623: 	# needed because old essay regrader has not parts info
 4624: 	if (exists $$record{"$version:resource.regrader"}) {
 4625: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4626: 	}
 4627: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4628: 	if ($displaySub[2]) {
 4629: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
 4630: 	}
 4631: 	$studentTable.='&nbsp;</td>'.
 4632: 	    &Apache::loncommon::end_data_table_row();
 4633:     }
 4634:     $studentTable.=&Apache::loncommon::end_data_table();
 4635:     return $studentTable;
 4636: }
 4637: 
 4638: sub updateGradeByPage {
 4639:     my ($request) = shift;
 4640: 
 4641:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4642:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4643:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4644:     my $pageTitle = $env{'form.page'};
 4645:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4646:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4647:     my $usec=$classlist->{$env{'form.student'}}[5];
 4648:     if (!&canmodify($usec)) {
 4649: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
 4650: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4651: 	return;
 4652:     }
 4653:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4654:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4655: 	'</h3>'."\n";
 4656: 
 4657:     $request->print($result);
 4658: 
 4659:     my $navmap = Apache::lonnavmaps::navmap->new();
 4660:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4661:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4662:     if (!$map) {
 4663: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
 4664: 	my ($symb)=&get_symb($request);
 4665: 	$request->print(&show_grading_menu_form($symb));
 4666: 	return; 
 4667:     }
 4668:     my $iterator = $navmap->getIterator($map->map_start(),
 4669: 					$map->map_finish());
 4670: 
 4671:     my $studentTable=
 4672: 	&Apache::loncommon::start_data_table().
 4673: 	&Apache::loncommon::start_data_table_header_row().
 4674: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
 4675: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
 4676: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
 4677: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
 4678: 	&Apache::loncommon::end_data_table_header_row();
 4679: 
 4680:     $iterator->next(); # skip the first BEGIN_MAP
 4681:     my $curRes = $iterator->next(); # for "current resource"
 4682:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4683:     while ($depth > 0) {
 4684:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4685:         if($curRes == $iterator->END_MAP) { $depth--; }
 4686: 
 4687:         if (ref($curRes) && $curRes->is_problem()) {
 4688: 	    my $parts = $curRes->parts();
 4689:             my $title = $curRes->compTitle();
 4690: 	    my $symbx = $curRes->symb();
 4691: 	    $studentTable.=
 4692: 		&Apache::loncommon::start_data_table_row().
 4693: 		'<td align="center" valign="top" >'.$prob.
 4694: 		(scalar(@{$parts}) == 1 ? '' 
 4695:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
 4696: 		.')').'</td>';
 4697: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4698: 
 4699: 	    my %newrecord=();
 4700: 	    my @displayPts=();
 4701:             my %aggregate = ();
 4702:             my $aggregateflag = 0;
 4703: 	    foreach my $partid (@{$parts}) {
 4704: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4705: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4706: 
 4707: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4708: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4709: 		my $partial = $newpts/$wgt;
 4710: 		my $score;
 4711: 		if ($partial > 0) {
 4712: 		    $score = 'correct_by_override';
 4713: 		} elsif ($newpts ne '') { #empty is taken as 0
 4714: 		    $score = 'incorrect_by_override';
 4715: 		}
 4716: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4717: 		if ($dropMenu eq 'excused') {
 4718: 		    $partial = '';
 4719: 		    $score = 'excused';
 4720: 		} elsif ($dropMenu eq 'reset status'
 4721: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4722: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4723: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4724: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4725: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4726: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4727: 		    $changeflag++;
 4728: 		    $newpts = '';
 4729:                     
 4730:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4731:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4732:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4733:                     if ($aggtries > 0) {
 4734:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4735:                         $aggregateflag = 1;
 4736:                     }
 4737: 		}
 4738: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4739: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4740: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4741: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4742: 		    '&nbsp;<br />';
 4743: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
 4744: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4745: 		    '&nbsp;<br />';
 4746: 		$question++;
 4747: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4748: 
 4749: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4750: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4751: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4752: 		    if (scalar(keys(%newrecord)) > 0);
 4753: 
 4754: 		$changeflag++;
 4755: 	    }
 4756: 	    if (scalar(keys(%newrecord)) > 0) {
 4757: 		my %record = 
 4758: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4759: 					     $udom,$uname);
 4760: 
 4761: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4762: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4763: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4764: 		    $newrecord{'resource.CODE'} = '';
 4765: 		}
 4766: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4767: 					$udom,$uname);
 4768: 		%record = &Apache::lonnet::restore($symbx,
 4769: 						   $env{'request.course.id'},
 4770: 						   $udom,$uname);
 4771: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4772: 					     $cdom,$cnum,$udom,$uname);
 4773: 	    }
 4774: 	    
 4775:             if ($aggregateflag) {
 4776:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4777:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4778:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4779:             }
 4780: 
 4781: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4782: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4783: 		&Apache::loncommon::end_data_table_row();
 4784: 
 4785: 	    $prob++;
 4786: 	}
 4787:         $curRes = $iterator->next();
 4788:     }
 4789: 
 4790:     $studentTable.=&Apache::loncommon::end_data_table();
 4791:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4792:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
 4793: 		  &mt('The scores were changed for [quant,_1,problem].',
 4794: 		  $changeflag));
 4795:     $request->print($grademsg.$studentTable);
 4796: 
 4797:     return '';
 4798: }
 4799: 
 4800: #-------- end of section for handling grading by page/sequence ---------
 4801: #
 4802: #-------------------------------------------------------------------
 4803: 
 4804: #--------------------Scantron Grading-----------------------------------
 4805: #
 4806: #------ start of section for handling grading by page/sequence ---------
 4807: 
 4808: =pod
 4809: 
 4810: =head1 Bubble sheet grading routines
 4811: 
 4812:   For this documentation:
 4813: 
 4814:    'scanline' refers to the full line of characters
 4815:    from the file that we are parsing that represents one entire sheet
 4816: 
 4817:    'bubble line' refers to the data
 4818:    representing the line of bubbles that are on the physical bubble sheet
 4819: 
 4820: 
 4821: The overall process is that a scanned in bubble sheet data is uploaded
 4822: into a course. When a user wants to grade, they select a
 4823: sequence/folder of resources, a file of bubble sheet info, and pick
 4824: one of the predefined configurations for what each scanline looks
 4825: like.
 4826: 
 4827: Next each scanline is checked for any errors of either 'missing
 4828: bubbles' (it's an error because it may have been mis-scanned
 4829: because too light bubbling), 'double bubble' (each bubble line should
 4830: have no more that one letter picked), invalid or duplicated CODE,
 4831: invalid student ID
 4832: 
 4833: If the CODE option is used that determines the randomization of the
 4834: homework problems, either way the student ID is looked up into a
 4835: username:domain.
 4836: 
 4837: During the validation phase the instructor can choose to skip scanlines. 
 4838: 
 4839: After the validation phase, there are now 3 bubble sheet files
 4840: 
 4841:   scantron_original_filename (unmodified original file)
 4842:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4843:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4844: 
 4845: Also there is a separate hash nohist_scantrondata that contains extra
 4846: correction information that isn't representable in the bubble sheet
 4847: file (see &scantron_getfile() for more information)
 4848: 
 4849: After all scanlines are either valid, marked as valid or skipped, then
 4850: foreach line foreach problem in the picked sequence, an ssi request is
 4851: made that simulates a user submitting their selected letter(s) against
 4852: the homework problem.
 4853: 
 4854: =over 4
 4855: 
 4856: 
 4857: 
 4858: =item defaultFormData
 4859: 
 4860:   Returns html hidden inputs used to hold context/default values.
 4861: 
 4862:  Arguments:
 4863:   $symb - $symb of the current resource 
 4864: 
 4865: =cut
 4866: 
 4867: sub defaultFormData {
 4868:     my ($symb)=@_;
 4869:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4870:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4871:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4872: }
 4873: 
 4874: 
 4875: =pod 
 4876: 
 4877: =item getSequenceDropDown
 4878: 
 4879:    Return html dropdown of possible sequences to grade
 4880:  
 4881:  Arguments:
 4882:    $symb - $symb of the current resource 
 4883: 
 4884: =cut
 4885: 
 4886: sub getSequenceDropDown {
 4887:     my ($symb)=@_;
 4888:     my $result='<select name="selectpage">'."\n";
 4889:     my ($titles,$symbx) = &getSymbMap();
 4890:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4891:     my $ctr=0;
 4892:     foreach (@$titles) {
 4893: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4894: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4895: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4896: 	    '>'.$showtitle.'</option>'."\n";
 4897: 	$ctr++;
 4898:     }
 4899:     $result.= '</select>';
 4900:     return $result;
 4901: }
 4902: 
 4903: my %bubble_lines_per_response;     # no. bubble lines for each response.
 4904:                                    # index is "symb.part_id"
 4905: 
 4906: my %first_bubble_line;             # First bubble line no. for each bubble.
 4907: 
 4908: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
 4909:                                    # matchresponse or rankresponse, where 
 4910:                                    # an individual response can have multiple 
 4911:                                    # lines
 4912: 
 4913: my %responsetype_per_response;     # responsetype for each response
 4914: 
 4915: # Save and restore the bubble lines array to the form env.
 4916: 
 4917: 
 4918: sub save_bubble_lines {
 4919:     foreach my $line (keys(%bubble_lines_per_response)) {
 4920: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
 4921: 	$env{"form.scantron.first_bubble_line.$line"} =
 4922: 	    $first_bubble_line{$line};
 4923:         $env{"form.scantron.sub_bubblelines.$line"} = 
 4924:             $subdivided_bubble_lines{$line};
 4925:         $env{"form.scantron.responsetype.$line"} =
 4926:             $responsetype_per_response{$line};
 4927:     }
 4928: }
 4929: 
 4930: 
 4931: sub restore_bubble_lines {
 4932:     my $line = 0;
 4933:     %bubble_lines_per_response = ();
 4934:     while ($env{"form.scantron.bubblelines.$line"}) {
 4935: 	my $value = $env{"form.scantron.bubblelines.$line"};
 4936: 	$bubble_lines_per_response{$line} = $value;
 4937: 	$first_bubble_line{$line}  =
 4938: 	    $env{"form.scantron.first_bubble_line.$line"};
 4939:         $subdivided_bubble_lines{$line} =
 4940:             $env{"form.scantron.sub_bubblelines.$line"};
 4941:         $responsetype_per_response{$line} =
 4942:             $env{"form.scantron.responsetype.$line"};
 4943: 	$line++;
 4944:     }
 4945: 
 4946: }
 4947: 
 4948: #  Given the parsed scanline, get the response for 
 4949: #  'answer' number n:
 4950: 
 4951: sub get_response_bubbles {
 4952:     my ($parsed_line, $response)  = @_;
 4953: 
 4954: 
 4955:     my $bubble_line = $first_bubble_line{$response-1} +1;
 4956:     my $bubble_lines= $bubble_lines_per_response{$response-1};
 4957:     
 4958:     my $selected = "";
 4959: 
 4960:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
 4961: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
 4962: 	$bubble_line++;
 4963:     }
 4964:     return $selected;
 4965: }
 4966: 
 4967: =pod 
 4968: 
 4969: =item scantron_filenames
 4970: 
 4971:    Returns a list of the scantron files in the current course 
 4972: 
 4973: =cut
 4974: 
 4975: sub scantron_filenames {
 4976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4977:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4978:     my $getpropath = 1;
 4979:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4980:                                        $getpropath);
 4981:     my @possiblenames;
 4982:     foreach my $filename (sort(@files)) {
 4983: 	($filename)=split(/&/,$filename);
 4984: 	if ($filename!~/^scantron_orig_/) { next ; }
 4985: 	$filename=~s/^scantron_orig_//;
 4986: 	push(@possiblenames,$filename);
 4987:     }
 4988:     return @possiblenames;
 4989: }
 4990: 
 4991: =pod 
 4992: 
 4993: =item scantron_uploads
 4994: 
 4995:    Returns  html drop-down list of scantron files in current course.
 4996: 
 4997:  Arguments:
 4998:    $file2grade - filename to set as selected in the dropdown
 4999: 
 5000: =cut
 5001: 
 5002: sub scantron_uploads {
 5003:     my ($file2grade) = @_;
 5004:     my $result=	'<select name="scantron_selectfile">';
 5005:     $result.="<option></option>";
 5006:     foreach my $filename (sort(&scantron_filenames())) {
 5007: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 5008:     }
 5009:     $result.="</select>";
 5010:     return $result;
 5011: }
 5012: 
 5013: =pod 
 5014: 
 5015: =item scantron_scantab
 5016: 
 5017:   Returns html drop down of the scantron formats in the scantronformat.tab
 5018:   file.
 5019: 
 5020: =cut
 5021: 
 5022: sub scantron_scantab {
 5023:     my $result='<select name="scantron_format">'."\n";
 5024:     $result.='<option></option>'."\n";
 5025:     my @lines = &get_scantronformat_file();
 5026:     if (@lines > 0) {
 5027:         foreach my $line (@lines) {
 5028:             next if (($line =~ /^\#/) || ($line eq ''));
 5029: 	    my ($name,$descrip)=split(/:/,$line);
 5030: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 5031:         }
 5032:     }
 5033:     $result.='</select>'."\n";
 5034:     return $result;
 5035: }
 5036: 
 5037: =pod
 5038: 
 5039: =item get_scantronformat_file
 5040: 
 5041:   Returns an array containing lines from the scantron format file for
 5042:   the domain of the course.
 5043: 
 5044:   If a url for a custom.tab file is listed in domain's configuration.db, 
 5045:   lines are from this file.
 5046: 
 5047:   Otherwise, if a default.tab has been published in RES space by the 
 5048:   domainconfig user, lines are from this file.
 5049: 
 5050:   Otherwise, fall back to getting lines from the legacy file on the
 5051:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
 5052: 
 5053: =cut
 5054: 
 5055: sub get_scantronformat_file {
 5056:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5057:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
 5058:     my $gottab = 0;
 5059:     my @lines;
 5060:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5061:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5062:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5063:             if ($formatfile ne '-1') {
 5064:                 @lines = split("\n",$formatfile,-1);
 5065:                 $gottab = 1;
 5066:             }
 5067:         }
 5068:     }
 5069:     if (!$gottab) {
 5070:         my $confname = $cdom.'-domainconfig';
 5071:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5072:         my $formatfile =  &Apache::lonnet::getfile($default);
 5073:         if ($formatfile ne '-1') {
 5074:             @lines = split("\n",$formatfile,-1);
 5075:             $gottab = 1;
 5076:         }
 5077:     }
 5078:     if (!$gottab) {
 5079:         my @domains = &Apache::lonnet::current_machine_domains();
 5080:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5081:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 5082:             @lines = <$fh>;
 5083:             close($fh);
 5084:         } else {
 5085:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
 5086:             @lines = <$fh>;
 5087:             close($fh);
 5088:         }
 5089:     }
 5090:     return @lines;
 5091: }
 5092: 
 5093: =pod 
 5094: 
 5095: =item scantron_CODElist
 5096: 
 5097:   Returns html drop down of the saved CODE lists from current course,
 5098:   generated from earlier printings.
 5099: 
 5100: =cut
 5101: 
 5102: sub scantron_CODElist {
 5103:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5104:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5105:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 5106:     my $namechoice='<option></option>';
 5107:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 5108: 	if ($name =~ /^error: 2 /) { next; }
 5109: 	if ($name =~ /^type\0/) { next; }
 5110: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 5111:     }
 5112:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 5113:     return $namechoice;
 5114: }
 5115: 
 5116: =pod 
 5117: 
 5118: =item scantron_CODEunique
 5119: 
 5120:   Returns the html for "Each CODE to be used once" radio.
 5121: 
 5122: =cut
 5123: 
 5124: sub scantron_CODEunique {
 5125:     my $result='<span style="white-space: nowrap;">
 5126:                  <label><input type="radio" name="scantron_CODEunique"
 5127:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 5128:                 </span>
 5129:                 <span style="white-space: nowrap;">
 5130:                  <label><input type="radio" name="scantron_CODEunique"
 5131:                         value="no" />'.&mt('No').' </label>
 5132:                 </span>';
 5133:     return $result;
 5134: }
 5135: 
 5136: =pod 
 5137: 
 5138: =item scantron_selectphase
 5139: 
 5140:   Generates the initial screen to start the bubble sheet process.
 5141:   Allows for - starting a grading run.
 5142:              - downloading existing scan data (original, corrected
 5143:                                                 or skipped info)
 5144: 
 5145:              - uploading new scan data
 5146: 
 5147:  Arguments:
 5148:   $r          - The Apache request object
 5149:   $file2grade - name of the file that contain the scanned data to score
 5150: 
 5151: =cut
 5152: 
 5153: sub scantron_selectphase {
 5154:     my ($r,$file2grade) = @_;
 5155:     my ($symb)=&get_symb($r);
 5156:     if (!$symb) {return '';}
 5157:     my $sequence_selector=&getSequenceDropDown($symb);
 5158:     my $default_form_data=&defaultFormData($symb);
 5159:     my $grading_menu_button=&show_grading_menu_form($symb);
 5160:     my $file_selector=&scantron_uploads($file2grade);
 5161:     my $format_selector=&scantron_scantab();
 5162:     my $CODE_selector=&scantron_CODElist();
 5163:     my $CODE_unique=&scantron_CODEunique();
 5164:     my $result;
 5165: 
 5166:     $ssi_error = 0;
 5167: 
 5168:     # Chunk of form to prompt for a file to grade and how:
 5169: 
 5170:     $result.= '
 5171:     <br />
 5172:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 5173:     <input type="hidden" name="command" value="scantron_warning" />
 5174:     '.$default_form_data.'
 5175:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5176:        '.&Apache::loncommon::start_data_table_header_row().'
 5177:             <th colspan="2">
 5178:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
 5179:             </th>
 5180:        '.&Apache::loncommon::end_data_table_header_row().'
 5181:        '.&Apache::loncommon::start_data_table_row().'
 5182:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
 5183:        '.&Apache::loncommon::end_data_table_row().'
 5184:        '.&Apache::loncommon::start_data_table_row().'
 5185:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
 5186:        '.&Apache::loncommon::end_data_table_row().'
 5187:        '.&Apache::loncommon::start_data_table_row().'
 5188:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
 5189:        '.&Apache::loncommon::end_data_table_row().'
 5190:        '.&Apache::loncommon::start_data_table_row().'
 5191:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
 5192:        '.&Apache::loncommon::end_data_table_row().'
 5193:        '.&Apache::loncommon::start_data_table_row().'
 5194:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
 5195:        '.&Apache::loncommon::end_data_table_row().'
 5196:        '.&Apache::loncommon::start_data_table_row().'
 5197: 	    <td> '.&mt('Options:').' </td>
 5198:             <td>
 5199: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
 5200:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
 5201:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
 5202: 	    </td>
 5203:        '.&Apache::loncommon::end_data_table_row().'
 5204:        '.&Apache::loncommon::start_data_table_row().'
 5205:             <td colspan="2">
 5206:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
 5207:             </td>
 5208:        '.&Apache::loncommon::end_data_table_row().'
 5209:     '.&Apache::loncommon::end_data_table().'
 5210:     </form>
 5211: ';
 5212:    
 5213:     $r->print($result);
 5214: 
 5215:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 5216:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5217: 
 5218: 	# Chunk of form to prompt for a scantron file upload.
 5219: 
 5220:         $r->print('
 5221:     <br />
 5222:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5223:        '.&Apache::loncommon::start_data_table_header_row().'
 5224:             <th>
 5225:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
 5226:             </th>
 5227:        '.&Apache::loncommon::end_data_table_header_row().'
 5228:        '.&Apache::loncommon::start_data_table_row().'
 5229:             <td>
 5230: ');
 5231:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 5232:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5233:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 5234:     $r->print('
 5235:               <script type="text/javascript" language="javascript">
 5236:     function checkUpload(formname) {
 5237: 	if (formname.upfile.value == "") {
 5238: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
 5239: 	    return false;
 5240: 	}
 5241: 	formname.submit();
 5242:     }
 5243:               </script>
 5244: 
 5245:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 5246:                 '.$default_form_data.'
 5247:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
 5248:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
 5249:                 <input name="command" value="scantronupload_save" type="hidden" />
 5250:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
 5251:                 <br />
 5252:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 5253:               </form>
 5254: ');
 5255: 
 5256:         $r->print('
 5257:             </td>
 5258:        '.&Apache::loncommon::end_data_table_row().'
 5259:        '.&Apache::loncommon::end_data_table().'
 5260: ');
 5261:     }
 5262: 
 5263:     # Chunk of the form that prompts to view a scoring office file,
 5264:     # corrected file, skipped records in a file.
 5265: 
 5266:     $r->print('
 5267:    <br />
 5268:    <form action="/adm/grades" name="scantron_download">
 5269:      '.$default_form_data.'
 5270:      <input type="hidden" name="command" value="scantron_download" />
 5271:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
 5272:        '.&Apache::loncommon::start_data_table_header_row().'
 5273:               <th>
 5274:                 &nbsp;'.&mt('Download a scoring office file').'
 5275:               </th>
 5276:        '.&Apache::loncommon::end_data_table_header_row().'
 5277:        '.&Apache::loncommon::start_data_table_row().'
 5278:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
 5279:                 <br />
 5280:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
 5281:        '.&Apache::loncommon::end_data_table_row().'
 5282:      '.&Apache::loncommon::end_data_table().'
 5283:    </form>
 5284:    <br />
 5285: ');
 5286: 
 5287:     &Apache::lonpickcode::code_list($r,2);
 5288: 
 5289:     $r->print('<br /><form method="post" name="checkscantron">'.
 5290:              $default_form_data."\n".
 5291:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
 5292:              &Apache::loncommon::start_data_table_header_row()."\n".
 5293:              '<th colspan="2">
 5294:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
 5295:              '</th>'."\n".
 5296:               &Apache::loncommon::end_data_table_header_row()."\n".
 5297:               &Apache::loncommon::start_data_table_row()."\n".
 5298:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
 5299:               '<td> '.$sequence_selector.' </td>'.
 5300:               &Apache::loncommon::end_data_table_row()."\n".
 5301:               &Apache::loncommon::start_data_table_row()."\n".
 5302:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
 5303:               '<td> '.$file_selector.' </td>'."\n".
 5304:               &Apache::loncommon::end_data_table_row()."\n".
 5305:               &Apache::loncommon::start_data_table_row()."\n".
 5306:               '<td> '.&mt('Format of data file:').' </td>'."\n".
 5307:               '<td> '.$format_selector.' </td>'."\n".
 5308:               &Apache::loncommon::end_data_table_row()."\n".
 5309:               &Apache::loncommon::start_data_table_row()."\n".
 5310:               '<td colspan="2">'."\n".
 5311:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
 5312:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
 5313:               '</td>'."\n".
 5314:               &Apache::loncommon::end_data_table_row()."\n".
 5315:               &Apache::loncommon::end_data_table()."\n".
 5316:               '</form><br />');
 5317:     $r->print($grading_menu_button);
 5318:     return;
 5319: }
 5320: 
 5321: =pod
 5322: 
 5323: =item get_scantron_config
 5324: 
 5325:    Parse and return the scantron configuration line selected as a
 5326:    hash of configuration file fields.
 5327: 
 5328:  Arguments:
 5329:     which - the name of the configuration to parse from the file.
 5330: 
 5331: 
 5332:  Returns:
 5333:             If the named configuration is not in the file, an empty
 5334:             hash is returned.
 5335:     a hash with the fields
 5336:       name         - internal name for the this configuration setup
 5337:       description  - text to display to operator that describes this config
 5338:       CODElocation - if 0 or the string 'none'
 5339:                           - no CODE exists for this config
 5340:                      if -1 || the string 'letter'
 5341:                           - a CODE exists for this config and is
 5342:                             a string of letters
 5343:                      Unsupported value (but planned for future support)
 5344:                           if a positive integer
 5345:                                - The CODE exists as the first n items from
 5346:                                  the question section of the form
 5347:                           if the string 'number'
 5348:                                - The CODE exists for this config and is
 5349:                                  a string of numbers
 5350:       CODEstart   - (only matter if a CODE exists) column in the line where
 5351:                      the CODE starts
 5352:       CODElength  - length of the CODE
 5353:       IDstart     - column where the student ID number starts
 5354:       IDlength    - length of the student ID info
 5355:       Qstart      - column where the information from the bubbled
 5356:                     'questions' start
 5357:       Qlength     - number of columns comprising a single bubble line from
 5358:                     the sheet. (usually either 1 or 10)
 5359:       Qon         - either a single character representing the character used
 5360:                     to signal a bubble was chosen in the positional setup, or
 5361:                     the string 'letter' if the letter of the chosen bubble is
 5362:                     in the final, or 'number' if a number representing the
 5363:                     chosen bubble is in the file (1->A 0->J)
 5364:       Qoff        - the character used to represent that a bubble was
 5365:                     left blank
 5366:       PaperID     - if the scanning process generates a unique number for each
 5367:                     sheet scanned the column that this ID number starts in
 5368:       PaperIDlength - number of columns that comprise the unique ID number
 5369:                       for the sheet of paper
 5370:       FirstName   - column that the first name starts in
 5371:       FirstNameLength - number of columns that the first name spans
 5372:  
 5373:       LastName    - column that the last name starts in
 5374:       LastNameLength - number of columns that the last name spans
 5375: 
 5376: =cut
 5377: 
 5378: sub get_scantron_config {
 5379:     my ($which) = @_;
 5380:     my @lines = &get_scantronformat_file();
 5381:     my %config;
 5382:     #FIXME probably should move to XML it has already gotten a bit much now
 5383:     foreach my $line (@lines) {
 5384: 	my ($name,$descrip)=split(/:/,$line);
 5385: 	if ($name ne $which ) { next; }
 5386: 	chomp($line);
 5387: 	my @config=split(/:/,$line);
 5388: 	$config{'name'}=$config[0];
 5389: 	$config{'description'}=$config[1];
 5390: 	$config{'CODElocation'}=$config[2];
 5391: 	$config{'CODEstart'}=$config[3];
 5392: 	$config{'CODElength'}=$config[4];
 5393: 	$config{'IDstart'}=$config[5];
 5394: 	$config{'IDlength'}=$config[6];
 5395: 	$config{'Qstart'}=$config[7];
 5396:  	$config{'Qlength'}=$config[8];
 5397: 	$config{'Qoff'}=$config[9];
 5398: 	$config{'Qon'}=$config[10];
 5399: 	$config{'PaperID'}=$config[11];
 5400: 	$config{'PaperIDlength'}=$config[12];
 5401: 	$config{'FirstName'}=$config[13];
 5402: 	$config{'FirstNamelength'}=$config[14];
 5403: 	$config{'LastName'}=$config[15];
 5404: 	$config{'LastNamelength'}=$config[16];
 5405: 	last;
 5406:     }
 5407:     return %config;
 5408: }
 5409: 
 5410: =pod 
 5411: 
 5412: =item username_to_idmap
 5413: 
 5414:     creates a hash keyed by student id with values of the corresponding
 5415:     student username:domain.
 5416: 
 5417:   Arguments:
 5418: 
 5419:     $classlist - reference to the class list hash. This is a hash
 5420:                  keyed by student name:domain  whose elements are references
 5421:                  to arrays containing various chunks of information
 5422:                  about the student. (See loncoursedata for more info).
 5423: 
 5424:   Returns
 5425:     %idmap - the constructed hash
 5426: 
 5427: =cut
 5428: 
 5429: sub username_to_idmap {
 5430:     my ($classlist)= @_;
 5431:     my %idmap;
 5432:     foreach my $student (keys(%$classlist)) {
 5433: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5434: 	    $student;
 5435:     }
 5436:     return %idmap;
 5437: }
 5438: 
 5439: =pod
 5440: 
 5441: =item scantron_fixup_scanline
 5442: 
 5443:    Process a requested correction to a scanline.
 5444: 
 5445:   Arguments:
 5446:     $scantron_config   - hash from &get_scantron_config()
 5447:     $scan_data         - hash of correction information 
 5448:                           (see &scantron_getfile())
 5449:     $line              - existing scanline
 5450:     $whichline         - line number of the passed in scanline
 5451:     $field             - type of change to process 
 5452:                          (either 
 5453:                           'ID'     -> correct the student ID number
 5454:                           'CODE'   -> correct the CODE
 5455:                           'answer' -> fixup the submitted answers)
 5456:     
 5457:    $args               - hash of additional info,
 5458:                           - 'ID' 
 5459:                                'newid' -> studentID to use in replacement
 5460:                                           of existing one
 5461:                           - 'CODE' 
 5462:                                'CODE_ignore_dup' - set to true if duplicates
 5463:                                                    should be ignored.
 5464: 	                       'CODE' - is new code or 'use_unfound'
 5465:                                         if the existing unfound code should
 5466:                                         be used as is
 5467:                           - 'answer'
 5468:                                'response' - new answer or 'none' if blank
 5469:                                'question' - the bubble line to change
 5470:                                'questionnum' - the question identifier,
 5471:                                                may include subquestion. 
 5472: 
 5473:   Returns:
 5474:     $line - the modified scanline
 5475: 
 5476:   Side effects: 
 5477:     $scan_data - may be updated
 5478: 
 5479: =cut
 5480: 
 5481: 
 5482: sub scantron_fixup_scanline {
 5483:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5484:     if ($field eq 'ID') {
 5485: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5486: 	    return ($line,1,'New value too large');
 5487: 	}
 5488: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5489: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5490: 				     $args->{'newid'});
 5491: 	}
 5492: 	substr($line,$$scantron_config{'IDstart'}-1,
 5493: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5494: 	if ($args->{'newid'}=~/^\s*$/) {
 5495: 	    &scan_data($scan_data,"$whichline.user",
 5496: 		       $args->{'username'}.':'.$args->{'domain'});
 5497: 	}
 5498:     } elsif ($field eq 'CODE') {
 5499: 	if ($args->{'CODE_ignore_dup'}) {
 5500: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5501: 	}
 5502: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5503: 	if ($args->{'CODE'} ne 'use_unfound') {
 5504: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5505: 		return ($line,1,'New CODE value too large');
 5506: 	    }
 5507: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5508: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5509: 	    }
 5510: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5511: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5512: 	}
 5513:     } elsif ($field eq 'answer') {
 5514: 	my $length=$scantron_config->{'Qlength'};
 5515: 	my $off=$scantron_config->{'Qoff'};
 5516: 	my $on=$scantron_config->{'Qon'};
 5517: 	my $answer=${off}x$length;
 5518: 	if ($args->{'response'} eq 'none') {
 5519: 	    &scan_data($scan_data,
 5520: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
 5521: 	} else {
 5522: 	    if ($on eq 'letter') {
 5523: 		my @alphabet=('A'..'Z');
 5524: 		$answer=$alphabet[$args->{'response'}];
 5525: 	    } elsif ($on eq 'number') {
 5526: 		$answer=$args->{'response'}+1;
 5527: 		if ($answer == 10) { $answer = '0'; }
 5528: 	    } else {
 5529: 		substr($answer,$args->{'response'},1)=$on;
 5530: 	    }
 5531: 	    &scan_data($scan_data,
 5532: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
 5533: 	}
 5534: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5535: 	substr($line,$where-1,$length)=$answer;
 5536:     }
 5537:     return $line;
 5538: }
 5539: 
 5540: =pod
 5541: 
 5542: =item scan_data
 5543: 
 5544:     Edit or look up  an item in the scan_data hash.
 5545: 
 5546:   Arguments:
 5547:     $scan_data  - The hash (see scantron_getfile)
 5548:     $key        - shorthand of the key to edit (actual key is
 5549:                   scantronfilename_key).
 5550:     $data        - New value of the hash entry.
 5551:     $delete      - If true, the entry is removed from the hash.
 5552: 
 5553:   Returns:
 5554:     The new value of the hash table field (undefined if deleted).
 5555: 
 5556: =cut
 5557: 
 5558: 
 5559: sub scan_data {
 5560:     my ($scan_data,$key,$value,$delete)=@_;
 5561:     my $filename=$env{'form.scantron_selectfile'};
 5562:     if (defined($value)) {
 5563: 	$scan_data->{$filename.'_'.$key} = $value;
 5564:     }
 5565:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5566:     return $scan_data->{$filename.'_'.$key};
 5567: }
 5568: 
 5569: # ----- These first few routines are general use routines.----
 5570: 
 5571: # Return the number of occurences of a pattern in a string.
 5572: 
 5573: sub occurence_count {
 5574:     my ($string, $pattern) = @_;
 5575: 
 5576:     my @matches = ($string =~ /$pattern/g);
 5577: 
 5578:     return scalar(@matches);
 5579: }
 5580: 
 5581: 
 5582: # Take a string known to have digits and convert all the
 5583: # digits into letters in the range J,A..I.
 5584: 
 5585: sub digits_to_letters {
 5586:     my ($input) = @_;
 5587: 
 5588:     my @alphabet = ('J', 'A'..'I');
 5589: 
 5590:     my @input    = split(//, $input);
 5591:     my $output ='';
 5592:     for (my $i = 0; $i < scalar(@input); $i++) {
 5593: 	if ($input[$i] =~ /\d/) {
 5594: 	    $output .= $alphabet[$input[$i]];
 5595: 	} else {
 5596: 	    $output .= $input[$i];
 5597: 	}
 5598:     }
 5599:     return $output;
 5600: }
 5601: 
 5602: =pod 
 5603: 
 5604: =item scantron_parse_scanline
 5605: 
 5606:   Decodes a scanline from the selected scantron file
 5607: 
 5608:  Arguments:
 5609:     line             - The text of the scantron file line to process
 5610:     whichline        - Line number
 5611:     scantron_config  - Hash describing the format of the scantron lines.
 5612:     scan_data        - Hash of extra information about the scanline
 5613:                        (see scantron_getfile for more information)
 5614:     just_header      - True if should not process question answers but only
 5615:                        the stuff to the left of the answers.
 5616:  Returns:
 5617:    Hash containing the result of parsing the scanline
 5618: 
 5619:    Keys are all proceeded by the string 'scantron.'
 5620: 
 5621:        CODE    - the CODE in use for this scanline
 5622:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5623:                  by the operator
 5624:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5625:                             CODEs were selected, but the usage has been
 5626:                             forced by the operator
 5627:        ID  - student ID
 5628:        PaperID - if used, the ID number printed on the sheet when the 
 5629:                  paper was scanned
 5630:        FirstName - first name from the sheet
 5631:        LastName  - last name from the sheet
 5632: 
 5633:      if just_header was not true these key may also exist
 5634: 
 5635:        missingerror - a list of bubble ranges that are considered to be answers
 5636:                       to a single question that don't have any bubbles filled in.
 5637:                       Of the form questionnumber:firstbubblenumber:count.
 5638:        doubleerror  - a list of bubble ranges that are considered to be answers
 5639:                       to a single question that have more than one bubble filled in.
 5640:                       Of the form questionnumber::firstbubblenumber:count
 5641:    
 5642:                 In the above, count is the number of bubble responses in the
 5643:                 input line needed to represent the possible answers to the question.
 5644:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5645:                 per line would have count = 2.
 5646: 
 5647:        maxquest     - the number of the last bubble line that was parsed
 5648: 
 5649:        (<number> starts at 1)
 5650:        <number>.answer - zero or more letters representing the selected
 5651:                          letters from the scanline for the bubble line 
 5652:                          <number>.
 5653:                          if blank there was either no bubble or there where
 5654:                          multiple bubbles, (consult the keys missingerror and
 5655:                          doubleerror if this is an error condition)
 5656: 
 5657: =cut
 5658: 
 5659: sub scantron_parse_scanline {
 5660:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5661: 
 5662:     my %record;
 5663:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5664:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5665:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5666: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5667: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5668: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5669: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5670: 	    $record{'scantron.CODE'}=substr($data,
 5671: 					    $$scantron_config{'CODEstart'}-1,
 5672: 					    $$scantron_config{'CODElength'});
 5673: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5674: 		$record{'scantron.useCODE'}=1;
 5675: 	    }
 5676: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5677: 		$record{'scantron.CODE_ignore_dup'}=1;
 5678: 	    }
 5679: 	} else {
 5680: 	    #FIXME interpret first N questions
 5681: 	}
 5682:     }
 5683:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5684: 				  $$scantron_config{'IDlength'});
 5685:     $record{'scantron.PaperID'}=
 5686: 	substr($data,$$scantron_config{'PaperID'}-1,
 5687: 	       $$scantron_config{'PaperIDlength'});
 5688:     $record{'scantron.FirstName'}=
 5689: 	substr($data,$$scantron_config{'FirstName'}-1,
 5690: 	       $$scantron_config{'FirstNamelength'});
 5691:     $record{'scantron.LastName'}=
 5692: 	substr($data,$$scantron_config{'LastName'}-1,
 5693: 	       $$scantron_config{'LastNamelength'});
 5694:     if ($just_header) { return \%record; }
 5695: 
 5696:     my @alphabet=('A'..'Z');
 5697:     my $questnum=0;
 5698:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5699: 
 5700:     chomp($questions);		# Get rid of any trailing \n.
 5701:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
 5702:     while (length($questions)) {
 5703: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5704:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
 5705:                              || 1;
 5706:         $questnum++;
 5707:         my $quest_id = $questnum;
 5708:         my $currentquest = substr($questions,0,$answer_length);
 5709:         $questions       = substr($questions,$answer_length);
 5710:         if (length($currentquest) < $answer_length) { next; }
 5711: 
 5712:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
 5713:             my $subquestnum = 1;
 5714:             my $subquestions = $currentquest;
 5715:             my @subanswers_needed = 
 5716:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
 5717:             foreach my $subans (@subanswers_needed) {
 5718:                 my $subans_length =
 5719:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
 5720:                 my $currsubquest = substr($subquestions,0,$subans_length);
 5721:                 $subquestions   = substr($subquestions,$subans_length);
 5722:                 $quest_id = "$questnum.$subquestnum";
 5723:                 if (($$scantron_config{'Qon'} eq 'letter') ||
 5724:                     ($$scantron_config{'Qon'} eq 'number')) {
 5725:                     $ansnum = &scantron_validator_lettnum($ansnum, 
 5726:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
 5727:                         \@alphabet,\%record,$scantron_config,$scan_data);
 5728:                 } else {
 5729:                     $ansnum = &scantron_validator_positional($ansnum,
 5730:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
 5731:                 }
 5732:                 $subquestnum ++;
 5733:             }
 5734:         } else {
 5735:             if (($$scantron_config{'Qon'} eq 'letter') ||
 5736:                 ($$scantron_config{'Qon'} eq 'number')) {
 5737:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
 5738:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5739:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5740:             } else {
 5741:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
 5742:                     $quest_id,$answers_needed,$currentquest,$whichline,
 5743:                     \@alphabet,\%record,$scantron_config,$scan_data);
 5744:             }
 5745:         }
 5746:     }
 5747:     $record{'scantron.maxquest'}=$questnum;
 5748:     return \%record;
 5749: }
 5750: 
 5751: sub scantron_validator_lettnum {
 5752:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
 5753:         $alphabet,$record,$scantron_config,$scan_data) = @_;
 5754: 
 5755:     # Qon 'letter' implies for each slot in currquest we have:
 5756:     #    ? or * for doubles, a letter in A-Z for a bubble, and
 5757:     #    about anything else (esp. a value of Qoff) for missing
 5758:     #    bubbles.
 5759:     #
 5760:     # Qon 'number' implies each slot gives a digit that indexes the
 5761:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
 5762:     #    and * or ? for double bubbles on a single line.
 5763:     #
 5764: 
 5765:     my $matchon;
 5766:     if ($$scantron_config{'Qon'} eq 'letter') {
 5767:         $matchon = '[A-Z]';
 5768:     } elsif ($$scantron_config{'Qon'} eq 'number') {
 5769:         $matchon = '\d';
 5770:     }
 5771:     my $occurrences = 0;
 5772:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5773:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5774:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5775:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5776:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5777:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5778:         my @singlelines = split('',$currquest);
 5779:         foreach my $entry (@singlelines) {
 5780:             $occurrences = &occurence_count($entry,$matchon);
 5781:             if ($occurrences > 1) {
 5782:                 last;
 5783:             }
 5784:         } 
 5785:     } else {
 5786:         $occurrences = &occurence_count($currquest,$matchon); 
 5787:     }
 5788:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
 5789:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5790:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5791:             my $bubble = substr($currquest,$ans,1);
 5792:             if ($bubble =~ /$matchon/ ) {
 5793:                 if ($$scantron_config{'Qon'} eq 'number') {
 5794:                     if ($bubble == 0) {
 5795:                         $bubble = 10; 
 5796:                     }
 5797:                     $record->{"scantron.$ansnum.answer"} = 
 5798:                         $alphabet->[$bubble-1];
 5799:                 } else {
 5800:                     $record->{"scantron.$ansnum.answer"} = $bubble;
 5801:                 }
 5802:             } else {
 5803:                 $record->{"scantron.$ansnum.answer"}='';
 5804:             }
 5805:             $ansnum++;
 5806:         }
 5807:     } elsif (!defined($currquest)
 5808:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
 5809:             || (&occurence_count($currquest,$matchon) == 0)) {
 5810:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5811:             $record->{"scantron.$ansnum.answer"}='';
 5812:             $ansnum++;
 5813:         }
 5814:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5815:             push(@{$record->{'scantron.missingerror'}},$quest_id);
 5816:         }
 5817:     } else {
 5818:         if ($$scantron_config{'Qon'} eq 'number') {
 5819:             $currquest = &digits_to_letters($currquest);            
 5820:         }
 5821:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5822:             my $bubble = substr($currquest,$ans,1);
 5823:             $record->{"scantron.$ansnum.answer"} = $bubble;
 5824:             $ansnum++;
 5825:         }
 5826:     }
 5827:     return $ansnum;
 5828: }
 5829: 
 5830: sub scantron_validator_positional {
 5831:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
 5832:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
 5833: 
 5834:     # Otherwise there's a positional notation;
 5835:     # each bubble line requires Qlength items, and there are filled in
 5836:     # bubbles for each case where there 'Qon' characters.
 5837:     #
 5838: 
 5839:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
 5840: 
 5841:     # If the split only gives us one element.. the full length of the
 5842:     # answer string, no bubbles are filled in:
 5843: 
 5844:     if ($answers_needed eq '') {
 5845:         return;
 5846:     }
 5847: 
 5848:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5849:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
 5850:             $record->{"scantron.$ansnum.answer"}='';
 5851:             $ansnum++;
 5852:         }
 5853:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
 5854:             push(@{$record->{"scantron.missingerror"}},$quest_id);
 5855:         }
 5856:     } elsif (scalar(@array) == 2) {
 5857:         my $location = length($array[0]);
 5858:         my $line_num = int($location / $$scantron_config{'Qlength'});
 5859:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
 5860:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5861:             if ($ans eq $line_num) {
 5862:                 $record->{"scantron.$ansnum.answer"} = $bubble;
 5863:             } else {
 5864:                 $record->{"scantron.$ansnum.answer"} = ' ';
 5865:             }
 5866:             $ansnum++;
 5867:          }
 5868:     } else {
 5869:         #  If there's more than one instance of a bubble character
 5870:         #  That's a double bubble; with positional notation we can
 5871:         #  record all the bubbles filled in as well as the
 5872:         #  fact this response consists of multiple bubbles.
 5873:         #
 5874:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
 5875:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
 5876:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
 5877:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
 5878:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
 5879:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
 5880:             my $doubleerror = 0;
 5881:             while (($currquest >= $$scantron_config{'Qlength'}) && 
 5882:                    (!$doubleerror)) {
 5883:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
 5884:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
 5885:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
 5886:                if (length(@currarray) > 2) {
 5887:                    $doubleerror = 1;
 5888:                } 
 5889:             }
 5890:             if ($doubleerror) {
 5891:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5892:             }
 5893:         } else {
 5894:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
 5895:         }
 5896:         my $item = $ansnum;
 5897:         for (my $ans=0; $ans<$answers_needed; $ans++) {
 5898:             $record->{"scantron.$item.answer"} = '';
 5899:             $item ++;
 5900:         }
 5901: 
 5902:         my @ans=@array;
 5903:         my $i=0;
 5904:         my $increment = 0;
 5905:         while ($#ans) {
 5906:             $i+=length($ans[0]) + $increment;
 5907:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
 5908:             my $bubble = $i%$$scantron_config{'Qlength'};
 5909:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
 5910:             shift(@ans);
 5911:             $increment = 1;
 5912:         }
 5913:         $ansnum += $answers_needed;
 5914:     }
 5915:     return $ansnum;
 5916: }
 5917: 
 5918: =pod
 5919: 
 5920: =item scantron_add_delay
 5921: 
 5922:    Adds an error message that occurred during the grading phase to a
 5923:    queue of messages to be shown after grading pass is complete
 5924: 
 5925:  Arguments:
 5926:    $delayqueue  - arrary ref of hash ref of error messages
 5927:    $scanline    - the scanline that caused the error
 5928:    $errormesage - the error message
 5929:    $errorcode   - a numeric code for the error
 5930: 
 5931:  Side Effects:
 5932:    updates the $delayqueue to have a new hash ref of the error
 5933: 
 5934: =cut
 5935: 
 5936: sub scantron_add_delay {
 5937:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5938:     push(@$delayqueue,
 5939: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5940: 	  'ecode' => $errorcode }
 5941: 	 );
 5942: }
 5943: 
 5944: =pod
 5945: 
 5946: =item scantron_find_student
 5947: 
 5948:    Finds the username for the current scanline
 5949: 
 5950:   Arguments:
 5951:    $scantron_record - hash result from scantron_parse_scanline
 5952:    $scan_data       - hash of correction information 
 5953:                       (see &scantron_getfile() form more information)
 5954:    $idmap           - hash from &username_to_idmap()
 5955:    $line            - number of current scanline
 5956:  
 5957:   Returns:
 5958:    Either 'username:domain' or undef if unknown
 5959: 
 5960: =cut
 5961: 
 5962: sub scantron_find_student {
 5963:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5964:     my $scanID=$$scantron_record{'scantron.ID'};
 5965:     if ($scanID =~ /^\s*$/) {
 5966:  	return &scan_data($scan_data,"$line.user");
 5967:     }
 5968:     foreach my $id (keys(%$idmap)) {
 5969:  	if (lc($id) eq lc($scanID)) {
 5970:  	    return $$idmap{$id};
 5971:  	}
 5972:     }
 5973:     return undef;
 5974: }
 5975: 
 5976: =pod
 5977: 
 5978: =item scantron_filter
 5979: 
 5980:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5981:    hidden resources was selected
 5982: 
 5983: =cut
 5984: 
 5985: sub scantron_filter {
 5986:     my ($curres)=@_;
 5987: 
 5988:     if (ref($curres) && $curres->is_problem()) {
 5989: 	# if the user has asked to not have either hidden
 5990: 	# or 'randomout' controlled resources to be graded
 5991: 	# don't include them
 5992: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5993: 	    && $curres->randomout) {
 5994: 	    return 0;
 5995: 	}
 5996: 	return 1;
 5997:     }
 5998:     return 0;
 5999: }
 6000: 
 6001: =pod
 6002: 
 6003: =item scantron_process_corrections
 6004: 
 6005:    Gets correction information out of submitted form data and corrects
 6006:    the scanline
 6007: 
 6008: =cut
 6009: 
 6010: sub scantron_process_corrections {
 6011:     my ($r) = @_;
 6012:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6013:     my ($scanlines,$scan_data)=&scantron_getfile();
 6014:     my $classlist=&Apache::loncoursedata::get_classlist();
 6015:     my $which=$env{'form.scantron_line'};
 6016:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 6017:     my ($skip,$err,$errmsg);
 6018:     if ($env{'form.scantron_skip_record'}) {
 6019: 	$skip=1;
 6020:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 6021: 	my $newstudent=$env{'form.scantron_username'}.':'.
 6022: 	    $env{'form.scantron_domain'};
 6023: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 6024: 	($line,$err,$errmsg)=
 6025: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6026: 				     'ID',{'newid'=>$newid,
 6027: 				    'username'=>$env{'form.scantron_username'},
 6028: 				    'domain'=>$env{'form.scantron_domain'}});
 6029:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 6030: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 6031: 	my $newCODE;
 6032: 	my %args;
 6033: 	if      ($resolution eq 'use_unfound') {
 6034: 	    $newCODE='use_unfound';
 6035: 	} elsif ($resolution eq 'use_found') {
 6036: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 6037: 	} elsif ($resolution eq 'use_typed') {
 6038: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 6039: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 6040: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 6041: 	}
 6042: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 6043: 	    $args{'CODE_ignore_dup'}=1;
 6044: 	}
 6045: 	$args{'CODE'}=$newCODE;
 6046: 	($line,$err,$errmsg)=
 6047: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 6048: 				     'CODE',\%args);
 6049:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 6050: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 6051: 	    ($line,$err,$errmsg)=
 6052: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 6053: 					 $which,'answer',
 6054: 					 { 'question'=>$question,
 6055: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
 6056:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
 6057: 	    if ($err) { last; }
 6058: 	}
 6059:     }
 6060:     if ($err) {
 6061: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 6062:     } else {
 6063: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 6064: 	&scantron_putfile($scanlines,$scan_data);
 6065:     }
 6066: }
 6067: 
 6068: =pod
 6069: 
 6070: =item reset_skipping_status
 6071: 
 6072:    Forgets the current set of remember skipped scanlines (and thus
 6073:    reverts back to considering all lines in the
 6074:    scantron_skipped_<filename> file)
 6075: 
 6076: =cut
 6077: 
 6078: sub reset_skipping_status {
 6079:     my ($scanlines,$scan_data)=&scantron_getfile();
 6080:     &scan_data($scan_data,'remember_skipping',undef,1);
 6081:     &scantron_putfile(undef,$scan_data);
 6082: }
 6083: 
 6084: =pod
 6085: 
 6086: =item start_skipping
 6087: 
 6088:    Marks a scanline to be skipped. 
 6089: 
 6090: =cut
 6091: 
 6092: sub start_skipping {
 6093:     my ($scan_data,$i)=@_;
 6094:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6095:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 6096: 	$remembered{$i}=2;
 6097:     } else {
 6098: 	$remembered{$i}=1;
 6099:     }
 6100:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 6101: }
 6102: 
 6103: =pod
 6104: 
 6105: =item should_be_skipped
 6106: 
 6107:    Checks whether a scanline should be skipped.
 6108: 
 6109: =cut
 6110: 
 6111: sub should_be_skipped {
 6112:     my ($scanlines,$scan_data,$i)=@_;
 6113:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 6114: 	# not redoing old skips
 6115: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 6116: 	return 0;
 6117:     }
 6118:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 6119: 
 6120:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 6121: 	return 0;
 6122:     }
 6123:     return 1;
 6124: }
 6125: 
 6126: =pod
 6127: 
 6128: =item remember_current_skipped
 6129: 
 6130:    Discovers what scanlines are in the scantron_skipped_<filename>
 6131:    file and remembers them into scan_data for later use.
 6132: 
 6133: =cut
 6134: 
 6135: sub remember_current_skipped {
 6136:     my ($scanlines,$scan_data)=&scantron_getfile();
 6137:     my %to_remember;
 6138:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6139: 	if ($scanlines->{'skipped'}[$i]) {
 6140: 	    $to_remember{$i}=1;
 6141: 	}
 6142:     }
 6143: 
 6144:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 6145:     &scantron_putfile(undef,$scan_data);
 6146: }
 6147: 
 6148: =pod
 6149: 
 6150: =item check_for_error
 6151: 
 6152:     Checks if there was an error when attempting to remove a specific
 6153:     scantron_.. bubble sheet data file. Prints out an error if
 6154:     something went wrong.
 6155: 
 6156: =cut
 6157: 
 6158: sub check_for_error {
 6159:     my ($r,$result)=@_;
 6160:     if ($result ne 'ok' && $result ne 'not_found' ) {
 6161: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
 6162:     }
 6163: }
 6164: 
 6165: =pod
 6166: 
 6167: =item scantron_warning_screen
 6168: 
 6169:    Interstitial screen to make sure the operator has selected the
 6170:    correct options before we start the validation phase.
 6171: 
 6172: =cut
 6173: 
 6174: sub scantron_warning_screen {
 6175:     my ($button_text)=@_;
 6176:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 6177:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6178:     my $CODElist;
 6179:     if ($scantron_config{'CODElocation'} &&
 6180: 	$scantron_config{'CODEstart'} &&
 6181: 	$scantron_config{'CODElength'}) {
 6182: 	$CODElist=$env{'form.scantron_CODElist'};
 6183: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 6184: 	$CODElist=
 6185: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
 6186: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 6187:     }
 6188:     return ('
 6189: <p>
 6190: <span class="LC_warning">
 6191: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
 6192: </p>
 6193: <table>
 6194: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
 6195: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
 6196: '.$CODElist.'
 6197: </table>
 6198: <br />
 6199: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
 6200: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
 6201: 
 6202: <br />
 6203: ');
 6204: }
 6205: 
 6206: =pod
 6207: 
 6208: =item scantron_do_warning
 6209: 
 6210:    Check if the operator has picked something for all required
 6211:    fields. Error out if something is missing.
 6212: 
 6213: =cut
 6214: 
 6215: sub scantron_do_warning {
 6216:     my ($r)=@_;
 6217:     my ($symb)=&get_symb($r);
 6218:     if (!$symb) {return '';}
 6219:     my $default_form_data=&defaultFormData($symb);
 6220:     $r->print(&scantron_form_start().$default_form_data);
 6221:     if ( $env{'form.selectpage'} eq '' ||
 6222: 	 $env{'form.scantron_selectfile'} eq '' ||
 6223: 	 $env{'form.scantron_format'} eq '' ) {
 6224: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
 6225: 	if ( $env{'form.selectpage'} eq '') {
 6226: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
 6227: 	} 
 6228: 	if ( $env{'form.scantron_selectfile'} eq '') {
 6229: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
 6230: 	} 
 6231: 	if ( $env{'form.scantron_format'} eq '') {
 6232: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
 6233: 	} 
 6234:     } else {
 6235: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 6236: 	$r->print('
 6237: '.$warning.'
 6238: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
 6239: <input type="hidden" name="command" value="scantron_validate" />
 6240: ');
 6241:     }
 6242:     $r->print("</form><br />".&show_grading_menu_form($symb));
 6243:     return '';
 6244: }
 6245: 
 6246: =pod
 6247: 
 6248: =item scantron_form_start
 6249: 
 6250:     html hidden input for remembering all selected grading options
 6251: 
 6252: =cut
 6253: 
 6254: sub scantron_form_start {
 6255:     my ($max_bubble)=@_;
 6256:     my $result= <<SCANTRONFORM;
 6257: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6258:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 6259:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 6260:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 6261:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 6262:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 6263:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 6264:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 6265:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 6266:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 6267: SCANTRONFORM
 6268: 
 6269:   my $line = 0;
 6270:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 6271:        my $chunk =
 6272: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 6273:        $chunk .=
 6274: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 6275:        $chunk .= 
 6276:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
 6277:        $chunk .=
 6278:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
 6279:        $result .= $chunk;
 6280:        $line++;
 6281:    }
 6282:     return $result;
 6283: }
 6284: 
 6285: =pod
 6286: 
 6287: =item scantron_validate_file
 6288: 
 6289:     Dispatch routine for doing validation of a bubble sheet data file.
 6290: 
 6291:     Also processes any necessary information resets that need to
 6292:     occur before validation begins (ignore previous corrections,
 6293:     restarting the skipped records processing)
 6294: 
 6295: =cut
 6296: 
 6297: sub scantron_validate_file {
 6298:     my ($r) = @_;
 6299:     my ($symb)=&get_symb($r);
 6300:     if (!$symb) {return '';}
 6301:     my $default_form_data=&defaultFormData($symb);
 6302:     
 6303:     # do the detection of only doing skipped records first befroe we delete
 6304:     # them when doing the corrections reset
 6305:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 6306: 	&reset_skipping_status();
 6307:     }
 6308:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 6309: 	&remember_current_skipped();
 6310: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 6311:     }
 6312: 
 6313:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 6314: 	&check_for_error($r,&scantron_remove_file('corrected'));
 6315: 	&check_for_error($r,&scantron_remove_file('skipped'));
 6316: 	&check_for_error($r,&scantron_remove_scan_data());
 6317: 	$env{'form.scantron_options_ignore'}='done';
 6318:     }
 6319: 
 6320:     if ($env{'form.scantron_corrections'}) {
 6321: 	&scantron_process_corrections($r);
 6322:     }
 6323:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
 6324:     #get the student pick code ready
 6325:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 6326:     my $max_bubble=&scantron_get_maxbubble();
 6327:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 6328:     $r->print($result);
 6329:     
 6330:     my @validate_phases=( 'sequence',
 6331: 			  'ID',
 6332: 			  'CODE',
 6333: 			  'doublebubble',
 6334: 			  'missingbubbles');
 6335:     if (!$env{'form.validatepass'}) {
 6336: 	$env{'form.validatepass'} = 0;
 6337:     }
 6338:     my $currentphase=$env{'form.validatepass'};
 6339: 
 6340: 
 6341:     my $stop=0;
 6342:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 6343: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
 6344: 	$r->rflush();
 6345: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 6346: 	{
 6347: 	    no strict 'refs';
 6348: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 6349: 	}
 6350:     }
 6351:     if (!$stop) {
 6352: 	my $warning=&scantron_warning_screen('Start Grading');
 6353: 	$r->print(&mt('Validation process complete.').'<br />
 6354: '.$warning.'
 6355: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
 6356: <input type="hidden" name="command" value="scantron_process" />
 6357: ');
 6358: 
 6359:     } else {
 6360: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 6361: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 6362:     }
 6363:     if ($stop) {
 6364: 	if ($validate_phases[$currentphase] eq 'sequence') {
 6365: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
 6366: 	    $r->print(' '.&mt('this error').' <br />');
 6367: 
 6368: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
 6369: 	} else {
 6370:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
 6371: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
 6372:             } else {
 6373:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
 6374:             }
 6375: 	    $r->print(' '.&mt('using corrected info').' <br />');
 6376: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
 6377: 	    $r->print(" ".&mt("this scanline saving it for later."));
 6378: 	}
 6379:     }
 6380:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 6381:     return '';
 6382: }
 6383: 
 6384: 
 6385: =pod
 6386: 
 6387: =item scantron_remove_file
 6388: 
 6389:    Removes the requested bubble sheet data file, makes sure that
 6390:    scantron_original_<filename> is never removed
 6391: 
 6392: 
 6393: =cut
 6394: 
 6395: sub scantron_remove_file {
 6396:     my ($which)=@_;
 6397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6399:     my $file='scantron_';
 6400:     if ($which eq 'corrected' || $which eq 'skipped') {
 6401: 	$file.=$which.'_';
 6402:     } else {
 6403: 	return 'refused';
 6404:     }
 6405:     $file.=$env{'form.scantron_selectfile'};
 6406:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 6407: }
 6408: 
 6409: 
 6410: =pod
 6411: 
 6412: =item scantron_remove_scan_data
 6413: 
 6414:    Removes all scan_data correction for the requested bubble sheet
 6415:    data file.  (In the case that both the are doing skipped records we need
 6416:    to remember the old skipped lines for the time being so that element
 6417:    persists for a while.)
 6418: 
 6419: =cut
 6420: 
 6421: sub scantron_remove_scan_data {
 6422:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6423:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6424:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 6425:     my @todelete;
 6426:     my $filename=$env{'form.scantron_selectfile'};
 6427:     foreach my $key (@keys) {
 6428: 	if ($key=~/^\Q$filename\E_/) {
 6429: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 6430: 		$key=~/remember_skipping/) {
 6431: 		next;
 6432: 	    }
 6433: 	    push(@todelete,$key);
 6434: 	}
 6435:     }
 6436:     my $result;
 6437:     if (@todelete) {
 6438: 	$result = &Apache::lonnet::del('nohist_scantrondata',
 6439: 				       \@todelete,$cdom,$cname);
 6440:     } else {
 6441: 	$result = 'ok';
 6442:     }
 6443:     return $result;
 6444: }
 6445: 
 6446: 
 6447: =pod
 6448: 
 6449: =item scantron_getfile
 6450: 
 6451:     Fetches the requested bubble sheet data file (all 3 versions), and
 6452:     the scan_data hash
 6453:   
 6454:   Arguments:
 6455:     None
 6456: 
 6457:   Returns:
 6458:     2 hash references
 6459: 
 6460:      - first one has 
 6461:          orig      -
 6462:          corrected -
 6463:          skipped   -  each of which points to an array ref of the specified
 6464:                       file broken up into individual lines
 6465:          count     - number of scanlines
 6466:  
 6467:      - second is the scan_data hash possible keys are
 6468:        ($number refers to scanline numbered $number and thus the key affects
 6469:         only that scanline
 6470:         $bubline refers to the specific bubble line element and the aspects
 6471:         refers to that specific bubble line element)
 6472: 
 6473:        $number.user - username:domain to use
 6474:        $number.CODE_ignore_dup 
 6475:                     - ignore the duplicate CODE error 
 6476:        $number.useCODE
 6477:                     - use the CODE in the scanline as is
 6478:        $number.no_bubble.$bubline
 6479:                     - it is valid that there is no bubbled in bubble
 6480:                       at $number $bubline
 6481:        remember_skipping
 6482:                     - a frozen hash containing keys of $number and values
 6483:                       of either 
 6484:                         1 - we are on a 'do skipped records pass' and plan
 6485:                             on processing this line
 6486:                         2 - we are on a 'do skipped records pass' and this
 6487:                             scanline has been marked to skip yet again
 6488: 
 6489: =cut
 6490: 
 6491: sub scantron_getfile {
 6492:     #FIXME really would prefer a scantron directory
 6493:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6494:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6495:     my $lines;
 6496:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6497: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 6498:     my %scanlines;
 6499:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 6500:     my $temp=$scanlines{'orig'};
 6501:     $scanlines{'count'}=$#$temp;
 6502: 
 6503:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6504: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 6505:     if ($lines eq '-1') {
 6506: 	$scanlines{'corrected'}=[];
 6507:     } else {
 6508: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 6509:     }
 6510:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 6511: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 6512:     if ($lines eq '-1') {
 6513: 	$scanlines{'skipped'}=[];
 6514:     } else {
 6515: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 6516:     }
 6517:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 6518:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6519:     my %scan_data = @tmp;
 6520:     return (\%scanlines,\%scan_data);
 6521: }
 6522: 
 6523: =pod
 6524: 
 6525: =item lonnet_putfile
 6526: 
 6527:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6528: 
 6529:  Arguments:
 6530:    $contents - data to store
 6531:    $filename - filename to store $contents into
 6532: 
 6533:  Returns:
 6534:    result value from &Apache::lonnet::finishuserfileupload
 6535: 
 6536: =cut
 6537: 
 6538: sub lonnet_putfile {
 6539:     my ($contents,$filename)=@_;
 6540:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6541:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6542:     $env{'form.sillywaytopassafilearound'}=$contents;
 6543:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6544: 
 6545: }
 6546: 
 6547: =pod
 6548: 
 6549: =item scantron_putfile
 6550: 
 6551:     Stores the current version of the bubble sheet data files, and the
 6552:     scan_data hash. (Does not modify the original version only the
 6553:     corrected and skipped versions.
 6554: 
 6555:  Arguments:
 6556:     $scanlines - hash ref that looks like the first return value from
 6557:                  &scantron_getfile()
 6558:     $scan_data - hash ref that looks like the second return value from
 6559:                  &scantron_getfile()
 6560: 
 6561: =cut
 6562: 
 6563: sub scantron_putfile {
 6564:     my ($scanlines,$scan_data) = @_;
 6565:     #FIXME really would prefer a scantron directory
 6566:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6567:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6568:     if ($scanlines) {
 6569: 	my $prefix='scantron_';
 6570: # no need to update orig, shouldn't change
 6571: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6572: #		    $env{'form.scantron_selectfile'});
 6573: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6574: 			$prefix.'corrected_'.
 6575: 			$env{'form.scantron_selectfile'});
 6576: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6577: 			$prefix.'skipped_'.
 6578: 			$env{'form.scantron_selectfile'});
 6579:     }
 6580:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6581: }
 6582: 
 6583: =pod
 6584: 
 6585: =item scantron_get_line
 6586: 
 6587:    Returns the correct version of the scanline
 6588: 
 6589:  Arguments:
 6590:     $scanlines - hash ref that looks like the first return value from
 6591:                  &scantron_getfile()
 6592:     $scan_data - hash ref that looks like the second return value from
 6593:                  &scantron_getfile()
 6594:     $i         - number of the requested line (starts at 0)
 6595: 
 6596:  Returns:
 6597:    A scanline, (either the original or the corrected one if it
 6598:    exists), or undef if the requested scanline should be
 6599:    skipped. (Either because it's an skipped scanline, or it's an
 6600:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6601:    pass.
 6602: 
 6603: =cut
 6604: 
 6605: sub scantron_get_line {
 6606:     my ($scanlines,$scan_data,$i)=@_;
 6607:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6608:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6609:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6610:     return $scanlines->{'orig'}[$i]; 
 6611: }
 6612: 
 6613: =pod
 6614: 
 6615: =item scantron_todo_count
 6616: 
 6617:     Counts the number of scanlines that need processing.
 6618: 
 6619:  Arguments:
 6620:     $scanlines - hash ref that looks like the first return value from
 6621:                  &scantron_getfile()
 6622:     $scan_data - hash ref that looks like the second return value from
 6623:                  &scantron_getfile()
 6624: 
 6625:  Returns:
 6626:     $count - number of scanlines to process
 6627: 
 6628: =cut
 6629: 
 6630: sub get_todo_count {
 6631:     my ($scanlines,$scan_data)=@_;
 6632:     my $count=0;
 6633:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6634: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6635: 	if ($line=~/^[\s\cz]*$/) { next; }
 6636: 	$count++;
 6637:     }
 6638:     return $count;
 6639: }
 6640: 
 6641: =pod
 6642: 
 6643: =item scantron_put_line
 6644: 
 6645:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6646:     data file.
 6647: 
 6648:  Arguments:
 6649:     $scanlines - hash ref that looks like the first return value from
 6650:                  &scantron_getfile()
 6651:     $scan_data - hash ref that looks like the second return value from
 6652:                  &scantron_getfile()
 6653:     $i         - line number to update
 6654:     $newline   - contents of the updated scanline
 6655:     $skip      - if true make the line for skipping and update the
 6656:                  'skipped' file
 6657: 
 6658: =cut
 6659: 
 6660: sub scantron_put_line {
 6661:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6662:     if ($skip) {
 6663: 	$scanlines->{'skipped'}[$i]=$newline;
 6664: 	&start_skipping($scan_data,$i);
 6665: 	return;
 6666:     }
 6667:     $scanlines->{'corrected'}[$i]=$newline;
 6668: }
 6669: 
 6670: =pod
 6671: 
 6672: =item scantron_clear_skip
 6673: 
 6674:    Remove a line from the 'skipped' file
 6675: 
 6676:  Arguments:
 6677:     $scanlines - hash ref that looks like the first return value from
 6678:                  &scantron_getfile()
 6679:     $scan_data - hash ref that looks like the second return value from
 6680:                  &scantron_getfile()
 6681:     $i         - line number to update
 6682: 
 6683: =cut
 6684: 
 6685: sub scantron_clear_skip {
 6686:     my ($scanlines,$scan_data,$i)=@_;
 6687:     if (exists($scanlines->{'skipped'}[$i])) {
 6688: 	undef($scanlines->{'skipped'}[$i]);
 6689: 	return 1;
 6690:     }
 6691:     return 0;
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item scantron_filter_not_exam
 6697: 
 6698:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6699:    filter out resources that are not marked as 'exam' mode
 6700: 
 6701: =cut
 6702: 
 6703: sub scantron_filter_not_exam {
 6704:     my ($curres)=@_;
 6705:     
 6706:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6707: 	# if the user has asked to not have either hidden
 6708: 	# or 'randomout' controlled resources to be graded
 6709: 	# don't include them
 6710: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6711: 	    && $curres->randomout) {
 6712: 	    return 0;
 6713: 	}
 6714: 	return 1;
 6715:     }
 6716:     return 0;
 6717: }
 6718: 
 6719: =pod
 6720: 
 6721: =item scantron_validate_sequence
 6722: 
 6723:     Validates the selected sequence, checking for resource that are
 6724:     not set to exam mode.
 6725: 
 6726: =cut
 6727: 
 6728: sub scantron_validate_sequence {
 6729:     my ($r,$currentphase) = @_;
 6730: 
 6731:     my $navmap=Apache::lonnavmaps::navmap->new();
 6732:     my (undef,undef,$sequence)=
 6733: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6734: 
 6735:     my $map=$navmap->getResourceByUrl($sequence);
 6736: 
 6737:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6738:                                     value="ignore" />');
 6739:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6740: 	my @resources=
 6741: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6742: 	if (@resources) {
 6743: 	    $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>");
 6744: 	    return (1,$currentphase);
 6745: 	}
 6746:     }
 6747: 
 6748:     return (0,$currentphase+1);
 6749: }
 6750: 
 6751: 
 6752: 
 6753: sub scantron_validate_ID {
 6754:     my ($r,$currentphase) = @_;
 6755:     
 6756:     #get student info
 6757:     my $classlist=&Apache::loncoursedata::get_classlist();
 6758:     my %idmap=&username_to_idmap($classlist);
 6759: 
 6760:     #get scantron line setup
 6761:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6762:     my ($scanlines,$scan_data)=&scantron_getfile();
 6763:     
 6764:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6765: 
 6766:     my %found=('ids'=>{},'usernames'=>{});
 6767:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6768: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6769: 	if ($line=~/^[\s\cz]*$/) { next; }
 6770: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6771: 						 $scan_data);
 6772: 	my $id=$$scan_record{'scantron.ID'};
 6773: 	my $found;
 6774: 	foreach my $checkid (keys(%idmap)) {
 6775: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6776: 	}
 6777: 	if ($found) {
 6778: 	    my $username=$idmap{$found};
 6779: 	    if ($found{'ids'}{$found}) {
 6780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6781: 					 $line,'duplicateID',$found);
 6782: 		return(1,$currentphase);
 6783: 	    } elsif ($found{'usernames'}{$username}) {
 6784: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6785: 					 $line,'duplicateID',$username);
 6786: 		return(1,$currentphase);
 6787: 	    }
 6788: 	    #FIXME store away line we previously saw the ID on to use above
 6789: 	    $found{'ids'}{$found}++;
 6790: 	    $found{'usernames'}{$username}++;
 6791: 	} else {
 6792: 	    if ($id =~ /^\s*$/) {
 6793: 		my $username=&scan_data($scan_data,"$i.user");
 6794: 		if (defined($username) && $found{'usernames'}{$username}) {
 6795: 		    &scantron_get_correction($r,$i,$scan_record,
 6796: 					     \%scantron_config,
 6797: 					     $line,'duplicateID',$username);
 6798: 		    return(1,$currentphase);
 6799: 		} elsif (!defined($username)) {
 6800: 		    &scantron_get_correction($r,$i,$scan_record,
 6801: 					     \%scantron_config,
 6802: 					     $line,'incorrectID');
 6803: 		    return(1,$currentphase);
 6804: 		}
 6805: 		$found{'usernames'}{$username}++;
 6806: 	    } else {
 6807: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6808: 					 $line,'incorrectID');
 6809: 		return(1,$currentphase);
 6810: 	    }
 6811: 	}
 6812:     }
 6813: 
 6814:     return (0,$currentphase+1);
 6815: }
 6816: 
 6817: 
 6818: sub scantron_get_correction {
 6819:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6820: #FIXME in the case of a duplicated ID the previous line, probably need
 6821: #to show both the current line and the previous one and allow skipping
 6822: #the previous one or the current one
 6823: 
 6824:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6825: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6826: 			    " for PaperID <tt>[_1]</tt>",
 6827: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
 6828:     } else {
 6829: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
 6830: 			    " in scanline [_1] <pre>[_2]</pre>",
 6831: 			    $i,$line)."</p> \n");
 6832:     }
 6833:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
 6834: 			  "The name on the paper is [_2],[_3]",
 6835: 			  $$scan_record{'scantron.ID'},
 6836: 			  $$scan_record{'scantron.LastName'},
 6837: 			  $$scan_record{'scantron.FirstName'})."</p>";
 6838: 
 6839:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6840:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6841:                            # Array populated for doublebubble or
 6842:     my @lines_to_correct;  # missingbubble errors to build javascript
 6843:                            # to validate radio button checking   
 6844: 
 6845:     if ($error =~ /ID$/) {
 6846: 	if ($error eq 'incorrectID') {
 6847: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
 6848: 		      "</p>\n");
 6849: 	} elsif ($error eq 'duplicateID') {
 6850: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
 6851: 	}
 6852: 	$r->print($message);
 6853: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6854: 	$r->print("\n<ul><li> ");
 6855: 	#FIXME it would be nice if this sent back the user ID and
 6856: 	#could do partial userID matches
 6857: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6858: 				       'scantron_username','scantron_domain'));
 6859: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6860: 	$r->print("\n@".
 6861: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6862: 
 6863: 	$r->print('</li>');
 6864:     } elsif ($error =~ /CODE$/) {
 6865: 	if ($error eq 'incorrectCODE') {
 6866: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
 6867: 	} elsif ($error eq 'duplicateCODE') {
 6868: 	    $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");
 6869: 	}
 6870: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
 6871: 			    $$scan_record{'scantron.CODE'})."<br />\n");
 6872: 	$r->print($message);
 6873: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
 6874: 	$r->print("\n<br /> ");
 6875: 	my $i=0;
 6876: 	if ($error eq 'incorrectCODE' 
 6877: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6878: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6879: 	    if ($closest > 0) {
 6880: 		foreach my $testcode (@{$closest}) {
 6881: 		    my $checked='';
 6882: 		    if (!$i) { $checked=' checked="checked" '; }
 6883: 		    $r->print("
 6884:    <label>
 6885:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
 6886:        ".&mt("Use the similar CODE [_1] instead.",
 6887: 	    "<b><tt>".$testcode."</tt></b>")."
 6888:     </label>
 6889:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6890: 		    $r->print("\n<br />");
 6891: 		    $i++;
 6892: 		}
 6893: 	    }
 6894: 	}
 6895: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6896: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6897: 	    $r->print("
 6898:     <label>
 6899:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
 6900:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
 6901: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
 6902:     </label>");
 6903: 	    $r->print("\n<br />");
 6904: 	}
 6905: 
 6906: 	$r->print(<<ENDSCRIPT);
 6907: <script type="text/javascript">
 6908: function change_radio(field) {
 6909:     var slct=document.scantronupload.scantron_CODE_resolution;
 6910:     var i;
 6911:     for (i=0;i<slct.length;i++) {
 6912:         if (slct[i].value==field) { slct[i].checked=true; }
 6913:     }
 6914: }
 6915: </script>
 6916: ENDSCRIPT
 6917: 	my $href="/adm/pickcode?".
 6918: 	   "form=".&escape("scantronupload").
 6919: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6920: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6921: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6922: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6923: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6924: 	    $r->print("
 6925:     <label>
 6926:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
 6927:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
 6928: 	     "<a target='_blank' href='$href'>","</a>")."
 6929:     </label> 
 6930:     ".&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')\" />"));
 6931: 	    $r->print("\n<br />");
 6932: 	}
 6933: 	$r->print("
 6934:     <label>
 6935:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
 6936:        ".&mt("Use [_1] as the CODE.",
 6937: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
 6938: 	$r->print("\n<br /><br />");
 6939:     } elsif ($error eq 'doublebubble') {
 6940: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
 6941: 
 6942: 	# The form field scantron_questions is acutally a list of line numbers.
 6943: 	# represented by this form so:
 6944: 
 6945: 	my $line_list = &questions_to_line_list($arg);
 6946: 
 6947: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6948: 		  $line_list.'" />');
 6949: 	$r->print($message);
 6950: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
 6951: 	foreach my $question (@{$arg}) {
 6952: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6953:                                                    $scan_record, $error);
 6954:             push(@lines_to_correct,@linenums);
 6955: 	}
 6956:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6957:     } elsif ($error eq 'missingbubble') {
 6958: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
 6959: 	$r->print($message);
 6960: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
 6961: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
 6962: 
 6963: 	# The form field scantron_questions is actually a list of line numbers not
 6964: 	# a list of question numbers. Therefore:
 6965: 	#
 6966: 	
 6967: 	my $line_list = &questions_to_line_list($arg);
 6968: 
 6969: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6970: 		  $line_list.'" />');
 6971: 	foreach my $question (@{$arg}) {
 6972: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
 6973:                                                    $scan_record, $error);
 6974:             push(@lines_to_correct,@linenums);
 6975: 	}
 6976:         $r->print(&verify_bubbles_checked(@lines_to_correct));
 6977:     } else {
 6978: 	$r->print("\n<ul>");
 6979:     }
 6980:     $r->print("\n</li></ul>");
 6981: }
 6982: 
 6983: sub verify_bubbles_checked {
 6984:     my (@ansnums) = @_;
 6985:     my $ansnumstr = join('","',@ansnums);
 6986:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
 6987:     my $output = (<<ENDSCRIPT);
 6988: <script type="text/javascript">
 6989: function verify_bubble_radio(form) {
 6990:     var ansnumArray = new Array ("$ansnumstr");
 6991:     var need_bubble_count = 0;
 6992:     for (var i=0; i<ansnumArray.length; i++) {
 6993:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
 6994:             var bubble_picked = 0; 
 6995:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
 6996:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
 6997:                     bubble_picked = 1;
 6998:                 }
 6999:             }
 7000:             if (bubble_picked == 0) {
 7001:                 need_bubble_count ++;
 7002:             }
 7003:         }
 7004:     }
 7005:     if (need_bubble_count) {
 7006:         alert("$warning");
 7007:         return;
 7008:     }
 7009:     form.submit(); 
 7010: }
 7011: </script>
 7012: ENDSCRIPT
 7013:     return $output;
 7014: }
 7015: 
 7016: =pod
 7017: 
 7018: =item  questions_to_line_list
 7019: 
 7020: Converts a list of questions into a string of comma separated
 7021: line numbers in the answer sheet used by the questions.  This is
 7022: used to fill in the scantron_questions form field.
 7023: 
 7024:   Arguments:
 7025:      questions    - Reference to an array of questions.
 7026: 
 7027: =cut
 7028: 
 7029: 
 7030: sub questions_to_line_list {
 7031:     my ($questions) = @_;
 7032:     my @lines;
 7033: 
 7034:     foreach my $item (@{$questions}) {
 7035:         my $question = $item;
 7036:         my ($first,$count,$last);
 7037:         if ($item =~ /^(\d+)\.(\d+)$/) {
 7038:             $question = $1;
 7039:             my $subquestion = $2;
 7040:             $first = $first_bubble_line{$question-1} + 1;
 7041:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7042:             my $subcount = 1;
 7043:             while ($subcount<$subquestion) {
 7044:                 $first += $subans[$subcount-1];
 7045:                 $subcount ++;
 7046:             }
 7047:             $count = $subans[$subquestion-1];
 7048:         } else {
 7049: 	    $first   = $first_bubble_line{$question-1} + 1;
 7050: 	    $count   = $bubble_lines_per_response{$question-1};
 7051:         }
 7052:         $last = $first+$count-1;
 7053:         push(@lines, ($first..$last));
 7054:     }
 7055:     return join(',', @lines);
 7056: }
 7057: 
 7058: =pod 
 7059: 
 7060: =item prompt_for_corrections
 7061: 
 7062: Prompts for a potentially multiline correction to the
 7063: user's bubbling (factors out common code from scantron_get_correction
 7064: for multi and missing bubble cases).
 7065: 
 7066:  Arguments:
 7067:    $r           - Apache request object.
 7068:    $question    - The question number to prompt for.
 7069:    $scan_config - The scantron file configuration hash.
 7070:    $scan_record - Reference to the hash that has the the parsed scanlines.
 7071:    $error       - Type of error
 7072: 
 7073:  Implicit inputs:
 7074:    %bubble_lines_per_response   - Starting line numbers for each question.
 7075:                                   Numbered from 0 (but question numbers are from
 7076:                                   1.
 7077:    %first_bubble_line           - Starting bubble line for each question.
 7078:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
 7079:                                   type problems render as separate sub-questions, 
 7080:                                   in exam mode. This hash contains a 
 7081:                                   comma-separated list of the lines per 
 7082:                                   sub-question.
 7083:    %responsetype_per_response   - essayresponse, formularesponse,
 7084:                                   stringresponse, imageresponse, reactionresponse,
 7085:                                   and organicresponse type problem parts can have
 7086:                                   multiple lines per response if the weight
 7087:                                   assigned exceeds 10.  In this case, only
 7088:                                   one bubble per line is permitted, but more 
 7089:                                   than one line might contain bubbles, e.g.
 7090:                                   bubbling of: line 1 - J, line 2 - J, 
 7091:                                   line 3 - B would assign 22 points.  
 7092: 
 7093: =cut
 7094: 
 7095: sub prompt_for_corrections {
 7096:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
 7097:     my ($current_line,$lines);
 7098:     my @linenums;
 7099:     my $questionnum = $question;
 7100:     if ($question =~ /^(\d+)\.(\d+)$/) {
 7101:         $question = $1;
 7102:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7103:         my $subquestion = $2;
 7104:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7105:         my $subcount = 1;
 7106:         while ($subcount<$subquestion) {
 7107:             $current_line += $subans[$subcount-1];
 7108:             $subcount ++;
 7109:         }
 7110:         $lines = $subans[$subquestion-1];
 7111:     } else {
 7112:         $current_line = $first_bubble_line{$question-1} + 1 ;
 7113:         $lines        = $bubble_lines_per_response{$question-1};
 7114:     }
 7115:     if ($lines > 1) {
 7116:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
 7117:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
 7118:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
 7119:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
 7120:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
 7121:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
 7122:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
 7123:             $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 />');
 7124:         } else {
 7125:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
 7126:         }
 7127:     }
 7128:     for (my $i =0; $i < $lines; $i++) {
 7129:         my $selected = $$scan_record{"scantron.$current_line.answer"};
 7130: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
 7131: 	        		  $questionnum,$error,split('', $selected));
 7132:         push(@linenums,$current_line);
 7133: 	$current_line++;
 7134:     }
 7135:     if ($lines > 1) {
 7136: 	$r->print("<hr /><br />");
 7137:     }
 7138:     return @linenums;
 7139: }
 7140: 
 7141: =pod
 7142: 
 7143: =item scantron_bubble_selector
 7144:   
 7145:    Generates the html radiobuttons to correct a single bubble line
 7146:    possibly showing the existing the selected bubbles if known
 7147: 
 7148:  Arguments:
 7149:     $r           - Apache request object
 7150:     $scan_config - hash from &get_scantron_config()
 7151:     $line        - Number of the line being displayed.
 7152:     $questionnum - Question number (may include subquestion)
 7153:     $error       - Type of error.
 7154:     @selected    - Array of bubbles picked on this line.
 7155: 
 7156: =cut
 7157: 
 7158: sub scantron_bubble_selector {
 7159:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
 7160:     my $max=$$scan_config{'Qlength'};
 7161: 
 7162:     my $scmode=$$scan_config{'Qon'};
 7163:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 7164: 
 7165:     my @alphabet=('A'..'Z');
 7166:     $r->print(&Apache::loncommon::start_data_table().
 7167:               &Apache::loncommon::start_data_table_row());
 7168:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
 7169:     for (my $i=0;$i<$max+1;$i++) {
 7170: 	$r->print("\n".'<td align="center">');
 7171: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 7172: 	else { $r->print('&nbsp;'); }
 7173: 	$r->print('</td>');
 7174:     }
 7175:     $r->print(&Apache::loncommon::end_data_table_row().
 7176:               &Apache::loncommon::start_data_table_row());
 7177:     for (my $i=0;$i<$max;$i++) {
 7178: 	$r->print("\n".
 7179: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
 7180: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 7181:     }
 7182:     my $nobub_checked = ' ';
 7183:     if ($error eq 'missingbubble') {
 7184:         $nobub_checked = ' checked = "checked" ';
 7185:     }
 7186:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
 7187: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
 7188:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
 7189:               $line.'" value="'.$questionnum.'" /></td>');
 7190:     $r->print(&Apache::loncommon::end_data_table_row().
 7191:               &Apache::loncommon::end_data_table());
 7192: }
 7193: 
 7194: =pod
 7195: 
 7196: =item num_matches
 7197: 
 7198:    Counts the number of characters that are the same between the two arguments.
 7199: 
 7200:  Arguments:
 7201:    $orig - CODE from the scanline
 7202:    $code - CODE to match against
 7203: 
 7204:  Returns:
 7205:    $count - integer count of the number of same characters between the
 7206:             two arguments
 7207: 
 7208: =cut
 7209: 
 7210: sub num_matches {
 7211:     my ($orig,$code) = @_;
 7212:     my @code=split(//,$code);
 7213:     my @orig=split(//,$orig);
 7214:     my $same=0;
 7215:     for (my $i=0;$i<scalar(@code);$i++) {
 7216: 	if ($code[$i] eq $orig[$i]) { $same++; }
 7217:     }
 7218:     return $same;
 7219: }
 7220: 
 7221: =pod
 7222: 
 7223: =item scantron_get_closely_matching_CODEs
 7224: 
 7225:    Cycles through all CODEs and finds the set that has the greatest
 7226:    number of same characters as the provided CODE
 7227: 
 7228:  Arguments:
 7229:    $allcodes - hash ref returned by &get_codes()
 7230:    $CODE     - CODE from the current scanline
 7231: 
 7232:  Returns:
 7233:    2 element list
 7234:     - first elements is number of how closely matching the best fit is 
 7235:       (5 means best set has 5 matching characters)
 7236:     - second element is an arrary ref containing the set of valid CODEs
 7237:       that best fit the passed in CODE
 7238: 
 7239: =cut
 7240: 
 7241: sub scantron_get_closely_matching_CODEs {
 7242:     my ($allcodes,$CODE)=@_;
 7243:     my @CODEs;
 7244:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 7245: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 7246:     }
 7247: 
 7248:     return ($#CODEs,$CODEs[-1]);
 7249: }
 7250: 
 7251: =pod
 7252: 
 7253: =item get_codes
 7254: 
 7255:    Builds a hash which has keys of all of the valid CODEs from the selected
 7256:    set of remembered CODEs.
 7257: 
 7258:  Arguments:
 7259:   $old_name - name of the set of remembered CODEs
 7260:   $cdom     - domain of the course
 7261:   $cnum     - internal course name
 7262: 
 7263:  Returns:
 7264:   %allcodes - keys are the valid CODEs, values are all 1
 7265: 
 7266: =cut
 7267: 
 7268: sub get_codes {
 7269:     my ($old_name, $cdom, $cnum) = @_;
 7270:     if (!$old_name) {
 7271: 	$old_name=$env{'form.scantron_CODElist'};
 7272:     }
 7273:     if (!$cdom) {
 7274: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 7275:     }
 7276:     if (!$cnum) {
 7277: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 7278:     }
 7279:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 7280: 				    $cdom,$cnum);
 7281:     my %allcodes;
 7282:     if ($result{"type\0$old_name"} eq 'number') {
 7283: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 7284:     } else {
 7285: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 7286:     }
 7287:     return %allcodes;
 7288: }
 7289: 
 7290: =pod
 7291: 
 7292: =item scantron_validate_CODE
 7293: 
 7294:    Validates all scanlines in the selected file to not have any
 7295:    invalid or underspecified CODEs and that none of the codes are
 7296:    duplicated if this was requested.
 7297: 
 7298: =cut
 7299: 
 7300: sub scantron_validate_CODE {
 7301:     my ($r,$currentphase) = @_;
 7302:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7303:     if ($scantron_config{'CODElocation'} &&
 7304: 	$scantron_config{'CODEstart'} &&
 7305: 	$scantron_config{'CODElength'}) {
 7306: 	if (!defined($env{'form.scantron_CODElist'})) {
 7307: 	    &FIXME_blow_up()
 7308: 	}
 7309:     } else {
 7310: 	return (0,$currentphase+1);
 7311:     }
 7312:     
 7313:     my %usedCODEs;
 7314: 
 7315:     my %allcodes=&get_codes();
 7316: 
 7317:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 7318: 
 7319:     my ($scanlines,$scan_data)=&scantron_getfile();
 7320:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7321: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7322: 	if ($line=~/^[\s\cz]*$/) { next; }
 7323: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7324: 						 $scan_data);
 7325: 	my $CODE=$$scan_record{'scantron.CODE'};
 7326: 	my $error=0;
 7327: 	if (!&Apache::lonnet::validCODE($CODE)) {
 7328: 	    &scantron_get_correction($r,$i,$scan_record,
 7329: 				     \%scantron_config,
 7330: 				     $line,'incorrectCODE',\%allcodes);
 7331: 	    return(1,$currentphase);
 7332: 	}
 7333: 	if (%allcodes && !exists($allcodes{$CODE}) 
 7334: 	    && !$$scan_record{'scantron.useCODE'}) {
 7335: 	    &scantron_get_correction($r,$i,$scan_record,
 7336: 				     \%scantron_config,
 7337: 				     $line,'incorrectCODE',\%allcodes);
 7338: 	    return(1,$currentphase);
 7339: 	}
 7340: 	if (exists($usedCODEs{$CODE}) 
 7341: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 7342: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 7343: 	    &scantron_get_correction($r,$i,$scan_record,
 7344: 				     \%scantron_config,
 7345: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 7346: 	    return(1,$currentphase);
 7347: 	}
 7348: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 7349:     }
 7350:     return (0,$currentphase+1);
 7351: }
 7352: 
 7353: =pod
 7354: 
 7355: =item scantron_validate_doublebubble
 7356: 
 7357:    Validates all scanlines in the selected file to not have any
 7358:    bubble lines with multiple bubbles marked.
 7359: 
 7360: =cut
 7361: 
 7362: sub scantron_validate_doublebubble {
 7363:     my ($r,$currentphase) = @_;
 7364:     #get student info
 7365:     my $classlist=&Apache::loncoursedata::get_classlist();
 7366:     my %idmap=&username_to_idmap($classlist);
 7367: 
 7368:     #get scantron line setup
 7369:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7370:     my ($scanlines,$scan_data)=&scantron_getfile();
 7371:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 7372: 
 7373:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7374: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7375: 	if ($line=~/^[\s\cz]*$/) { next; }
 7376: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7377: 						 $scan_data);
 7378: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 7379: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 7380: 				 'doublebubble',
 7381: 				 $$scan_record{'scantron.doubleerror'});
 7382:     	return (1,$currentphase);
 7383:     }
 7384:     return (0,$currentphase+1);
 7385: }
 7386: 
 7387: 
 7388: sub scantron_get_maxbubble {
 7389:     if (defined($env{'form.scantron_maxbubble'}) &&
 7390: 	$env{'form.scantron_maxbubble'}) {
 7391: 	&restore_bubble_lines();
 7392: 	return $env{'form.scantron_maxbubble'};
 7393:     }
 7394: 
 7395:     my (undef, undef, $sequence) =
 7396: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7397: 
 7398:     my $navmap=Apache::lonnavmaps::navmap->new();
 7399:     my $map=$navmap->getResourceByUrl($sequence);
 7400:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7401: 
 7402:     &Apache::lonxml::clear_problem_counter();
 7403: 
 7404:     my $uname       = $env{'form.student'};
 7405:     my $udom        = $env{'form.userdom'};
 7406:     my $cid         = $env{'request.course.id'};
 7407:     my $total_lines = 0;
 7408:     %bubble_lines_per_response = ();
 7409:     %first_bubble_line         = ();
 7410:     %subdivided_bubble_lines   = ();
 7411:     %responsetype_per_response = ();
 7412:   
 7413:     my $response_number = 0;
 7414:     my $bubble_line     = 0;
 7415:     foreach my $resource (@resources) {
 7416:         my $symb = $resource->symb();
 7417: 
 7418:         my (@parts,@allparts,@possible_parts);
 7419: 
 7420:         # Need to retrieve part IDs and response IDs because essayresponse,
 7421:         # reactionresponse and organicresponse items are not included in 
 7422:         # $analysis{'parts'} from lonnet::ssi.  
 7423:         if (ref($resource->parts()) eq 'ARRAY') {
 7424:             foreach my $part (@{$resource->parts()}) {
 7425:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
 7426:                     my @resp_ids = $resource->responseIds($part);
 7427:                     foreach my $id (@resp_ids) {
 7428:                         my $part_id = $part.'.'.$id;
 7429:                         push(@possible_parts,$part_id);
 7430:                     }
 7431:                 }
 7432:             }
 7433:         }
 7434: 
 7435:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
 7436:                                         ('symb' => $symb,
 7437:                                          'grade_target' => 'analyze',
 7438:                                          'grade_courseid' => $cid,
 7439:                                          'grade_domain' => $udom,
 7440:                                          'grade_username' => $uname));
 7441:         my (undef, $an) =
 7442:             split(/_HASH_REF__/,$result, 2);
 7443: 
 7444: 	my %analysis = &Apache::lonnet::str2hash($an);
 7445: 
 7446:         if (ref($analysis{'parts'}) eq 'ARRAY') {
 7447:             foreach my $part (@{$analysis{'parts'}}) {
 7448:                 my ($id,$respid) = split(/\./,$part);
 7449:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
 7450:                     push(@parts,$part);
 7451:                 }
 7452:             }
 7453:         }
 7454:         # Add part_ids for any essayresponse, reactionresponse or 
 7455:         # organicresponse items. 
 7456:         foreach my $part_id (@possible_parts) {
 7457:             if (grep(/^\Q$part_id\E$/,@parts)) {
 7458:                 push(@allparts,$part_id);
 7459:             } else {
 7460:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
 7461:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
 7462:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
 7463:                     push(@allparts,$part_id);
 7464:                 }
 7465:             }
 7466:         }
 7467: 
 7468: 	foreach my $part_id (@allparts) {
 7469:             my $lines;
 7470: 
 7471: 	    # TODO - make this a persistent hash not an array.
 7472: 
 7473:             # optionresponse, matchresponse and rankresponse type items 
 7474:             # render as separate sub-questions in exam mode.
 7475:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
 7476:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
 7477:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
 7478:                 my ($numbub,$numshown);
 7479:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
 7480:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
 7481:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
 7482:                     }
 7483:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
 7484:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
 7485:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
 7486:                     }
 7487:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
 7488:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
 7489:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
 7490:                     }
 7491:                 }
 7492:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
 7493:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
 7494:                 }
 7495:                 my $bubbles_per_line = 10;
 7496:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
 7497:                 if (($numbub % $bubbles_per_line) != 0) {
 7498:                     $inner_bubble_lines++;
 7499:                 }
 7500:                 for (my $i=0; $i<$numshown; $i++) {
 7501:                     $subdivided_bubble_lines{$response_number} .= 
 7502:                         $inner_bubble_lines.',';
 7503:                 }
 7504:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
 7505:                 $lines = $numshown * $inner_bubble_lines;
 7506:             } else {
 7507:                 $lines = $analysis{"$part_id.bubble_lines"};
 7508:             } 
 7509: 
 7510:             $first_bubble_line{$response_number} = $bubble_line;
 7511: 	    $bubble_lines_per_response{$response_number} = $lines;
 7512:             $responsetype_per_response{$response_number} = 
 7513:                 $analysis{$part_id.'.type'};
 7514: 	    $response_number++;
 7515: 
 7516: 	    $bubble_line +=  $lines;
 7517: 	    $total_lines +=  $lines;
 7518: 	}
 7519: 
 7520:     }
 7521:     &Apache::lonnet::delenv('scantron\.');
 7522: 
 7523:     &save_bubble_lines();
 7524:     $env{'form.scantron_maxbubble'} =
 7525: 	$total_lines;
 7526:     return $env{'form.scantron_maxbubble'};
 7527: }
 7528: 
 7529: 
 7530: sub scantron_validate_missingbubbles {
 7531:     my ($r,$currentphase) = @_;
 7532:     #get student info
 7533:     my $classlist=&Apache::loncoursedata::get_classlist();
 7534:     my %idmap=&username_to_idmap($classlist);
 7535: 
 7536:     #get scantron line setup
 7537:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7538:     my ($scanlines,$scan_data)=&scantron_getfile();
 7539:     my $max_bubble=&scantron_get_maxbubble();
 7540:     if (!$max_bubble) { $max_bubble=2**31; }
 7541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 7542: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7543: 	if ($line=~/^[\s\cz]*$/) { next; }
 7544: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7545: 						 $scan_data);
 7546: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 7547: 	my @to_correct;
 7548: 	
 7549: 	# Probably here's where the error is...
 7550: 
 7551: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 7552:             my $lastbubble;
 7553:             if ($missing =~ /^(\d+)\.(\d+)$/) {
 7554:                my $question = $1;
 7555:                my $subquestion = $2;
 7556:                if (!defined($first_bubble_line{$question -1})) { next; }
 7557:                my $first = $first_bubble_line{$question-1};
 7558:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
 7559:                my $subcount = 1;
 7560:                while ($subcount<$subquestion) {
 7561:                    $first += $subans[$subcount-1];
 7562:                    $subcount ++;
 7563:                }
 7564:                my $count = $subans[$subquestion-1];
 7565:                $lastbubble = $first + $count;
 7566:             } else {
 7567:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
 7568:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
 7569:             }
 7570:             if ($lastbubble > $max_bubble) { next; }
 7571: 	    push(@to_correct,$missing);
 7572: 	}
 7573: 	if (@to_correct) {
 7574: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 7575: 				     $line,'missingbubble',\@to_correct);
 7576: 	    return (1,$currentphase);
 7577: 	}
 7578: 
 7579:     }
 7580:     return (0,$currentphase+1);
 7581: }
 7582: 
 7583: 
 7584: sub scantron_process_students {
 7585:     my ($r) = @_;
 7586: 
 7587:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 7588:     my ($symb)=&get_symb($r);
 7589:     if (!$symb) {
 7590: 	return '';
 7591:     }
 7592:     my $default_form_data=&defaultFormData($symb);
 7593: 
 7594:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 7595:     my ($scanlines,$scan_data)=&scantron_getfile();
 7596:     my $classlist=&Apache::loncoursedata::get_classlist();
 7597:     my %idmap=&username_to_idmap($classlist);
 7598:     my $navmap=Apache::lonnavmaps::navmap->new();
 7599:     my $map=$navmap->getResourceByUrl($sequence);
 7600:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 7601: #    $r->print("geto ".scalar(@resources)."<br />");
 7602:     my $result= <<SCANTRONFORM;
 7603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 7604:   <input type="hidden" name="command" value="scantron_configphase" />
 7605:   $default_form_data
 7606: SCANTRONFORM
 7607:     $r->print($result);
 7608: 
 7609:     my @delayqueue;
 7610:     my %completedstudents;
 7611:     
 7612:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
 7613:     my $count=&get_todo_count($scanlines,$scan_data);
 7614:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 7615:  				    'Scantron Progress',$count,
 7616: 				    'inline',undef,'scantronupload');
 7617:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7618: 					  'Processing first student');
 7619:     my $start=&Time::HiRes::time();
 7620:     my $i=-1;
 7621:     my ($uname,$udom,$started);
 7622: 
 7623:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 7624:     
 7625: 
 7626:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
 7627:     # the user and return.
 7628: 
 7629:     if ($ssi_error) {
 7630: 	$r->print("</form>");
 7631: 	&ssi_print_error($r);
 7632: 	$r->print(&show_grading_menu_form($symb));
 7633:         &Apache::lonnet::remove_lock($lock);
 7634: 	return '';		# Dunno why the other returns return '' rather than just returning.
 7635:     }
 7636: 
 7637:     while ($i<$scanlines->{'count'}) {
 7638:  	($uname,$udom)=('','');
 7639:  	$i++;
 7640:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 7641:  	if ($line=~/^[\s\cz]*$/) { next; }
 7642: 	if ($started) {
 7643: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7644: 						     'last student');
 7645: 	}
 7646: 	$started=1;
 7647:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 7648:  						 $scan_data);
 7649:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 7650:  					      \%idmap,$i)) {
 7651:   	    &scantron_add_delay(\@delayqueue,$line,
 7652:  				'Unable to find a student that matches',1);
 7653:  	    next;
 7654:   	}
 7655:  	if (exists $completedstudents{$uname}) {
 7656:  	    &scantron_add_delay(\@delayqueue,$line,
 7657:  				'Student '.$uname.' has multiple sheets',2);
 7658:  	    next;
 7659:  	}
 7660:   	($uname,$udom)=split(/:/,$uname);
 7661: 
 7662: 	&Apache::lonxml::clear_problem_counter();
 7663:   	&Apache::lonnet::appenv($scan_record);
 7664: 
 7665: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 7666: 	    &scantron_putfile($scanlines,$scan_data);
 7667: 	}
 7668: 	
 7669: 	my $i=0;
 7670: 	foreach my $resource (@resources) {
 7671: 	    $i++;
 7672: 	    my %form=('submitted'     =>'scantron',
 7673: 		      'grade_target'  =>'grade',
 7674: 		      'grade_username'=>$uname,
 7675: 		      'grade_domain'  =>$udom,
 7676: 		      'grade_courseid'=>$env{'request.course.id'},
 7677: 		      'grade_symb'    =>$resource->symb());
 7678: 	    if (exists($scan_record->{'scantron.CODE'})
 7679: 		&& 
 7680: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 7681: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 7682: 	    } else {
 7683: 		$form{'CODE'}='';
 7684: 	    } 
 7685: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
 7686: 	    if ($ssi_error) {
 7687: 		$ssi_error = 0;	# So end of handler error message does not trigger.
 7688: 		$r->print("</form>");
 7689: 		&ssi_print_error($r);
 7690: 		$r->print(&show_grading_menu_form($symb));
 7691:                 &Apache::lonnet::remove_lock($lock);
 7692: 		return '';	# Why return ''?  Beats me.
 7693: 	    }
 7694: 
 7695: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 7696: 	}
 7697: 	$completedstudents{$uname}={'line'=>$line};
 7698: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 7699:     } continue {
 7700: 	&Apache::lonxml::clear_problem_counter();
 7701: 	&Apache::lonnet::delenv('scantron\.');
 7702:     }
 7703:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 7704:     &Apache::lonnet::remove_lock($lock);
 7705: #    my $lasttime = &Time::HiRes::time()-$start;
 7706: #    $r->print("<p>took $lasttime</p>");
 7707: 
 7708:     $r->print("</form>");
 7709:     $r->print(&show_grading_menu_form($symb));
 7710:     return '';
 7711: }
 7712: 
 7713: sub scantron_upload_scantron_data {
 7714:     my ($r)=@_;
 7715:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 7716:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 7717: 							  'domainid',
 7718: 							  'coursename');
 7719:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7720: 						   'domainid');
 7721:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7722:     $r->print('
 7723: <script type="text/javascript" language="javascript">
 7724:     function checkUpload(formname) {
 7725: 	if (formname.upfile.value == "") {
 7726: 	    alert("Please use the browse button to select a file from your local directory.");
 7727: 	    return false;
 7728: 	}
 7729: 	formname.submit();
 7730:     }
 7731: </script>
 7732: 
 7733: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
 7734: '.$default_form_data.'
 7735: <table>
 7736: <tr><td>'.$select_link.'                             </td></tr>
 7737: <tr><td>'.&mt('Course ID:').'     </td>
 7738:     <td><input name="courseid"   type="text" />      </td></tr>
 7739: <tr><td>'.&mt('Course Name:').'   </td>
 7740:     <td><input name="coursename" type="text" />      </td></tr>
 7741: <tr><td>'.&mt('Domain:').'        </td>
 7742:     <td>'.$domsel.'                                  </td></tr>
 7743: <tr><td>'.&mt('File to upload:').'</td>
 7744:     <td><input type="file" name="upfile" size="50" /></td></tr>
 7745: </table>
 7746: <input name="command" value="scantronupload_save" type="hidden" />
 7747: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
 7748: </form>
 7749: ');
 7750:     return '';
 7751: }
 7752: 
 7753: 
 7754: sub scantron_upload_scantron_data_save {
 7755:     my($r)=@_;
 7756:     my ($symb)=&get_symb($r,1);
 7757:     my $doanotherupload=
 7758: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7759: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7760: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
 7761: 	'</form>'."\n";
 7762:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7763: 	!&Apache::lonnet::allowed('usc',
 7764: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7765: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
 7766: 	if ($symb) {
 7767: 	    $r->print(&show_grading_menu_form($symb));
 7768: 	} else {
 7769: 	    $r->print($doanotherupload);
 7770: 	}
 7771: 	return '';
 7772:     }
 7773:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7774:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
 7775:     my $fname=$env{'form.upfile.filename'};
 7776:     #FIXME
 7777:     #copied from lonnet::userfileupload()
 7778:     #make that function able to target a specified course
 7779:     # Replace Windows backslashes by forward slashes
 7780:     $fname=~s/\\/\//g;
 7781:     # Get rid of everything but the actual filename
 7782:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7783:     # Replace spaces by underscores
 7784:     $fname=~s/\s+/\_/g;
 7785:     # Replace all other weird characters by nothing
 7786:     $fname=~s/[^\w\.\-]//g;
 7787:     # See if there is anything left
 7788:     unless ($fname) { return 'error: no uploaded file'; }
 7789:     my $uploadedfile=$fname;
 7790:     $fname='scantron_orig_'.$fname;
 7791:     if (length($env{'form.upfile'}) < 2) {
 7792: 	$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>"));
 7793:     } else {
 7794: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7795: 	if ($result =~ m|^/uploaded/|) {
 7796: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
 7797: 			  (length($env{'form.upfile'})-1),
 7798: 			  '<span class="LC_filename">'.$result."</span>"));
 7799: 	} else {
 7800: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
 7801: 			  $result,
 7802: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
 7803: 
 7804: 	}
 7805:     }
 7806:     if ($symb) {
 7807: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7808:     } else {
 7809: 	$r->print($doanotherupload);
 7810:     }
 7811:     return '';
 7812: }
 7813: 
 7814: sub valid_file {
 7815:     my ($requested_file)=@_;
 7816:     foreach my $filename (sort(&scantron_filenames())) {
 7817: 	if ($requested_file eq $filename) { return 1; }
 7818:     }
 7819:     return 0;
 7820: }
 7821: 
 7822: sub scantron_download_scantron_data {
 7823:     my ($r)=@_;
 7824:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7825:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7827:     my $file=$env{'form.scantron_selectfile'};
 7828:     if (! &valid_file($file)) {
 7829: 	$r->print('
 7830: 	<p>
 7831: 	    '.&mt('The requested file name was invalid.').'
 7832:         </p>
 7833: ');
 7834: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7835: 	return;
 7836:     }
 7837:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7838:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7839:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7840:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7841:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7842:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7843:     $r->print('
 7844:     <p>
 7845: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
 7846: 	      '<a href="'.$orig.'">','</a>').'
 7847:     </p>
 7848:     <p>
 7849: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
 7850: 	      '<a href="'.$corrected.'">','</a>').'
 7851:     </p>
 7852:     <p>
 7853: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
 7854: 	      '<a href="'.$skipped.'">','</a>').'
 7855:     </p>
 7856: ');
 7857:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7858:     return '';
 7859: }
 7860: 
 7861: sub checkscantron_results {
 7862:     my ($r) = @_;
 7863:     my ($symb)=&get_symb($r);
 7864:     if (!$symb) {return '';}
 7865:     my $grading_menu_button=&show_grading_menu_form($symb);
 7866:     my $cid = $env{'request.course.id'};
 7867:     my %lettdig = (
 7868:                     A => 1,
 7869:                     B => 2,
 7870:                     C => 3,
 7871:                     D => 4,
 7872:                     E => 5,
 7873:                     F => 6,
 7874:                     G => 7,
 7875:                     H => 8,
 7876:                     I => 9,
 7877:                     J => 0,
 7878:                   );
 7879:     my $numletts = scalar(keys(%lettdig));
 7880:     my $cnum = $env{'course.'.$cid.'.num'};
 7881:     my $cdom = $env{'course.'.$cid.'.domain'};
 7882:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
 7883:     my %record;
 7884:     my %scantron_config =
 7885:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
 7886:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
 7887:     my $classlist=&Apache::loncoursedata::get_classlist();
 7888:     my %idmap=&Apache::grades::username_to_idmap($classlist);
 7889:     my $navmap=Apache::lonnavmaps::navmap->new();
 7890:     my $map=$navmap->getResourceByUrl($sequence);
 7891:     my @resources=$navmap->retrieveResources($map,undef,1,0);
 7892:     my (%scandata,%lastname,%bylast);
 7893:     $r->print('
 7894: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
 7895: 
 7896:     my @delayqueue;
 7897:     my %completedstudents;
 7898: 
 7899:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
 7900:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
 7901:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
 7902:                                     'inline',undef,'checkscantron');
 7903:     my ($username,$domain,$uname,$started);
 7904: 
 7905:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
 7906: 
 7907:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 7908:                                           'Processing first student');
 7909:     my $start=&Time::HiRes::time();
 7910:     my $i=-1;
 7911: 
 7912:     while ($i<$scanlines->{'count'}) {
 7913:         ($username,$domain,$uname)=('','','');
 7914:         $i++;
 7915:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
 7916:         if ($line=~/^[\s\cz]*$/) { next; }
 7917:         if ($started) {
 7918:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 7919:                                                      'last student');
 7920:         }
 7921:         $started=1;
 7922:         my $scan_record=
 7923:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
 7924:                                                      $scan_data);
 7925:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
 7926:                                                               \%idmap,$i)) {
 7927:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7928:                                 'Unable to find a student that matches',1);
 7929:             next;
 7930:         }
 7931:         if (exists $completedstudents{$uname}) {
 7932:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
 7933:                                 'Student '.$uname.' has multiple sheets',2);
 7934:             next;
 7935:         }
 7936:         my $pid = $scan_record->{'scantron.ID'};
 7937:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
 7938:         push(@{$bylast{$lastname{$pid}}},$pid);
 7939:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
 7940:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
 7941:         chomp($scandata{$pid});
 7942:         $scandata{$pid} =~ s/\r$//;
 7943:         ($username,$domain)=split(/:/,$uname);
 7944:         my $counter = -1;
 7945:         my (%expected,%startpos);
 7946:         foreach my $resource (@resources) {
 7947:             next if (!$resource->is_problem());
 7948:             my $symb = $resource->symb();
 7949:             my $partsref = $resource->parts();
 7950:             my @parts;
 7951:             my @part_ids = ();
 7952:             if (ref($partsref) eq 'ARRAY') {
 7953:                @parts = @{$partsref};
 7954:                foreach my $part (@parts) {
 7955:                    my @resp_ids = $resource->responseIds($part);
 7956:                    foreach my $resp (@resp_ids) {
 7957:                        $counter ++;
 7958:                        my $part_id = $part.'.'.$resp;
 7959:                        $expected{$part_id} = 0;
 7960:                        push(@part_ids,$part_id);
 7961:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
 7962:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
 7963:                            foreach my $item (@sub_lines) {
 7964:                                $expected{$part_id} += $item;
 7965:                            }
 7966:                        } else {
 7967:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
 7968:                        }
 7969:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
 7970:                    }
 7971:                 }
 7972:             }
 7973:             if ($symb) {
 7974:                 my %recorded;
 7975:                 my (%returnhash) =
 7976:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
 7977:                 if ($returnhash{'version'}) {
 7978:                     my %lasthash=();
 7979:                     my $version;
 7980:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
 7981:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 7982:                             $lasthash{$key}=$returnhash{$version.':'.$key};
 7983:                         }
 7984:                     }
 7985:                     foreach my $key (keys(%lasthash)) {
 7986:                         if ($key =~ /\.scantron$/) {
 7987:                             my $value = &unescape($lasthash{$key});
 7988:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
 7989:                             if ($value eq '') {
 7990:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
 7991:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
 7992:                                         $recorded{$part_id} .= $;
 7993:                                     }
 7994:                                 }
 7995:                             } else {
 7996:                                 my @tocheck;
 7997:                                 my @items = split(//,$value);
 7998:                                 if (($scantron_config{'Qon'} eq 'letter') ||
 7999:                                     ($scantron_config{'Qon'} eq 'number')) {
 8000:                                     if (@items < $expected{$part_id}) {
 8001:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
 8002:                                         my @singles = split(//,$fragment);
 8003:                                         foreach my $pos (@singles) {
 8004:                                             if ($pos eq ' ') {
 8005:                                                 push(@tocheck,$pos);
 8006:                                             } else {
 8007:                                                 my $next = shift(@items);
 8008:                                                 push(@tocheck,$next);
 8009:                                             }
 8010:                                         }
 8011:                                     } else {
 8012:                                         @tocheck = @items;
 8013:                                     }
 8014:                                     foreach my $letter (@tocheck) {
 8015:                                         if ($scantron_config{'Qon'} eq 'letter') {
 8016:                                             if ($letter !~ /^[A-J]$/) {
 8017:                                                 $letter = $scantron_config{'Qoff'};
 8018:                                             }
 8019:                                             $recorded{$part_id} .= $letter;
 8020:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
 8021:                                             my $digit;
 8022:                                             if ($letter !~ /^[A-J]$/) {
 8023:                                                 $digit = $scantron_config{'Qoff'};
 8024:                                             } else {
 8025:                                                 $digit = $lettdig{$letter};
 8026:                                             }
 8027:                                             $recorded{$part_id} .= $digit;
 8028:                                         }
 8029:                                     }
 8030:                                 } else {
 8031:                                     @tocheck = @items;
 8032:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
 8033:                                         my $curr_sub = shift(@tocheck);
 8034:                                         my $digit;
 8035:                                         if ($curr_sub =~ /^[A-J]$/) {
 8036:                                             $digit = $lettdig{$curr_sub}-1;
 8037:                                         }
 8038:                                         if ($curr_sub eq 'J') {
 8039:                                             $digit += scalar($numletts);
 8040:                                         }
 8041:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8042:                                             if ($j == $digit) {
 8043:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
 8044:                                             } else {
 8045:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8046:                                             }
 8047:                                         }
 8048:                                     }
 8049:                                 }
 8050:                             }
 8051:                         }
 8052:                     }
 8053:                 }
 8054:                 foreach my $part_id (@part_ids) {
 8055:                     if ($recorded{$part_id} eq '') {
 8056:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
 8057:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
 8058:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
 8059:                             }
 8060:                         }
 8061:                     }
 8062:                     $record{$pid} .= $recorded{$part_id};
 8063:                 }
 8064:             }
 8065:         }
 8066:     }
 8067:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 8068:     $r->print('<br />');
 8069:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
 8070:     $passed = 0;
 8071:     $failed = 0;
 8072:     $numstudents = 0;
 8073:     foreach my $last (sort(keys(%bylast))) {
 8074:         if (ref($bylast{$last}) eq 'ARRAY') {
 8075:             foreach my $pid (sort(@{$bylast{$last}})) {
 8076:                 my $showscandata = $scandata{$pid};
 8077:                 my $showrecord = $record{$pid};
 8078:                 $showscandata =~ s/\s/&nbsp;/g;
 8079:                 $showrecord =~ s/\s/&nbsp;/g;
 8080:                 if ($scandata{$pid} eq $record{$pid}) {
 8081:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
 8082:                     $okstudents .= '<tr class="'.$css_class.'">'.
 8083: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
 8084: '</tr>'."\n".
 8085: '<tr class="'.$css_class.'">'."\n".
 8086: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
 8087:                     $passed ++;
 8088:                 } else {
 8089:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
 8090:                     $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".
 8091: '</tr>'."\n".
 8092: '<tr class="'.$css_class.'">'."\n".
 8093: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
 8094: '</tr>'."\n";
 8095:                     $failed ++;
 8096:                 }
 8097:                 $numstudents ++;
 8098:             }
 8099:         }
 8100:     }
 8101:     $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>');
 8102:     $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>');
 8103:     if ($passed) {
 8104:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
 8105:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8106:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8107:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8108:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8109:                  $okstudents."\n".
 8110:                  &Apache::loncommon::end_data_table().'<br />');
 8111:     }
 8112:     if ($failed) {
 8113:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
 8114:         $r->print(&Apache::loncommon::start_data_table()."\n".
 8115:                  &Apache::loncommon::start_data_table_header_row()."\n".
 8116:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
 8117:                  &Apache::loncommon::end_data_table_header_row()."\n".
 8118:                  $badstudents."\n".
 8119:                  &Apache::loncommon::end_data_table()).'<br />'.
 8120:                  &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.');  
 8121:     }
 8122:     $r->print('</form><br />'.$grading_menu_button);
 8123:     return;
 8124: }
 8125: 
 8126: 
 8127: #-------- end of section for handling grading scantron forms -------
 8128: #
 8129: #-------------------------------------------------------------------
 8130: 
 8131: #-------------------------- Menu interface -------------------------
 8132: #
 8133: #--- Show a Grading Menu button - Calls the next routine ---
 8134: sub show_grading_menu_form {
 8135:     my ($symb)=@_;
 8136:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 8137: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8138: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 8139: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 8140: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
 8141: 	'</form>'."\n";
 8142:     return $result;
 8143: }
 8144: 
 8145: # -- Retrieve choices for grading form
 8146: sub savedState {
 8147:     my %savedState = ();
 8148:     if ($env{'form.saveState'}) {
 8149: 	foreach (split(/:/,$env{'form.saveState'})) {
 8150: 	    my ($key,$value) = split(/=/,$_,2);
 8151: 	    $savedState{$key} = $value;
 8152: 	}
 8153:     }
 8154:     return \%savedState;
 8155: }
 8156: 
 8157: sub grading_menu {
 8158:     my ($request) = @_;
 8159:     my ($symb)=&get_symb($request);
 8160:     if (!$symb) {return '';}
 8161:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8162:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8163: 
 8164:     $request->print($table);
 8165:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 8166:                   'handgrade'=>$hdgrade,
 8167:                   'probTitle'=>$probTitle,
 8168:                   'command'=>'submit_options',
 8169:                   'saveState'=>"",
 8170:                   'gradingMenu'=>1,
 8171:                   'showgrading'=>"yes");
 8172:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8173:     my @menu = ({ url => $url,
 8174:                      name => &mt('Manual Grading/View Submissions'),
 8175:                      short_description => 
 8176:     &mt('Start the process of hand grading submissions.'),
 8177:                  });
 8178:     $fields{'command'} = 'csvform';
 8179:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8180:     push(@menu, { url => $url,
 8181:                    name => &mt('Upload Scores'),
 8182:                    short_description => 
 8183:             &mt('Specify a file containing the class scores for current resource.')});
 8184:     $fields{'command'} = 'processclicker';
 8185:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8186:     push(@menu, { url => $url,
 8187:                    name => &mt('Process Clicker'),
 8188:                    short_description => 
 8189:             &mt('Specify a file containing the clicker information for this resource.')});
 8190:     $fields{'command'} = 'scantron_selectphase';
 8191:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8192:     push(@menu, { url => $url,
 8193:                    name => &mt('Grade/Manage/Review Scantron Forms'),
 8194:                    short_description => 
 8195:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
 8196:     $fields{'command'} = 'verify';
 8197:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 8198:     push(@menu, { url => "",
 8199:                    name => &mt('Verify Receipt'),
 8200:                    short_description => 
 8201:             &mt('')});
 8202:     #
 8203:     # Create the menu
 8204:     my $Str;
 8205:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 8206:     $Str .= '<form method="post" action="" name="gradingMenu">';
 8207:     $Str .= '<input type="hidden" name="command" value="" />'.
 8208:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8209: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8210: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8211: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8212: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8213: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8214: 
 8215:     foreach my $menudata (@menu) {
 8216:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 8217:             $Str .='    <h3><a '.
 8218:                 $menudata->{'jscript'}.
 8219:                 ' href="'.
 8220:                 $menudata->{'url'}.'" >'.
 8221:                 $menudata->{'name'}."</a></h3>\n";
 8222:         } else {
 8223:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
 8224:                 $menudata->{'jscript'}.
 8225:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 8226:                 ' /> '.
 8227: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
 8228:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 8229:         }
 8230:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 8231:             "\n";
 8232:     }
 8233:     $Str .="</form>\n";
 8234:     $request->print(<<GRADINGMENUJS);
 8235: <script type="text/javascript" language="javascript">
 8236:     function checkChoice(formname,val,cmdx) {
 8237: 	if (val <= 2) {
 8238: 	    var cmd = radioSelection(formname.radioChoice);
 8239: 	    var cmdsave = cmd;
 8240: 	} else {
 8241: 	    cmd = cmdx;
 8242: 	    cmdsave = 'submission';
 8243: 	}
 8244: 	formname.command.value = cmd;
 8245: 	if (val < 5) formname.submit();
 8246: 	if (val == 5) {
 8247: 	    if (!checkReceiptNo(formname,'notOK')) { 
 8248: 	        return false;
 8249: 	    } else {
 8250: 	        formname.submit();
 8251: 	    }
 8252: 	}
 8253:     }
 8254: 
 8255:     function checkReceiptNo(formname,nospace) {
 8256: 	var receiptNo = formname.receipt.value;
 8257: 	var checkOpt = false;
 8258: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8259: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8260: 	if (checkOpt) {
 8261: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8262: 	    formname.receipt.value = "";
 8263: 	    formname.receipt.focus();
 8264: 	    return false;
 8265: 	}
 8266: 	return true;
 8267:     }
 8268: </script>
 8269: GRADINGMENUJS
 8270:     &commonJSfunctions($request);
 8271:     return $Str;    
 8272: }
 8273: 
 8274: 
 8275: #--- Displays the submissions first page -------
 8276: sub submit_options {
 8277:     my ($request) = @_;
 8278:     my ($symb)=&get_symb($request);
 8279:     if (!$symb) {return '';}
 8280:     my $probTitle = &Apache::lonnet::gettitle($symb);
 8281: 
 8282:     $request->print(<<GRADINGMENUJS);
 8283: <script type="text/javascript" language="javascript">
 8284:     function checkChoice(formname,val,cmdx) {
 8285: 	if (val <= 2) {
 8286: 	    var cmd = radioSelection(formname.radioChoice);
 8287: 	    var cmdsave = cmd;
 8288: 	} else {
 8289: 	    cmd = cmdx;
 8290: 	    cmdsave = 'submission';
 8291: 	}
 8292: 	formname.command.value = cmd;
 8293: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 8294: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 8295: 	if (val < 5) formname.submit();
 8296: 	if (val == 5) {
 8297: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 8298: 	    formname.submit();
 8299: 	}
 8300: 	if (val < 7) formname.submit();
 8301:     }
 8302: 
 8303:     function checkReceiptNo(formname,nospace) {
 8304: 	var receiptNo = formname.receipt.value;
 8305: 	var checkOpt = false;
 8306: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 8307: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 8308: 	if (checkOpt) {
 8309: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 8310: 	    formname.receipt.value = "";
 8311: 	    formname.receipt.focus();
 8312: 	    return false;
 8313: 	}
 8314: 	return true;
 8315:     }
 8316: </script>
 8317: GRADINGMENUJS
 8318:     &commonJSfunctions($request);
 8319:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 8320:     my $result;
 8321:     my (undef,$sections) = &getclasslist('all','0');
 8322:     my $savedState = &savedState();
 8323:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 8324:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 8325:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 8326:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 8327: 
 8328:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 8329: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 8330: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 8331: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 8332: 	'<input type="hidden" name="command"     value="" />'."\n".
 8333: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 8334: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 8335: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 8336: 
 8337:     $result.='
 8338:     <div class="LC_grade_select_mode">
 8339:       <div class="LC_grade_select_mode_current">
 8340:         <h2>
 8341:           '.&mt('Grade Current Resource').'
 8342:         </h2>
 8343:         <div class="LC_grade_select_mode_body">
 8344:           <div class="LC_grades_resource_info">
 8345:            '.$table.'
 8346:           </div>
 8347:           <div class="LC_grade_select_mode_selector">
 8348:              <div class="LC_grade_select_mode_selector_header">
 8349:                 '.&mt('Sections').'
 8350:              </div>
 8351:              <div class="LC_grade_select_mode_selector_body">
 8352: 	       <select name="section" multiple="multiple" size="5">'."\n";
 8353:     if (ref($sections)) {
 8354: 	foreach my $section (sort(@$sections)) {
 8355: 	    $result.='<option value="'.$section.'" '.
 8356: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
 8357: 	}
 8358:     }
 8359:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 8360:     $result.='
 8361:              </div>
 8362:           </div>
 8363:           <div class="LC_grade_select_mode_selector">
 8364:              <div class="LC_grade_select_mode_selector_header">
 8365:                 '.&mt('Groups').'
 8366:              </div>
 8367:              <div class="LC_grade_select_mode_selector_body">
 8368:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
 8369:              </div>
 8370:           </div>
 8371:           <div class="LC_grade_select_mode_selector">
 8372:              <div class="LC_grade_select_mode_selector_header">
 8373:                 '.&mt('Access Status').'
 8374:              </div>
 8375:              <div class="LC_grade_select_mode_selector_body">
 8376:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
 8377:              </div>
 8378:           </div>
 8379:           <div class="LC_grade_select_mode_selector">
 8380:              <div class="LC_grade_select_mode_selector_header">
 8381:                 '.&mt('Submission Status').'
 8382:              </div>
 8383:              <div class="LC_grade_select_mode_selector_body">
 8384:                <select name="submitonly" size="5">
 8385: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
 8386: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
 8387: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
 8388: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
 8389:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
 8390:                </select>
 8391:              </div>
 8392:           </div>
 8393:           <div class="LC_grade_select_mode_type_body">
 8394:             <div class="LC_grade_select_mode_type">
 8395:               <label>
 8396:                 <input type="radio" name="radioChoice" value="submission" '.
 8397:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
 8398:              &mt('Select individual students to grade and view submissions.').'
 8399: 	      </label> 
 8400:             </div>
 8401:             <div class="LC_grade_select_mode_type">
 8402: 	      <label>
 8403:                 <input type="radio" name="radioChoice" value="viewgrades" '.
 8404:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 8405:                     &mt('Grade all selected students in a grading table.').'
 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 class="LC_grade_select_mode_page">
 8415:         <h2>
 8416:          '.&mt('Grade Complete Folder for One Student').'
 8417:         </h2>
 8418:         <div class="LC_grades_select_mode_body">
 8419:           <div class="LC_grade_select_mode_type_body">
 8420:             <div class="LC_grade_select_mode_type">
 8421:               <label>
 8422:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
 8423: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 8424:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
 8425:               </label>
 8426:             </div>
 8427:             <div class="LC_grade_select_mode_type">
 8428: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
 8429:             </div>
 8430:           </div>
 8431:         </div>
 8432:       </div>
 8433:     </div>
 8434:   </form>';
 8435:     $result .= &show_grading_menu_form($symb);
 8436:     return $result;
 8437: }
 8438: 
 8439: sub reset_perm {
 8440:     undef(%perm);
 8441: }
 8442: 
 8443: sub init_perm {
 8444:     &reset_perm();
 8445:     foreach my $test_perm ('vgr','mgr','opa') {
 8446: 
 8447: 	my $scope = $env{'request.course.id'};
 8448: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 8449: 
 8450: 	    $scope .= '/'.$env{'request.course.sec'};
 8451: 	    if ( $perm{$test_perm}=
 8452: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 8453: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 8454: 	    } else {
 8455: 		delete($perm{$test_perm});
 8456: 	    }
 8457: 	}
 8458:     }
 8459: }
 8460: 
 8461: sub gather_clicker_ids {
 8462:     my %clicker_ids;
 8463: 
 8464:     my $classlist = &Apache::loncoursedata::get_classlist();
 8465: 
 8466:     # Set up a couple variables.
 8467:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 8468:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 8469:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 8470: 
 8471:     foreach my $student (keys(%$classlist)) {
 8472:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 8473:         my $username = $classlist->{$student}->[$username_idx];
 8474:         my $domain   = $classlist->{$student}->[$domain_idx];
 8475:         my $clickers =
 8476: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 8477:         foreach my $id (split(/\,/,$clickers)) {
 8478:             $id=~s/^[\#0]+//;
 8479:             $id=~s/[\-\:]//g;
 8480:             if (exists($clicker_ids{$id})) {
 8481: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 8482:             } else {
 8483: 		$clicker_ids{$id}=$username.':'.$domain;
 8484:             }
 8485:         }
 8486:     }
 8487:     return %clicker_ids;
 8488: }
 8489: 
 8490: sub gather_adv_clicker_ids {
 8491:     my %clicker_ids;
 8492:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 8493:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8494:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 8495:     foreach my $element (sort(keys(%coursepersonnel))) {
 8496:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 8497:             my ($puname,$pudom)=split(/\:/,$person);
 8498:             my $clickers =
 8499: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 8500:             foreach my $id (split(/\,/,$clickers)) {
 8501: 		$id=~s/^[\#0]+//;
 8502:                 $id=~s/[\-\:]//g;
 8503: 		if (exists($clicker_ids{$id})) {
 8504: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 8505: 		} else {
 8506: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 8507: 		}
 8508:             }
 8509:         }
 8510:     }
 8511:     return %clicker_ids;
 8512: }
 8513: 
 8514: sub clicker_grading_parameters {
 8515:     return ('gradingmechanism' => 'scalar',
 8516:             'upfiletype' => 'scalar',
 8517:             'specificid' => 'scalar',
 8518:             'pcorrect' => 'scalar',
 8519:             'pincorrect' => 'scalar');
 8520: }
 8521: 
 8522: sub process_clicker {
 8523:     my ($r)=@_;
 8524:     my ($symb)=&get_symb($r);
 8525:     if (!$symb) {return '';}
 8526:     my $result=&checkforfile_js();
 8527:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 8528:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 8529:     $result.=$table;
 8530:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 8531:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 8532:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 8533:         '.</b></td></tr>'."\n";
 8534:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 8535: # Attempt to restore parameters from last session, set defaults if not present
 8536:     my %Saveable_Parameters=&clicker_grading_parameters();
 8537:     &Apache::loncommon::restore_course_settings('grades_clicker',
 8538:                                                  \%Saveable_Parameters);
 8539:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 8540:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 8541:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 8542:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 8543: 
 8544:     my %checked;
 8545:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
 8546:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 8547:           $checked{$gradingmechanism}="checked='checked'";
 8548:        }
 8549:     }
 8550: 
 8551:     my $upload=&mt("Upload File");
 8552:     my $type=&mt("Type");
 8553:     my $attendance=&mt("Award points just for participation");
 8554:     my $personnel=&mt("Correctness determined from response by course personnel");
 8555:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 8556:     my $given=&mt("Correctness determined from given list of answers").' '.
 8557:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
 8558:     my $pcorrect=&mt("Percentage points for correct solution");
 8559:     my $pincorrect=&mt("Percentage points for incorrect solution");
 8560:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 8561: 						   ('iclicker' => 'i>clicker',
 8562:                                                     'interwrite' => 'interwrite PRS'));
 8563:     $symb = &Apache::lonenc::check_encrypt($symb);
 8564:     $result.=<<ENDUPFORM;
 8565: <script type="text/javascript">
 8566: function sanitycheck() {
 8567: // Accept only integer percentages
 8568:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 8569:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 8570: // Find out grading choice
 8571:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8572:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 8573:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 8574:       }
 8575:    }
 8576: // By default, new choice equals user selection
 8577:    newgradingchoice=gradingchoice;
 8578: // Not good to give more points for false answers than correct ones
 8579:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 8580:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 8581:    }
 8582: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 8583:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 8584:       document.forms.gradesupload.pcorrect.value=100;
 8585:       document.forms.gradesupload.pincorrect.value=100;
 8586:    }
 8587: // If the values are different, cannot be attendance only
 8588:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 8589:        (gradingchoice=='attendance')) {
 8590:        newgradingchoice='personnel';
 8591:    }
 8592: // Change grading choice to new one
 8593:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 8594:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 8595:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 8596:       } else {
 8597:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 8598:       }
 8599:    }
 8600: // Remember the old state
 8601:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 8602: }
 8603: </script>
 8604: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 8605: <input type="hidden" name="symb" value="$symb" />
 8606: <input type="hidden" name="command" value="processclickerfile" />
 8607: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8608: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8609: <input type="file" name="upfile" size="50" />
 8610: <br /><label>$type: $selectform</label>
 8611: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 8612: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 8613: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 8614: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 8615: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
 8616: <br />&nbsp;&nbsp;&nbsp;
 8617: <input type="text" name="givenanswer" size="50" />
 8618: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 8619: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 8620: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 8621: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 8622: </form>
 8623: ENDUPFORM
 8624:     $result.='</td></tr></table>'."\n".
 8625:              '</td></tr></table><br /><br />'."\n";
 8626:     $result.=&show_grading_menu_form($symb);
 8627:     return $result;
 8628: }
 8629: 
 8630: sub process_clicker_file {
 8631:     my ($r)=@_;
 8632:     my ($symb)=&get_symb($r);
 8633:     if (!$symb) {return '';}
 8634: 
 8635:     my %Saveable_Parameters=&clicker_grading_parameters();
 8636:     &Apache::loncommon::store_course_settings('grades_clicker',
 8637:                                               \%Saveable_Parameters);
 8638: 
 8639:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8640:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 8641: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 8642: 	return $result.&show_grading_menu_form($symb);
 8643:     }
 8644:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
 8645:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
 8646:         return $result.&show_grading_menu_form($symb);
 8647:     }
 8648:     my $foundgiven=0;
 8649:     if ($env{'form.gradingmechanism'} eq 'given') {
 8650:         $env{'form.givenanswer'}=~s/^\s*//gs;
 8651:         $env{'form.givenanswer'}=~s/\s*$//gs;
 8652:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
 8653:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
 8654:         my @answers=split(/\,/,$env{'form.givenanswer'});
 8655:         $foundgiven=$#answers+1;
 8656:     }
 8657:     my %clicker_ids=&gather_clicker_ids();
 8658:     my %correct_ids;
 8659:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 8660: 	%correct_ids=&gather_adv_clicker_ids();
 8661:     }
 8662:     if ($env{'form.gradingmechanism'} eq 'specific') {
 8663: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 8664: 	   $correct_id=~tr/a-z/A-Z/;
 8665: 	   $correct_id=~s/\s//gs;
 8666: 	   $correct_id=~s/^[\#0]+//;
 8667:            $correct_id=~s/[\-\:]//g;
 8668:            if ($correct_id) {
 8669: 	      $correct_ids{$correct_id}='specified';
 8670:            }
 8671:         }
 8672:     }
 8673:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 8674: 	$result.=&mt('Score based on attendance only');
 8675:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
 8676:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
 8677:     } else {
 8678: 	my $number=0;
 8679: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 8680: 	foreach my $id (sort(keys(%correct_ids))) {
 8681: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 8682: 	    if ($correct_ids{$id} eq 'specified') {
 8683: 		$result.=&mt('specified');
 8684: 	    } else {
 8685: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 8686: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 8687: 	    }
 8688: 	    $number++;
 8689: 	}
 8690:         $result.="</p>\n";
 8691: 	if ($number==0) {
 8692: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 8693: 	    return $result.&show_grading_menu_form($symb);
 8694: 	}
 8695:     }
 8696:     if (length($env{'form.upfile'}) < 2) {
 8697:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 8698: 		     '<span class="LC_error">',
 8699: 		     '</span>',
 8700: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 8701:         return $result.&show_grading_menu_form($symb);
 8702:     }
 8703: 
 8704: # Were able to get all the info needed, now analyze the file
 8705: 
 8706:     $result.=&Apache::loncommon::studentbrowser_javascript();
 8707:     $symb = &Apache::lonenc::check_encrypt($symb);
 8708:     my $heading=&mt('Scanning clicker file');
 8709:     $result.=(<<ENDHEADER);
 8710: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8711: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8712: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8713: <form method="post" action="/adm/grades" name="clickeranalysis">
 8714: <input type="hidden" name="symb" value="$symb" />
 8715: <input type="hidden" name="command" value="assignclickergrades" />
 8716: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 8717: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 8718: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 8719: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 8720: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 8721: ENDHEADER
 8722:     if ($env{'form.gradingmechanism'} eq 'given') {
 8723:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
 8724:     } 
 8725:     my %responses;
 8726:     my @questiontitles;
 8727:     my $errormsg='';
 8728:     my $number=0;
 8729:     if ($env{'form.upfiletype'} eq 'iclicker') {
 8730: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 8731:     }
 8732:     if ($env{'form.upfiletype'} eq 'interwrite') {
 8733:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 8734:     }
 8735:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 8736:              '<input type="hidden" name="number" value="'.$number.'" />'.
 8737:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 8738:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 8739:              '<br />';
 8740:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
 8741:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
 8742:        return $result.&show_grading_menu_form($symb);
 8743:     } 
 8744: # Remember Question Titles
 8745: # FIXME: Possibly need delimiter other than ":"
 8746:     for (my $i=0;$i<$number;$i++) {
 8747:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 8748:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 8749:     }
 8750:     my $correct_count=0;
 8751:     my $student_count=0;
 8752:     my $unknown_count=0;
 8753: # Match answers with usernames
 8754: # FIXME: Possibly need delimiter other than ":"
 8755:     foreach my $id (keys(%responses)) {
 8756:        if ($correct_ids{$id}) {
 8757:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 8758:           $correct_count++;
 8759:        } elsif ($clicker_ids{$id}) {
 8760:           if ($clicker_ids{$id}=~/\,/) {
 8761: # More than one user with the same clicker!
 8762:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 8763:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8764:                            "<select name='multi".$id."'>";
 8765:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 8766:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 8767:              }
 8768:              $result.='</select>';
 8769:              $unknown_count++;
 8770:           } else {
 8771: # Good: found one and only one user with the right clicker
 8772:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 8773:              $student_count++;
 8774:           }
 8775:        } else {
 8776:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 8777:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 8778:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 8779:                    "\n".&mt("Domain").": ".
 8780:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 8781:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 8782:           $unknown_count++;
 8783:        }
 8784:     }
 8785:     $result.='<hr />'.
 8786:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 8787:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
 8788:        if ($correct_count==0) {
 8789:           $errormsg.="Found no correct answers answers for grading!";
 8790:        } elsif ($correct_count>1) {
 8791:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 8792:        }
 8793:     }
 8794:     if ($number<1) {
 8795:        $errormsg.="Found no questions.";
 8796:     }
 8797:     if ($errormsg) {
 8798:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 8799:     } else {
 8800:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 8801:     }
 8802:     $result.='</form></td></tr></table>'."\n".
 8803:              '</td></tr></table><br /><br />'."\n";
 8804:     return $result.&show_grading_menu_form($symb);
 8805: }
 8806: 
 8807: sub iclicker_eval {
 8808:     my ($questiontitles,$responses)=@_;
 8809:     my $number=0;
 8810:     my $errormsg='';
 8811:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8812:         my %components=&Apache::loncommon::record_sep($line);
 8813:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8814: 	if ($entries[0] eq 'Question') {
 8815: 	    for (my $i=3;$i<$#entries;$i+=6) {
 8816: 		$$questiontitles[$number]=$entries[$i];
 8817: 		$number++;
 8818: 	    }
 8819: 	}
 8820: 	if ($entries[0]=~/^\#/) {
 8821: 	    my $id=$entries[0];
 8822: 	    my @idresponses;
 8823: 	    $id=~s/^[\#0]+//;
 8824: 	    for (my $i=0;$i<$number;$i++) {
 8825: 		my $idx=3+$i*6;
 8826: 		push(@idresponses,$entries[$idx]);
 8827: 	    }
 8828: 	    $$responses{$id}=join(',',@idresponses);
 8829: 	}
 8830:     }
 8831:     return ($errormsg,$number);
 8832: }
 8833: 
 8834: sub interwrite_eval {
 8835:     my ($questiontitles,$responses)=@_;
 8836:     my $number=0;
 8837:     my $errormsg='';
 8838:     my $skipline=1;
 8839:     my $questionnumber=0;
 8840:     my %idresponses=();
 8841:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 8842:         my %components=&Apache::loncommon::record_sep($line);
 8843:         my @entries=map {$components{$_}} (sort(keys(%components)));
 8844:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 8845:         if ($entries[1] eq 'Response') { $skipline=1; }
 8846:         next if $skipline;
 8847:         if ($entries[0]!=$questionnumber) {
 8848:            $questionnumber=$entries[0];
 8849:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 8850:            $number++;
 8851:         }
 8852:         my $id=$entries[4];
 8853:         $id=~s/^[\#0]+//;
 8854:         $id=~s/^v\d*\://i;
 8855:         $id=~s/[\-\:]//g;
 8856:         $idresponses{$id}[$number]=$entries[6];
 8857:     }
 8858:     foreach my $id (keys(%idresponses)) {
 8859:        $$responses{$id}=join(',',@{$idresponses{$id}});
 8860:        $$responses{$id}=~s/^\s*\,//;
 8861:     }
 8862:     return ($errormsg,$number);
 8863: }
 8864: 
 8865: sub assign_clicker_grades {
 8866:     my ($r)=@_;
 8867:     my ($symb)=&get_symb($r);
 8868:     if (!$symb) {return '';}
 8869: # See which part we are saving to
 8870:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 8871: # FIXME: This should probably look for the first handgradeable part
 8872:     my $part=$$partlist[0];
 8873: # Start screen output
 8874:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 8875: 
 8876:     my $heading=&mt('Assigning grades based on clicker file');
 8877:     $result.=(<<ENDHEADER);
 8878: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 8879: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 8880: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 8881: ENDHEADER
 8882: # Get correct result
 8883: # FIXME: Possibly need delimiter other than ":"
 8884:     my @correct=();
 8885:     my $gradingmechanism=$env{'form.gradingmechanism'};
 8886:     my $number=$env{'form.number'};
 8887:     if ($gradingmechanism ne 'attendance') {
 8888:        foreach my $key (keys(%env)) {
 8889:           if ($key=~/^form\.correct\:/) {
 8890:              my @input=split(/\,/,$env{$key});
 8891:              for (my $i=0;$i<=$#input;$i++) {
 8892:                  if (($correct[$i]) && ($input[$i]) &&
 8893:                      ($correct[$i] ne $input[$i])) {
 8894:                     $result.='<br /><span class="LC_warning">'.
 8895:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 8896:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 8897:                  } elsif ($input[$i]) {
 8898:                     $correct[$i]=$input[$i];
 8899:                  }
 8900:              }
 8901:           }
 8902:        }
 8903:        for (my $i=0;$i<$number;$i++) {
 8904:           if (!$correct[$i]) {
 8905:              $result.='<br /><span class="LC_error">'.
 8906:                       &mt('No correct result given for question "[_1]"!',
 8907:                           $env{'form.question:'.$i}).'</span>';
 8908:           }
 8909:        }
 8910:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 8911:     }
 8912: # Start grading
 8913:     my $pcorrect=$env{'form.pcorrect'};
 8914:     my $pincorrect=$env{'form.pincorrect'};
 8915:     my $storecount=0;
 8916:     foreach my $key (keys(%env)) {
 8917:        my $user='';
 8918:        if ($key=~/^form\.student\:(.*)$/) {
 8919:           $user=$1;
 8920:        }
 8921:        if ($key=~/^form\.unknown\:(.*)$/) {
 8922:           my $id=$1;
 8923:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 8924:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 8925:           } elsif ($env{'form.multi'.$id}) {
 8926:              $user=$env{'form.multi'.$id};
 8927:           }
 8928:        }
 8929:        if ($user) { 
 8930:           my @answer=split(/\,/,$env{$key});
 8931:           my $sum=0;
 8932:           my $realnumber=$number;
 8933:           for (my $i=0;$i<$number;$i++) {
 8934:              if ($answer[$i]) {
 8935:                 if ($gradingmechanism eq 'attendance') {
 8936:                    $sum+=$pcorrect;
 8937:                 } elsif ($answer[$i] eq '*') {
 8938:                    $sum+=$pcorrect;
 8939:                 } elsif ($answer[$i] eq '-') {
 8940:                    $realnumber--;
 8941:                 } else {
 8942:                    if ($answer[$i] eq $correct[$i]) {
 8943:                       $sum+=$pcorrect;
 8944:                    } else {
 8945:                       $sum+=$pincorrect;
 8946:                    }
 8947:                 }
 8948:              }
 8949:           }
 8950:           my $ave=$sum/(100*$realnumber);
 8951: # Store
 8952:           my ($username,$domain)=split(/\:/,$user);
 8953:           my %grades=();
 8954:           $grades{"resource.$part.solved"}='correct_by_override';
 8955:           $grades{"resource.$part.awarded"}=$ave;
 8956:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 8957:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 8958:                                                  $env{'request.course.id'},
 8959:                                                  $domain,$username);
 8960:           if ($returncode ne 'ok') {
 8961:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 8962:           } else {
 8963:              $storecount++;
 8964:           }
 8965:        }
 8966:     }
 8967: # We are done
 8968:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 8969:              '</td></tr></table>'."\n".
 8970:              '</td></tr></table><br /><br />'."\n";
 8971:     return $result.&show_grading_menu_form($symb);
 8972: }
 8973: 
 8974: sub handler {
 8975:     my $request=$_[0];
 8976:     &reset_caches();
 8977:     if ($env{'browser.mathml'}) {
 8978: 	&Apache::loncommon::content_type($request,'text/xml');
 8979:     } else {
 8980: 	&Apache::loncommon::content_type($request,'text/html');
 8981:     }
 8982:     $request->send_http_header;
 8983:     return '' if $request->header_only;
 8984:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8985:     my $symb=&get_symb($request,1);
 8986:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8987:     my $command=$commands[0];
 8988: 
 8989:     if ($#commands > 0) {
 8990: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8991:     }
 8992: 
 8993:     $ssi_error = 0;
 8994:     $request->print(&Apache::loncommon::start_page('Grading'));
 8995:     if ($symb eq '' && $command eq '') {
 8996: 	if ($env{'user.adv'}) {
 8997: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8998: 		($env{'form.codethree'})) {
 8999: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 9000: 		    $env{'form.codethree'};
 9001: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 9002: 		    &Apache::lonnet::checkin($token);
 9003: 		if ($tsymb) {
 9004: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 9005: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 9006: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
 9007: 					  ('grade_username' => $tuname,
 9008: 					   'grade_domain' => $tudom,
 9009: 					   'grade_courseid' => $tcrsid,
 9010: 					   'grade_symb' => $tsymb)));
 9011: 		    } else {
 9012: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 9013: 		    }
 9014: 		} else {
 9015: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 9016: 		}
 9017: 	    } else {
 9018: 		$request->print(&Apache::lonxml::tokeninputfield());
 9019: 	    }
 9020: 	}
 9021:     } else {
 9022: 	&init_perm();
 9023: 	if ($command eq 'submission' && $perm{'vgr'}) {
 9024: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 9025: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 9026: 	    &pickStudentPage($request);
 9027: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 9028: 	    &displayPage($request);
 9029: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 9030: 	    &updateGradeByPage($request);
 9031: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 9032: 	    &processGroup($request);
 9033: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 9034: 	    $request->print(&grading_menu($request));
 9035: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 9036: 	    $request->print(&submit_options($request));
 9037: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 9038: 	    $request->print(&viewgrades($request));
 9039: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 9040: 	    $request->print(&processHandGrade($request));
 9041: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 9042: 	    $request->print(&editgrades($request));
 9043: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 9044: 	    $request->print(&verifyreceipt($request));
 9045:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 9046:             $request->print(&process_clicker($request));
 9047:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 9048:             $request->print(&process_clicker_file($request));
 9049:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 9050:             $request->print(&assign_clicker_grades($request));
 9051: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 9052: 	    $request->print(&upcsvScores_form($request));
 9053: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 9054: 	    $request->print(&csvupload($request));
 9055: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 9056: 	    $request->print(&csvuploadmap($request));
 9057: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 9058: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 9059: 		$request->print(&csvuploadoptions($request));
 9060: 	    } else {
 9061: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 9062: 		    $env{'form.upfile_associate'} = 'reverse';
 9063: 		} else {
 9064: 		    $env{'form.upfile_associate'} = 'forward';
 9065: 		}
 9066: 		$request->print(&csvuploadmap($request));
 9067: 	    }
 9068: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 9069: 	    $request->print(&csvuploadassign($request));
 9070: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 9071: 	    $request->print(&scantron_selectphase($request));
 9072:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 9073:  	    $request->print(&scantron_do_warning($request));
 9074: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 9075: 	    $request->print(&scantron_validate_file($request));
 9076: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 9077: 	    $request->print(&scantron_process_students($request));
 9078:  	} elsif ($command eq 'scantronupload' && 
 9079:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9080: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9081:  	    $request->print(&scantron_upload_scantron_data($request)); 
 9082:  	} elsif ($command eq 'scantronupload_save' &&
 9083:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 9084: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 9085:  	    $request->print(&scantron_upload_scantron_data_save($request));
 9086:  	} elsif ($command eq 'scantron_download' &&
 9087: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 9088:  	    $request->print(&scantron_download_scantron_data($request));
 9089:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
 9090:             $request->print(&checkscantron_results($request));     
 9091: 	} elsif ($command) {
 9092: 	    $request->print("Access Denied ($command)");
 9093: 	}
 9094:     }
 9095:     if ($ssi_error) {
 9096: 	&ssi_print_error($request);
 9097:     }
 9098:     $request->print(&Apache::loncommon::end_page());
 9099:     &reset_caches();
 9100:     return '';
 9101: }
 9102: 
 9103: 1;
 9104: 
 9105: __END__;

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